David K. Bainbridge | df9df63 | 2016-07-07 18:47:46 -0700 | [diff] [blame^] | 1 | // Copyright 2016 Open Networking Laboratory |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
David K. Bainbridge | 97ee805 | 2016-06-14 00:52:07 -0700 | [diff] [blame] | 14 | package main |
| 15 | |
| 16 | import ( |
| 17 | "encoding/json" |
David K. Bainbridge | 97ee805 | 2016-06-14 00:52:07 -0700 | [diff] [blame] | 18 | "net/http" |
David K. Bainbridge | a9c2e0a | 2016-07-01 18:33:50 -0700 | [diff] [blame] | 19 | "strings" |
David K. Bainbridge | 97ee805 | 2016-06-14 00:52:07 -0700 | [diff] [blame] | 20 | ) |
| 21 | |
| 22 | type Vendors interface { |
| 23 | Switchq(mac string) (bool, error) |
| 24 | } |
| 25 | |
| 26 | type VendorRec struct { |
| 27 | Prefix string `json:"prefix"` |
| 28 | Vendor string `json:"vendor"` |
| 29 | Provision bool `json:"provision"` |
| 30 | } |
| 31 | |
| 32 | type VendorsData struct { |
| 33 | Vendors map[string]VendorRec |
| 34 | } |
| 35 | |
| 36 | func NewVendors(spec string) (Vendors, error) { |
| 37 | v := VendorsData{} |
| 38 | v.Vendors = make(map[string]VendorRec) |
| 39 | |
| 40 | t := &http.Transport{} |
| 41 | t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/"))) |
| 42 | c := &http.Client{Transport: t} |
| 43 | res, err := c.Get(spec) |
| 44 | if err != nil { |
| 45 | return nil, err |
| 46 | } |
| 47 | defer res.Body.Close() |
| 48 | |
| 49 | data := make([]VendorRec, 0) |
| 50 | decoder := json.NewDecoder(res.Body) |
| 51 | err = decoder.Decode(&data) |
| 52 | if err != nil { |
| 53 | return nil, err |
| 54 | } |
| 55 | for _, rec := range data { |
| 56 | v.Vendors[rec.Prefix] = rec |
| 57 | } |
David K. Bainbridge | a9c2e0a | 2016-07-01 18:33:50 -0700 | [diff] [blame] | 58 | log.Debugf("known vendors %+v", v.Vendors) |
David K. Bainbridge | 97ee805 | 2016-06-14 00:52:07 -0700 | [diff] [blame] | 59 | |
| 60 | return &v, nil |
| 61 | } |
| 62 | |
| 63 | func (v *VendorsData) Switchq(mac string) (bool, error) { |
| 64 | if len(mac) < 8 { |
| 65 | return false, nil |
| 66 | } |
| 67 | rec, ok := v.Vendors[strings.ToUpper(mac[0:8])] |
| 68 | if !ok || !rec.Provision { |
| 69 | return false, nil |
| 70 | } |
| 71 | |
| 72 | return true, nil |
| 73 | } |