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