Debian Codegraph @

tor/tor.go

raw symbols SCIP
1 package tor
2
3 import (
4 "context"
5 "fmt"
6 "io"
7 "io/ioutil"
8 "net/textproto"
9 "os"
10 "path/filepath"
11 "strconv"
12 "time"
13
14 "github.com/cretz/bine/control"
15
16 "github.com/cretz/bine/process"
17 )
18
19 // Tor is the wrapper around the Tor process and control port connection. It
20 // should be created with Start and developers should always call Close when
21 // done.
22 type Tor struct {
23 // Process is the Tor instance that is running.
24 Process process.Process
25
26 // Control is the Tor controller connection.
27 Control *control.Conn
28
29 // ProcessCancelFunc is the context cancellation func for the Tor process.
30 // It is used by Close and should not be called directly. This can be nil.
31 ProcessCancelFunc context.CancelFunc
32
33 // ControlPort is the port that Control is connected on. It is 0 if the
34 // connection is an embedded control connection.
35 ControlPort int
36
37 // DataDir is the path to the data directory that Tor is using.
38 DataDir string
39
40 // DeleteDataDirOnClose is true if, when Close is invoked, the entire
41 // directory will be deleted.
42 DeleteDataDirOnClose bool
43
44 // DebugWriter is the writer used for debug logs, or nil if debug logs
45 // should not be emitted.
46 DebugWriter io.Writer
47
48 // StopProcessOnClose, if true, will attempt to halt the process on close.
49 StopProcessOnClose bool
50
51 // GeoIPCreatedFile is the path, relative to DataDir, that was created from
52 // StartConf.GeoIPFileReader. It is empty if no file was created.
53 GeoIPCreatedFile string
54
55 // GeoIPv6CreatedFile is the path, relative to DataDir, that was created
56 // from StartConf.GeoIPFileReader. It is empty if no file was created.
57 GeoIPv6CreatedFile string
58 }
59
60 // StartConf is the configuration used for Start when starting a Tor instance. A
61 // default instance with no fields set is the default used for Start.
62 type StartConf struct {
63 // ExePath is the path to the Tor executable. If it is not present, "tor" is
64 // used either locally or on the PATH. This is ignored if ProcessCreator is
65 // set.
66 ExePath string
67
68 // ProcessCreator is the override to use a specific process creator. If set,
69 // ExePath is ignored.
70 ProcessCreator process.Creator
71
72 // UseEmbeddedControlConn can be set to true to use
73 // process.Process.EmbeddedControlConn() instead of creating a connection
74 // via ControlPort. Note, this only works when ProcessCreator is an
75 // embedded Tor creator with version >= 0.3.5.x.
76 UseEmbeddedControlConn bool
77
78 // ControlPort is the port to use for the Tor controller. If it is 0, Tor
79 // picks a port for use. This is ignored if UseEmbeddedControlConn is true.
80 ControlPort int
81
82 // DataDir is the directory used by Tor. If it is empty, a temporary
83 // directory is created in TempDataDirBase.
84 DataDir string
85
86 // TempDataDirBase is the parent directory that a temporary data directory
87 // will be created under for use by Tor. This is ignored if DataDir is not
88 // empty. If empty it is assumed to be the current working directory.
89 TempDataDirBase string
90
91 // RetainTempDataDir, if true, will not set the created temporary data
92 // directory to be deleted on close. This is ignored if DataDir is not
93 // empty.
94 RetainTempDataDir bool
95
96 // DisableCookieAuth, if true, will not use the default SAFECOOKIE
97 // authentication mechanism for the Tor controller.
98 DisableCookieAuth bool
99
100 // DisableEagerAuth, if true, will not authenticate on Start.
101 DisableEagerAuth bool
102
103 // EnableNetwork, if true, will connect to the wider Tor network on start.
104 EnableNetwork bool
105
106 // ExtraArgs is the set of extra args passed to the Tor instance when
107 // started.
108 ExtraArgs []string
109
110 // TorrcFile is the torrc file to set on start. If empty, a blank torrc is
111 // created in the data directory and is used instead.
112 TorrcFile string
113
114 // DebugWriter is the writer to use for debug logs, or nil for no debug
115 // logs.
116 DebugWriter io.Writer
117
118 // NoHush if true does not set --hush. By default --hush is set.
119 NoHush bool
120
121 // NoAutoSocksPort if true does not set "--SocksPort auto" as is done by
122 // default. This means the caller could set their own or just let it
123 // default to 9050.
124 NoAutoSocksPort bool
125
126 // GeoIPReader, if present, is called before start to copy geo IP files to
127 // the data directory. Errors are propagated. If the ReadCloser is present,
128 // it is copied to the data dir, overwriting as necessary, and then closed
129 // and the appropriate command line argument is added to reference it. If
130 // both the ReadCloser and error are nil, no copy or command line argument
131 // is used for that version. This is called twice, once with false and once
132 // with true for ipv6.
133 //
134 // This can be set to torutil/geoipembed.GeoIPReader to use an embedded
135 // source.
136 GeoIPFileReader func(ipv6 bool) (io.ReadCloser, error)
137 }
138
139 // Start a Tor instance and connect to it. If ctx is nil, context.Background()
140 // is used. If conf is nil, a default instance is used.
141 func Start(ctx context.Context, conf *StartConf) (*Tor, error) {
142 if ctx == nil {
143 ctx = context.Background()
144 }
145 if conf == nil {
146 conf = &StartConf{}
147 }
148 tor := &Tor{DataDir: conf.DataDir, DebugWriter: conf.DebugWriter, StopProcessOnClose: true}
149 // Create the data dir and make it absolute
150 if tor.DataDir == "" {
151 tempBase := conf.TempDataDirBase
152 if tempBase == "" {
153 tempBase = "."
154 }
155 var err error
156 if tempBase, err = filepath.Abs(tempBase); err != nil {
157 return nil, err
158 }
159 if tor.DataDir, err = ioutil.TempDir(tempBase, "data-dir-"); err != nil {
160 return nil, fmt.Errorf("Unable to create temp data dir: %v", err)
161 }
162 tor.Debugf("Created temp data directory at: %v", tor.DataDir)
163 tor.DeleteDataDirOnClose = !conf.RetainTempDataDir
164 } else if err := os.MkdirAll(tor.DataDir, 0700); err != nil {
165 return nil, fmt.Errorf("Unable to create data dir: %v", err)
166 }
167
168 // !!!! From this point on, we must close tor if we error !!!!
169
170 // Copy geoip stuff if necessary
171 err := tor.copyGeoIPFiles(conf)
172 // Start tor
173 if err == nil {
174 err = tor.startProcess(ctx, conf)
175 }
176 // Connect the controller
177 if err == nil {
178 err = tor.connectController(ctx, conf)
179 }
180 // Attempt eager auth w/ no password
181 if err == nil && !conf.DisableEagerAuth {
182 err = tor.Control.Authenticate("")
183 }
184 // If there was an error, we have to try to close here but it may leave the process open
185 if err != nil {
186 if closeErr := tor.Close(); closeErr != nil {
187 err = fmt.Errorf("Error on start: %v (also got error trying to close: %v)", err, closeErr)
188 }
189 }
190 return tor, err
191 }
192
193 func (t *Tor) copyGeoIPFiles(conf *StartConf) error {
194 if conf.GeoIPFileReader == nil {
195 return nil
196 }
197 if r, err := conf.GeoIPFileReader(false); err != nil {
198 return fmt.Errorf("Unable to read geoip file: %v", err)
199 } else if r != nil {
200 t.GeoIPCreatedFile = "geoip"
201 if err := createFile(filepath.Join(t.DataDir, "geoip"), r); err != nil {
202 return fmt.Errorf("Unable to create geoip file: %v", err)
203 }
204 }
205 if r, err := conf.GeoIPFileReader(true); err != nil {
206 return fmt.Errorf("Unable to read geoip6 file: %v", err)
207 } else if r != nil {
208 t.GeoIPv6CreatedFile = "geoip6"
209 if err := createFile(filepath.Join(t.DataDir, "geoip6"), r); err != nil {
210 return fmt.Errorf("Unable to create geoip6 file: %v", err)
211 }
212 }
213 return nil
214 }
215
216 func createFile(to string, from io.ReadCloser) error {
217 f, err := os.Create(to)
218 if err == nil {
219 _, err = io.Copy(f, from)
220 if closeErr := f.Close(); err == nil {
221 err = closeErr
222 }
223 }
224 if closeErr := from.Close(); err == nil {
225 err = closeErr
226 }
227 return err
228 }
229
230 func (t *Tor) startProcess(ctx context.Context, conf *StartConf) error {
231 // Get the creator
232 creator := conf.ProcessCreator
233 if creator == nil {
234 torPath := conf.ExePath
235 if torPath == "" {
236 torPath = "tor"
237 }
238 creator = process.NewCreator(torPath)
239 }
240 // Build the args
241 args := []string{"--DataDirectory", t.DataDir}
242 if !conf.DisableCookieAuth {
243 args = append(args, "--CookieAuthentication", "1")
244 }
245 if !conf.EnableNetwork {
246 args = append(args, "--DisableNetwork", "1")
247 }
248 if !conf.NoHush {
249 args = append(args, "--hush")
250 }
251 if !conf.NoAutoSocksPort {
252 args = append(args, "--SocksPort", "auto")
253 }
254 if t.GeoIPCreatedFile != "" {
255 args = append(args, "--GeoIPFile", filepath.Join(t.DataDir, t.GeoIPCreatedFile))
256 }
257 if t.GeoIPv6CreatedFile != "" {
258 args = append(args, "--GeoIPv6File", filepath.Join(t.DataDir, t.GeoIPv6CreatedFile))
259 }
260 // If there is no Torrc file, create a blank temp one
261 torrcFileName := conf.TorrcFile
262 if torrcFileName == "" {
263 torrcFile, err := ioutil.TempFile(t.DataDir, "torrc-")
264 if err != nil {
265 return err
266 }
267 torrcFileName = torrcFile.Name()
268 if err = torrcFile.Close(); err != nil {
269 return err
270 }
271 }
272 args = append(args, "-f", torrcFileName)
273 // Create file for Tor to write the control port to if it's not told to us and we're not embedded
274 var controlPortFileName string
275 var err error
276 if !conf.UseEmbeddedControlConn {
277 if conf.ControlPort == 0 {
278 controlPortFile, err := ioutil.TempFile(t.DataDir, "control-port-")
279 if err != nil {
280 return err
281 }
282 controlPortFileName = controlPortFile.Name()
283 if err = controlPortFile.Close(); err != nil {
284 return err
285 }
286 args = append(args, "--ControlPort", "auto", "--ControlPortWriteToFile", controlPortFile.Name())
287 } else {
288 args = append(args, "--ControlPort", strconv.Itoa(conf.ControlPort))
289 }
290 }
291 // Create process creator with args
292 var processCtx context.Context
293 processCtx, t.ProcessCancelFunc = context.WithCancel(ctx)
294 args = append(args, conf.ExtraArgs...)
295 p, err := creator.New(processCtx, args...)
296 if err != nil {
297 return err
298 }
299 // Use the embedded conn if requested
300 if conf.UseEmbeddedControlConn {
301 t.Debugf("Using embedded control connection")
302 conn, err := p.EmbeddedControlConn()
303 if err != nil {
304 return fmt.Errorf("Unable to get embedded control conn: %v", err)
305 }
306 t.Control = control.NewConn(textproto.NewConn(conn))
307 t.Control.DebugWriter = t.DebugWriter
308 }
309 // Start process with the args
310 t.Debugf("Starting tor with args %v", args)
311 if err = p.Start(); err != nil {
312 return err
313 }
314 t.Process = p
315 // If not embedded, try a few times to read the control port file if we need to
316 if !conf.UseEmbeddedControlConn {
317 t.ControlPort = conf.ControlPort
318 if t.ControlPort == 0 {
319 ControlPortCheck:
320 for i := 0; i < 10; i++ {
321 select {
322 case <-ctx.Done():
323 err = ctx.Err()
324 break ControlPortCheck
325 default:
326 // Try to read the controlport file, or wait a bit
327 var byts []byte
328 if byts, err = ioutil.ReadFile(controlPortFileName); err != nil {
329 break ControlPortCheck
330 } else if t.ControlPort, err = process.ControlPortFromFileContents(string(byts)); err == nil {
331 break ControlPortCheck
332 }
333 time.Sleep(200 * time.Millisecond)
334 }
335 }
336 if err != nil {
337 return fmt.Errorf("Unable to read control port file: %v", err)
338 }
339 }
340 }
341 return nil
342 }
343
344 func (t *Tor) connectController(ctx context.Context, conf *StartConf) error {
345 // This doesn't apply if already connected (e.g. using embedded conn)
346 if t.Control != nil {
347 return nil
348 }
349 t.Debugf("Connecting to control port %v", t.ControlPort)
350 textConn, err := textproto.Dial("tcp", "127.0.0.1:"+strconv.Itoa(t.ControlPort))
351 if err != nil {
352 return err
353 }
354 t.Control = control.NewConn(textConn)
355 t.Control.DebugWriter = t.DebugWriter
356 return nil
357 }
358
359 // EnableNetwork sets DisableNetwork to 0 and optionally waits for bootstrap to
360 // complete. The context can be nil. If DisableNetwork isnt 1, this does
361 // nothing.
362 func (t *Tor) EnableNetwork(ctx context.Context, wait bool) error {
363 if ctx == nil {
364 ctx = context.Background()
365 }
366 // Only enable if DisableNetwork is 1
367 if vals, err := t.Control.GetConf("DisableNetwork"); err != nil {
368 return err
369 } else if len(vals) == 0 || vals[0].Key != "DisableNetwork" || vals[0].Val != "1" {
370 return nil
371 }
372 // Enable the network
373 if err := t.Control.SetConf(control.KeyVals("DisableNetwork", "0")...); err != nil {
374 return nil
375 }
376 // If not waiting, leave
377 if !wait {
378 return nil
379 }
380 // Wait for progress to hit 100
381 _, err := t.Control.EventWait(ctx, []control.EventCode{control.EventCodeStatusClient},
382 func(evt control.Event) (bool, error) {
383 if status, _ := evt.(*control.StatusEvent); status != nil && status.Action == "BOOTSTRAP" {
384 if status.Severity == "NOTICE" && status.Arguments["PROGRESS"] == "100" {
385 return true, nil
386 } else if status.Severity == "ERR" {
387 return false, fmt.Errorf("Failing bootstrapping, Tor warning: %v", status.Arguments["WARNING"])
388 }
389 }
390 return false, nil
391 })
392 return err
393 }
394
395 // Close sends a halt to the Tor process if it can, closes the controller
396 // connection, and stops the process.
397 func (t *Tor) Close() error {
398 t.Debugf("Closing Tor")
399 errs := []error{}
400 // If controller is authenticated, send the quit signal to the process. Otherwise, just close the controller.
401 sentHalt := false
402 if t.Control != nil {
403 if t.Control.Authenticated && t.StopProcessOnClose {
404 if err := t.Control.Signal("HALT"); err != nil {
405 errs = append(errs, fmt.Errorf("Unable to signal halt: %v", err))
406 } else {
407 sentHalt = true
408 }
409 }
410 // Now close the controller
411 if err := t.Control.Close(); err != nil {
412 errs = append(errs, fmt.Errorf("Unable to close contrlller: %v", err))
413 } else {
414 t.Control = nil
415 }
416 }
417 if t.Process != nil {
418 // If we didn't halt, we have to force kill w/ the cancel func
419 if !sentHalt && t.StopProcessOnClose {
420 t.ProcessCancelFunc()
421 }
422 // Wait for a bit to make sure it stopped
423 errCh := make(chan error, 1)
424 var waitErr error
425 go func() { errCh <- t.Process.Wait() }()
426 select {
427 case waitErr = <-errCh:
428 if waitErr != nil {
429 errs = append(errs, fmt.Errorf("Process wait failed: %v", waitErr))
430 }
431 case <-time.After(300 * time.Millisecond):
432 errs = append(errs, fmt.Errorf("Process did not exit after 300 ms"))
433 }
434 if waitErr == nil {
435 t.Process = nil
436 }
437 }
438 // Get rid of the entire data dir
439 if t.DeleteDataDirOnClose {
440 if err := os.RemoveAll(t.DataDir); err != nil {
441 errs = append(errs, fmt.Errorf("Failed to remove data dir %v: %v", t.DataDir, err))
442 }
443 }
444 // Combine the errors if present
445 if len(errs) == 0 {
446 return nil
447 } else if len(errs) == 1 {
448 t.Debugf("Error while closing Tor: %v", errs[0])
449 return errs[0]
450 }
451 t.Debugf("Errors while closing Tor: %v", errs)
452 return fmt.Errorf("Got %v errors while closing - %v", len(errs), errs)
453 }