David K. Bainbridge | 97ee805 | 2016-06-14 00:52:07 -0700 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
David K. Bainbridge | 97ee805 | 2016-06-14 00:52:07 -0700 | [diff] [blame] | 5 | "net/http" |
David K. Bainbridge | a9c2e0a | 2016-07-01 18:33:50 -0700 | [diff] [blame] | 6 | "strings" |
David K. Bainbridge | 97ee805 | 2016-06-14 00:52:07 -0700 | [diff] [blame] | 7 | ) |
| 8 | |
| 9 | type Vendors interface { |
| 10 | Switchq(mac string) (bool, error) |
| 11 | } |
| 12 | |
| 13 | type VendorRec struct { |
| 14 | Prefix string `json:"prefix"` |
| 15 | Vendor string `json:"vendor"` |
| 16 | Provision bool `json:"provision"` |
| 17 | } |
| 18 | |
| 19 | type VendorsData struct { |
| 20 | Vendors map[string]VendorRec |
| 21 | } |
| 22 | |
| 23 | func NewVendors(spec string) (Vendors, error) { |
| 24 | v := VendorsData{} |
| 25 | v.Vendors = make(map[string]VendorRec) |
| 26 | |
| 27 | t := &http.Transport{} |
| 28 | t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/"))) |
| 29 | c := &http.Client{Transport: t} |
| 30 | res, err := c.Get(spec) |
| 31 | if err != nil { |
| 32 | return nil, err |
| 33 | } |
| 34 | defer res.Body.Close() |
| 35 | |
| 36 | data := make([]VendorRec, 0) |
| 37 | decoder := json.NewDecoder(res.Body) |
| 38 | err = decoder.Decode(&data) |
| 39 | if err != nil { |
| 40 | return nil, err |
| 41 | } |
| 42 | for _, rec := range data { |
| 43 | v.Vendors[rec.Prefix] = rec |
| 44 | } |
David K. Bainbridge | a9c2e0a | 2016-07-01 18:33:50 -0700 | [diff] [blame] | 45 | log.Debugf("known vendors %+v", v.Vendors) |
David K. Bainbridge | 97ee805 | 2016-06-14 00:52:07 -0700 | [diff] [blame] | 46 | |
| 47 | return &v, nil |
| 48 | } |
| 49 | |
| 50 | func (v *VendorsData) Switchq(mac string) (bool, error) { |
| 51 | if len(mac) < 8 { |
| 52 | return false, nil |
| 53 | } |
| 54 | rec, ok := v.Vendors[strings.ToUpper(mac[0:8])] |
| 55 | if !ok || !rec.Provision { |
| 56 | return false, nil |
| 57 | } |
| 58 | |
| 59 | return true, nil |
| 60 | } |