/
exec.go
105 lines (80 loc) · 2.07 KB
/
exec.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package producer
import (
"bufio"
"context"
"fmt"
"io"
"os"
"os/exec"
"github.com/RedTeamPentesting/monsoon/shell"
"golang.org/x/sync/errgroup"
)
// Exec runs a command and produces each line the command prints.
type Exec struct {
cmd string
}
// statically ensure that *Exec implements Source
var _ Source = &Exec{}
// NewFile creates a new producer from a reader. If seekable is set to false
// (e.g. for stdin), Yield() returns an error for subsequent runs.
func NewExec(cmd string) *Exec {
return &Exec{cmd: cmd}
}
// Yield runs the command and sends all lines printed by it to ch and the number
// of items to the channel count. Sending stops and ch and count are closed
// when an error occurs or the context is cancelled.
func (e *Exec) Yield(ctx context.Context, ch chan<- string, count chan<- int) (err error) {
defer close(ch)
defer close(count)
args, err := shell.Split(e.cmd)
if err != nil {
return fmt.Errorf("error splitting command %q: %w", e.cmd, err)
}
commandOutput, commandOutputWriter := io.Pipe()
cmd := exec.CommandContext(ctx, args[0], args[1:]...)
cmd.Stdout = commandOutputWriter
cmd.Stderr = os.Stderr
eg, localCtx := errgroup.WithContext(ctx)
eg.Go(func() error {
err := cmd.Run()
// close the writer, ignoring any errors
_ = commandOutputWriter.Close()
return err
})
eg.Go(func() error {
// io.Copy(os.Stdout, commandOutput)
num := 0
sc := bufio.NewScanner(commandOutput)
for sc.Scan() {
num++
select {
case <-localCtx.Done():
return nil
case ch <- sc.Text():
}
}
fmt.Printf("scanner: done, num %v\n", num)
select {
case <-localCtx.Done():
case count <- num:
}
fmt.Printf("scanner: done, err %v\n", sc.Err())
return sc.Err()
})
fmt.Printf("exec main, waiting\n")
err = eg.Wait()
fmt.Printf("exec main, done, err: %v\n", err)
return err
}
// allow testing an exec command early before setting up the producer.
func CheckExec(cmd string) error {
args, err := shell.Split(cmd)
if err != nil {
return err
}
_, err = exec.LookPath(args[0])
if err != nil {
return err
}
return nil
}