Skip to content

Commit

Permalink
feat(libtor): prevent concurrent calls
Browse files Browse the repository at this point in the history
  • Loading branch information
bassosimone committed Jan 15, 2024
1 parent 64f61ec commit 1ce69de
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions internal/libtor/enabled.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ import (
"os"
"runtime"
"sync"
"sync/atomic"

"github.com/cretz/bine/process"
"github.com/ooni/probe-cli/v3/internal/netxlite"
Expand Down Expand Up @@ -163,6 +164,10 @@ func (p *torProcess) Wait() (err error) {
return
}

// ErrConcurrentCalls indicates there have been concurrent libtor calls, which
// would lead to memory corruption inside of libtor.a.
var ErrConcurrentCalls = errors.New("libtor: another thread is already running tor")

// ErrTooManyArguments indicates that p.args contains too many arguments
var ErrTooManyArguments = errors.New("libtor: too many arguments")

Expand All @@ -172,6 +177,9 @@ var ErrCannotCreateControlSocket = errors.New("libtor: cannot create a control s
// ErrNonzeroExitCode indicates that tor returned a nonzero exit code
var ErrNonzeroExitCode = errors.New("libtor: command completed with nonzero exit code")

// concurrentCalls prevents concurrent libtor.a calls.
var concurrentCalls = &atomic.Int64{}

// runtor runs tor until completion and ensures that tor exits when
// the given ctx is cancelled or its deadline expires.
func (p *torProcess) runtor(ctx context.Context, cc net.Conn, args ...string) {
Expand All @@ -191,6 +199,13 @@ func (p *torProcess) runtor(ctx context.Context, cc net.Conn, args ...string) {
return
}

// make sure we're not going to have actual concurrent calls.
if !concurrentCalls.CompareAndSwap(0, 1) {
p.startErr <- ErrConcurrentCalls // nonblocking channel
return
}
defer concurrentCalls.Store(0)

// Note: when writing this code I was wondering whether I needed to
// use unsafe.Pointer to track pointers that matter to C code. Reading
// this message[1] has been useful to understand that the most likely
Expand Down

0 comments on commit 1ce69de

Please sign in to comment.