-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.go
More file actions
384 lines (300 loc) · 8.59 KB
/
app.go
File metadata and controls
384 lines (300 loc) · 8.59 KB
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
package extcap
import (
"errors"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
const (
defaultHelpPage = "https://github.com/kor44/extcap"
)
// App is the main structure of a extcap application.
type App struct {
// Application brief description
Description string
// HelpPage is link to help page with description. Can be link to file or URL
// Examples:
// file:///C:/Program%20Files/Wireshark/sshdump.html
// http://desowin.org/usbpcap/
HelpPage string
// Version of tool
Version string
// AdditionalVersion is used to show verbose version of tool when provided flag -v (--version).
// In case of empty, Version value will be used.
AdditionalVersion string
// CaptureExamples allows add more examples in usage section of help
// By default usage examples include following common examples:
// <application-name> --extcap-interfaces
// <application-name> --extcap-dlts --extcap-interface <iface-name>
// <application-name> --extcap-config --extcap-interface <iface-name>
// <application-name> --capture --extcap-interface <iface-name> --fifo <fifo_name>
CaptureExamples []string
// ListInterfaces returns list of intefaces. If not implements it will use name of executable (without extension) and HelpPage
// Result will be used by Wireshark to display in list of available interfaces to capture
ListInterfaces func() ([]Interface, error)
// ListLinkType returns LinkType (DLT) for given interface. Optional.
// If not defined, then return LinkType=147
// dlt {number=147}{name=<iface_name>}{display=Capture dependent DLT}
ListLinkType func(iface string) (LinkType, error)
// ListArgs returns configuration parameters for given interface. Optional.
ListArgs func(iface string) ([]Arg, error)
// StartCapture starts capture process. Required.
// Before capture extcap open pipe with function OpenPipe and return writer.
StartCapture func(iface string, w io.WriteCloser, filter string, args *CaptureArgs) error
// OpenPipe opens fifo pipe to write capture results. If it not defined then default is used.
OpenPipe func(string) (io.WriteCloser, error)
// Base options. See extcap-base.h
/*listIfacesFlag *bool
versionFlag *string
listDLTsFlag *bool
listIfaceCfgFlag *bool
startCaptureFlag *bool
ifaceFlag *string
filterFlag *string
fifoFlag *string
*/
/* need implement
log-level
log-file
*/
// add writer for dubug
writer io.Writer
}
// Run creates application with minimal necessary functionality
// in case there are no interfaces and interface configuration options.
func Run(desc string, captureFunc func(fifo io.WriteCloser, filter string) error) error {
app := &App{
Description: desc,
StartCapture: func(iface string, fifo io.WriteCloser, filter string, argSet *CaptureArgs) error {
return captureFunc(fifo, filter)
},
}
return app.Run(os.Args)
}
func (app *App) init() {
if app.ListInterfaces == nil {
app.ListInterfaces = func() ([]Interface, error) {
name := os.Args[0]
iface := Interface{
Value: strings.TrimSuffix(filepath.Base(name), filepath.Ext(name)),
Display: app.Description,
}
return []Interface{iface}, nil
}
}
if app.ListLinkType == nil {
app.ListLinkType = func(iface string) (LinkType, error) {
//dlt {number=147}{name=<iface_name>}{display=Capture dependent DLT}
return LinkType{147, iface, "Capture dependent DLT"}, nil
}
}
if app.OpenPipe == nil {
app.OpenPipe = openPipe
}
if app.Version == "" {
app.Version = "0.0.0"
}
if app.AdditionalVersion == "" {
app.AdditionalVersion = app.Version
}
if app.writer == nil {
app.writer = os.Stdout
}
}
// Runs main loop application
func (app *App) Run(args []string) error {
app.init()
if len(args) == 1 {
// print help
fmt.Fprintf(app.writer, app.help())
return nil
}
// TODO: need parse commands order insensitive
command := args[1]
switch command {
case "-v", "--version":
fmt.Fprintln(app.writer, app.AdditionalVersion)
return nil
case "-h", "--help":
fmt.Fprintf(app.writer, app.help())
return nil
// list the extcap Interfaces
case "--extcap-interfaces":
return app.cmdListInterfaces()
// list the additional configuration for an interface
case "--extcap-config":
if len(args[2:]) < 2 {
return NewError("show interface config", ErrNoInterfaceSpecified)
}
return app.cmdListIfaceArgs(args[2:])
// list the DLTs
case "--extcap-dlts":
if len(args[2:]) < 2 {
return NewError("show interface DLTs", ErrNoInterfaceSpecified)
}
return app.cmdListLinkTypes(args[2:])
// run the capture
case "--capture":
cfg, remainArgs, err := parseCommonStartCaptureFlags(args[2:])
if err != nil {
return NewError("extcap capture", err)
}
return app.cmdStartCapture(cfg, remainArgs)
// print tool version for extcap
case "--extcap-version":
return app.cmdPrintToolVersion()
}
return fmt.Errorf(`Invalid option: '%s'`, command)
}
func parseInterfaceName(args []string) (string, error) {
if len(args) < 2 {
return "", fmt.Errorf(`Not enough input parameters: "%s".\nExpected: "--extcap-interface <iface-name>"`,
strings.Join(args, " "))
}
if args[0] != "--extcap-interface" {
return "", ErrNoInterfaceSpecified
}
return args[1], nil
}
func (app *App) cmdListInterfaces() error {
ifaces, err := app.ListInterfaces()
if err != nil {
return err
}
fmt.Fprintln(app.writer, versionString(app.Version, app.HelpPage))
for i := range ifaces {
_, err := fmt.Fprintln(app.writer, ifaces[i].marshal())
if err != nil {
return fmt.Errorf("print interfaces: %w", err)
}
}
return nil
}
func (app *App) cmdListLinkTypes(args []string) error {
iface, err := parseInterfaceName(args)
if err != nil {
return err
}
dlt, err := app.ListLinkType(iface)
if err != nil {
return err
}
if _, err = fmt.Fprintln(app.writer, dlt.marshal()); err != nil {
return NewError("print link types", err)
}
return nil
}
func (app *App) cmdListIfaceArgs(args []string) error {
if app.ListArgs == nil {
return nil
}
iface, err := parseInterfaceName(args)
if err != nil {
return err
}
confOpts, err := app.ListArgs(iface)
if err != nil {
return err
}
for i := range confOpts {
confOpts[i].setID(i)
_, err = fmt.Fprintln(app.writer, argString(confOpts[i]))
if err != nil {
return NewError("print interface arguments", err)
}
}
return nil
}
// return help page string
func (app *App) help() string {
w := new(strings.Builder)
fmt.Fprintf(w, "%s - %s\n\n", os.Args[0], app.AdditionalVersion)
fmt.Fprintf(w, "Usage:\n%s\n", strings.Join(app.CaptureExamples, "\n"))
//fmt.Fprintf(w, "Options:%s", app.)
return w.String()
}
type captureConfig struct {
iface string
fifo string
filter string
}
func parseCommonStartCaptureFlags(args []string) (captureConfig, []string, error) {
temp := make([]string, len(args))
copy(temp, args)
var cfg captureConfig
for i, v := range temp {
if v == "--extcap-interface" && i+1 < len(temp) {
cfg.iface = temp[i+1]
temp = append(temp[:i], temp[i+2:]...)
goto GET_FIFO
}
}
return captureConfig{}, args, ErrNoInterfaceSpecified
GET_FIFO:
for i, v := range temp {
if v == "--fifo" && i+1 < len(temp) {
cfg.fifo = temp[i+1]
temp = append(temp[:i], temp[i+2:]...)
goto GET_FILTER
}
}
return captureConfig{}, args, ErrNoPipeProvided
GET_FILTER:
for i, v := range temp {
if v == "--extcap-capture-filter" && i+1 < len(temp) {
cfg.filter = temp[i+1]
temp = append(temp[:i], temp[i+2:]...)
break
}
}
return cfg, temp, nil
}
type CaptureArgs struct {
fs *flag.FlagSet
flags []string
}
func (set *CaptureArgs) ParseArgs(args []Arg) error {
for _, a := range args {
a.addFlag(set)
}
return set.fs.Parse(set.flags)
}
// Exist check wheather flag for argument is provided or not
func (set *CaptureArgs) Exist(name string) bool {
f := "--" + name
for i := range set.flags {
if set.flags[i] == f {
return true
}
}
return false
}
func newCaptureArgs(flags []string) *CaptureArgs {
return &CaptureArgs{
fs: flag.NewFlagSet("capture", flag.ExitOnError),
flags: flags,
}
}
func (app *App) cmdStartCapture(cfg captureConfig, remainArgs []string) error {
pipe, err := app.OpenPipe(cfg.fifo)
if err != nil {
return err
}
argSet := newCaptureArgs(remainArgs)
err = app.StartCapture(cfg.iface, pipe, cfg.filter, argSet)
return err
}
func (app *App) cmdPrintToolVersion() error {
_, err := fmt.Fprintln(app.writer, versionString(app.Version, app.HelpPage))
return err
}
func openPipe(name string) (io.WriteCloser, error) {
pipe, err := os.OpenFile(name, os.O_WRONLY, os.ModeNamedPipe)
if err != nil {
return nil, NewError(fmt.Sprintf("open pipe:%s", name), errors.Unwrap(err))
}
return pipe, nil
}