-
Notifications
You must be signed in to change notification settings - Fork 0
/
tor.go
71 lines (60 loc) · 1.63 KB
/
tor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright (c) 2022 Vasiliy Vasilyuk. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tornado
import (
"bufio"
"bytes"
"context"
"fmt"
"os/exec"
"strings"
)
func launchBackgroundTorDemon(ctx context.Context, trc torrc) (cmd *exec.Cmd, err error) {
if ctx == nil {
panic("tornado: cannot create tor demon by nil context")
}
cmd = exec.CommandContext(ctx, "tor", "-f", trc.filename)
cmd.Dir = trc.dataDirectory
stdoutPipe, err := cmd.StderrPipe()
if err != nil {
const format = "failed to create stdout pipe for exec command %q: %v"
return nil, fmt.Errorf(format, cmd.String(), err)
}
defer stdoutPipe.Close()
if err := cmd.Start(); err != nil {
const format = "failed starting the command %q: %v"
return nil, fmt.Errorf(format, cmd.String(), err)
}
launchLog := bytes.NewBuffer(make([]byte, 0, 4096))
launched := make(chan error, 1)
go func() {
defer close(launched)
scanner := bufio.NewScanner(stdoutPipe)
for scanner.Scan() {
text := scanner.Text()
launchLog.WriteString(text)
if strings.Contains(text, "Bootstrapped 100%") {
return
}
}
if err := scanner.Err(); err != nil {
const format = "failed to scan text: %v"
launched <- fmt.Errorf(format, err)
return
}
launched <- cmd.Wait()
}()
select {
case <-ctx.Done():
err = ctx.Err()
case err = <-launched:
}
if err != nil {
const format = "failed running the command %q: %v" +
"\n\n# Torrc file:\n%s" +
"\n\n# Launch log:\n%s"
return nil, fmt.Errorf(format, cmd.String(), err, trc.torrc, launchLog.String())
}
return cmd, nil
}