Debian Codegraph @

process/process.go

raw symbols SCIP
1 // Package process is the low-level abstraction for a Tor instance.
2 //
3 // The standard use is to create a Creator with NewCreator and the path to the
4 // Tor executable. The child package 'embedded' can be used if Tor is statically
5 // linked in the binary. Most developers will prefer the tor package adjacent to
6 // this one for a higher level abstraction over the process and control port
7 // connection.
8 package process
9
10 import (
11 "context"
12 "fmt"
13 "net"
14 "os"
15 "os/exec"
16 "strconv"
17 "strings"
18
19 "github.com/cretz/bine/torutil"
20 )
21
22 // Process is the interface implemented by Tor processes.
23 type Process interface {
24 // Start starts the Tor process in the background and returns. It is
25 // analagous to os/exec.Cmd.Start.
26 Start() error
27 // Wait waits for the Tor process to exit and returns error if it was not a
28 // successful exit. It is analagous to os/exec.Cmd.Wait.
29 Wait() error
30 // ControlConn is used for statically linked, embedded processes to create
31 // a controller connection. For non-embedded processes or Tor versions that
32 // don't support embedded control connections, ErrControlConnUnsupported is
33 // returned. Note, this should only be called once per process before
34 // Start, and the connection does not need to be closed.
35 EmbeddedControlConn() (net.Conn, error)
36 }
37
38 // Creator is the interface for process creation.
39 type Creator interface {
40 New(ctx context.Context, args ...string) (Process, error)
41 }
42
43 type CmdCreatorFunc func(ctx context.Context, args ...string) (*exec.Cmd, error)
44
45 // NewCreator creates a Creator for external Tor process execution based on the
46 // given exe path.
47 func NewCreator(exePath string) Creator {
48 return CmdCreatorFunc(func(ctx context.Context, args ...string) (*exec.Cmd, error) {
49 cmd := exec.CommandContext(ctx, exePath, args...)
50 cmd.Stdout = os.Stdout
51 cmd.Stderr = os.Stderr
52 return cmd, nil
53 })
54 }
55
56 type exeProcess struct {
57 *exec.Cmd
58 }
59
60 func (c CmdCreatorFunc) New(ctx context.Context, args ...string) (Process, error) {
61 cmd, err := c(ctx, args...)
62 return &exeProcess{cmd}, err
63 }
64
65 // ErrControlConnUnsupported is returned by Process.EmbeddedControlConn when
66 // it is unsupported.
67 var ErrControlConnUnsupported = fmt.Errorf("Control conn not supported")
68
69 func (e *exeProcess) EmbeddedControlConn() (net.Conn, error) {
70 return nil, ErrControlConnUnsupported
71 }
72
73 // ControlPortFromFileContents reads a control port file that is written by Tor
74 // when ControlPortWriteToFile is set.
75 func ControlPortFromFileContents(contents string) (int, error) {
76 contents = strings.TrimSpace(contents)
77 _, port, ok := torutil.PartitionString(contents, ':')
78 if !ok || !strings.HasPrefix(contents, "PORT=") {
79 return 0, fmt.Errorf("Invalid port format: %v", contents)
80 }
81 return strconv.Atoi(port)
82 }