-
Notifications
You must be signed in to change notification settings - Fork 159
/
csv.go
95 lines (81 loc) · 2.27 KB
/
csv.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
/*
* NETCAP - Traffic Analysis Framework
* Copyright (c) 2017 Philipp Mieden <dreadl0ck [at] protonmail [dot] ch>
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package types
import (
"fmt"
"log"
"os"
"strings"
proto "github.com/golang/protobuf/proto"
"github.com/mgutz/ansi"
)
var (
selection []int
// UTC allows to print timestamp in the utc format
UTC bool
)
// CSV ensures that the type can be converted to comma separated values
// and provides access to the timestamp of the audit record
type CSV interface {
// returns CSV values
CSVRecord() []string
// returns CSV header fields
CSVHeader() []string
// used to retrieve the timestamp of the audit record for labeling
NetcapTimestamp() string
}
// selectFields returns an array with the inidices of the desired fields for selection
func selectFields(all []string, selection string) (s []int) {
var (
fields = strings.Split(selection, ",")
ok bool
)
s = make([]int, len(fields))
for i, val := range fields {
for index, name := range all {
if name == val {
s[i] = index
ok = true
break
}
}
if !ok {
fmt.Println("invalid field: ", ansi.Red+val+ansi.Reset)
fmt.Println("available fields: ", ansi.Yellow+strings.Join(all, ",")+ansi.Reset)
os.Exit(1)
}
ok = false
}
return s
}
// Select takes a proto.Message and sets the selection on the package level
func Select(msg proto.Message, vals string) {
if vals != "" && vals != " " {
if p, ok := msg.(CSV); ok {
selection = selectFields(p.CSVHeader(), vals)
} else {
log.Fatal("netcap type does not implement the types.CSV interface!")
}
}
}
// filter applies a selection if configured
func filter(in []string) []string {
if len(selection) == 0 {
return in
}
r := make([]string, len(selection))
for i, v := range selection {
r[i] = in[v]
}
return r
}