File: loader.go

package info (click to toggle)
termshark 2.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 1,800 kB
  • sloc: sh: 98; makefile: 9
file content (202 lines) | stat: -rw-r--r-- 4,344 bytes parent folder | download
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
// Copyright 2019-2021 Graham Clark. All rights reserved.  Use of this source
// code is governed by the MIT license that can be found in the LICENSE
// file.

package capinfo

import (
	"bytes"
	"context"
	"fmt"
	"os/exec"
	"sync"

	"github.com/gcla/gowid"
	"github.com/gcla/termshark/v2"
	"github.com/gcla/termshark/v2/pcap"
	log "github.com/sirupsen/logrus"
)

//======================================================================

var Goroutinewg *sync.WaitGroup

//======================================================================

type ILoaderCmds interface {
	Capinfo(pcap string) pcap.IPcapCommand
}

type commands struct{}

func MakeCommands() commands {
	return commands{}
}

var _ ILoaderCmds = commands{}

func (c commands) Capinfo(pcapfile string) pcap.IPcapCommand {
	args := []string{pcapfile}
	return &pcap.Command{
		Cmd: exec.Command(termshark.CapinfosBin(), args...),
	}
}

//======================================================================

type Loader struct {
	cmds ILoaderCmds

	SuppressErrors bool // if true, don't report process errors e.g. at shutdown

	mainCtx      context.Context // cancelling this cancels the dependent contexts
	mainCancelFn context.CancelFunc

	capinfoCtx      context.Context
	capinfoCancelFn context.CancelFunc

	capinfoCmd pcap.IPcapCommand
}

func NewLoader(cmds ILoaderCmds, ctx context.Context) *Loader {
	res := &Loader{
		cmds: cmds,
	}
	res.mainCtx, res.mainCancelFn = context.WithCancel(ctx)
	return res
}

func (c *Loader) StopLoad() {
	if c.capinfoCancelFn != nil {
		c.capinfoCancelFn()
	}
}

//======================================================================

type ICapinfoCallbacks interface {
	OnCapinfoData(data string)
	AfterCapinfoEnd(success bool)
}

func (c *Loader) StartLoad(pcap string, app gowid.IApp, cb ICapinfoCallbacks) {
	termshark.TrackedGo(func() {
		c.loadCapinfoAsync(pcap, app, cb)
	}, Goroutinewg)
}

func (c *Loader) loadCapinfoAsync(pcapf string, app gowid.IApp, cb ICapinfoCallbacks) {
	c.capinfoCtx, c.capinfoCancelFn = context.WithCancel(c.mainCtx)

	procChan := make(chan int)
	pid := 0

	defer func() {
		if pid == 0 {
			close(procChan)
		}
	}()

	c.capinfoCmd = c.cmds.Capinfo(pcapf)

	termChan := make(chan error)

	termshark.TrackedGo(func() {
		var err error
		cmd := c.capinfoCmd
		cancelledChan := c.capinfoCtx.Done()
		procChan := procChan
		state := pcap.NotStarted

		kill := func() {
			err := termshark.KillIfPossible(cmd)
			if err != nil {
				log.Infof("Did not kill tshark capinfos process: %v", err)
			}
		}

	loop:
		for {
			select {
			case err = <-termChan:
				state = pcap.Terminated
				if !c.SuppressErrors && err != nil {
					if _, ok := err.(*exec.ExitError); ok {
						cerr := gowid.WithKVs(termshark.BadCommand, map[string]interface{}{
							"command": c.capinfoCmd.String(),
							"error":   err,
						})
						pcap.HandleError(pcap.CapinfoCode, app, cerr, cb)
					}
				}

			case pid := <-procChan:
				procChan = nil
				if pid != 0 {
					state = pcap.Started
					if cancelledChan == nil {
						kill()
					}
				}

			case <-cancelledChan:
				cancelledChan = nil
				if state == pcap.Started {
					kill()
				}
			}

			if state == pcap.Terminated || (cancelledChan == nil && state == pcap.NotStarted) {
				break loop
			}
		}
	}, Goroutinewg)

	capinfoOut, err := c.capinfoCmd.StdoutReader()
	if err != nil {
		pcap.HandleError(pcap.CapinfoCode, app, err, cb)
		return
	}

	defer func() {
		cb.AfterCapinfoEnd(true)
	}()

	app.Run(gowid.RunFunction(func(app gowid.IApp) {
		pcap.HandleBegin(pcap.CapinfoCode, app, cb)
	}))
	defer func() {
		app.Run(gowid.RunFunction(func(app gowid.IApp) {
			pcap.HandleEnd(pcap.CapinfoCode, app, cb)
		}))
	}()

	err = c.capinfoCmd.Start()
	if err != nil {
		err = fmt.Errorf("Error starting capinfo %v: %v", c.capinfoCmd, err)
		pcap.HandleError(pcap.CapinfoCode, app, err, cb)
		return
	}

	log.Infof("Started capinfo command %v with pid %d", c.capinfoCmd, c.capinfoCmd.Pid())

	termshark.TrackedGo(func() {
		termChan <- c.capinfoCmd.Wait()
	}, Goroutinewg)

	pid = c.capinfoCmd.Pid()
	procChan <- pid

	buf := new(bytes.Buffer)
	buf.ReadFrom(capinfoOut)

	cb.OnCapinfoData(buf.String())

	c.capinfoCancelFn()
}

//======================================================================
// Local Variables:
// mode: Go
// fill-column: 78
// End: