| 1 | package network |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "fmt" |
| 6 | "strconv" |
| 7 | "strings" |
| 8 | "sync" |
| 9 | |
| 10 | "github.com/bettercap/bettercap/core" |
| 11 | ) |
| 12 | |
| 13 | type Meta struct { |
| 14 | sync.Mutex |
| 15 | m map[string]interface{} |
| 16 | } |
| 17 | |
| 18 | // we want to protect concurrent access to the Meta |
| 19 | // object so the m field needs to be unexported, this |
| 20 | // is to have it in JSON regardless. |
| 21 | type metaJSON struct { |
| 22 | Values map[string]interface{} `json:"values"` |
| 23 | } |
| 24 | |
| 25 | func NewMeta() *Meta { |
| 26 | return &Meta{ |
| 27 | m: make(map[string]interface{}), |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | func (m *Meta) MarshalJSON() ([]byte, error) { |
| 32 | m.Lock() |
| 33 | defer m.Unlock() |
| 34 | return json.Marshal(metaJSON{Values: m.m}) |
| 35 | } |
| 36 | |
| 37 | func (m *Meta) Set(name string, value interface{}) { |
| 38 | m.Lock() |
| 39 | defer m.Unlock() |
| 40 | m.m[name] = value |
| 41 | } |
| 42 | |
| 43 | func (m *Meta) Get(name string) interface{} { |
| 44 | m.Lock() |
| 45 | defer m.Unlock() |
| 46 | |
| 47 | if v, found := m.m[name]; found { |
| 48 | return v |
| 49 | } |
| 50 | return "" |
| 51 | } |
| 52 | |
| 53 | func (m *Meta) GetIntsWith(name string, with int, sorted bool) []int { |
| 54 | sints := strings.Split(m.Get(name).(string), ",") |
| 55 | ints := []int{with} |
| 56 | |
| 57 | for _, s := range sints { |
| 58 | n, err := strconv.Atoi(s) |
| 59 | if err == nil { |
| 60 | ints = append(ints, n) |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | return core.UniqueInts(ints, sorted) |
| 65 | } |
| 66 | |
| 67 | func (m *Meta) SetInts(name string, ints []int) { |
| 68 | list := make([]string, len(ints)) |
| 69 | for i, n := range ints { |
| 70 | list[i] = fmt.Sprintf("%d", n) |
| 71 | } |
| 72 | |
| 73 | m.Set(name, strings.Join(list, ",")) |
| 74 | } |
| 75 | |
| 76 | func (m *Meta) GetOr(name string, dflt interface{}) interface{} { |
| 77 | m.Lock() |
| 78 | defer m.Unlock() |
| 79 | |
| 80 | if v, found := m.m[name]; found { |
| 81 | return v |
| 82 | } |
| 83 | return dflt |
| 84 | } |
| 85 | |
| 86 | func (m *Meta) Each(cb func(name string, value interface{})) { |
| 87 | m.Lock() |
| 88 | defer m.Unlock() |
| 89 | |
| 90 | for k, v := range m.m { |
| 91 | cb(k, v) |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | func (m *Meta) Empty() bool { |
| 96 | m.Lock() |
| 97 | defer m.Unlock() |
| 98 | return len(m.m) == 0 |
| 99 | } |