forked from unpoller/unifi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unifi.go
382 lines (306 loc) · 10.1 KB
/
unifi.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
// Package unifi provides a set of types to unload (unmarshal) Ubiquiti UniFi
// controller data. Also provided are methods to easily get data for devices -
// things like access points and switches, and for clients - the things
// connected to those access points and switches. As a bonus, each device and
// client type provided has an attached method to create InfluxDB datapoints.
package unifi
import (
"bytes"
"context"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"time"
"golang.org/x/net/publicsuffix"
)
var (
ErrAuthenticationFailed = fmt.Errorf("authentication failed")
ErrInvalidStatusCode = fmt.Errorf("invalid status code from server")
ErrNoParams = fmt.Errorf("requested PUT with no parameters")
ErrInvalidSignature = fmt.Errorf("certificate signature does not match")
)
// NewUnifi creates a http.Client with authenticated cookies.
// Used to make additional, authenticated requests to the APIs.
// Start here.
func NewUnifi(config *Config) (*Unifi, error) {
jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
if err != nil {
return nil, fmt.Errorf("creating cookiejar: %w", err)
}
u := newUnifi(config, jar)
for i, cert := range config.SSLCert {
p, _ := pem.Decode(cert)
u.fingerprints[i] = fmt.Sprintf("%x", sha256.Sum256(p.Bytes))
}
if err := u.checkNewStyleAPI(); err != nil {
return u, err
}
if err := u.Login(); err != nil {
return u, err
}
if err := u.GetServerData(); err != nil {
return u, fmt.Errorf("unable to get server version: %w", err)
}
return u, nil
}
func newUnifi(config *Config, jar http.CookieJar) *Unifi {
config.URL = strings.TrimRight(config.URL, "/")
if config.ErrorLog == nil {
config.ErrorLog = discardLogs
}
if config.DebugLog == nil {
config.DebugLog = discardLogs
}
u := &Unifi{
Config: config,
Client: &http.Client{
Timeout: config.Timeout,
Jar: jar,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: !config.VerifySSL, // nolint: gosec
},
},
},
}
if len(config.SSLCert) > 0 {
u.fingerprints = make(fingerprints, len(config.SSLCert))
u.Client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true, // nolint: gosec
VerifyPeerCertificate: u.verifyPeerCertificate,
},
}
}
return u
}
func (u *Unifi) verifyPeerCertificate(certs [][]byte, chains [][]*x509.Certificate) error {
if len(u.fingerprints) == 0 {
return nil
}
for _, cert := range certs {
if u.fingerprints.Contains(fmt.Sprintf("%x", sha256.Sum256(cert))) {
return nil
}
}
return ErrInvalidSignature
}
// Login is a helper method. It can be called to grab a new authentication cookie.
func (u *Unifi) Login() error {
start := time.Now()
// magic login.
req, err := u.UniReq(APILoginPath, fmt.Sprintf(`{"username":"%s","password":"%s"}`, u.User, u.Pass))
if err != nil {
return err
}
resp, err := u.Do(req)
if err != nil {
return fmt.Errorf("making request: %w", err)
}
defer resp.Body.Close() // we need no data here.
_, _ = io.Copy(ioutil.Discard, resp.Body) // avoid leaking.
u.DebugLog("Requested %s: elapsed %v, returned %d bytes",
req.URL, time.Since(start).Round(time.Millisecond), resp.ContentLength)
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("(user: %s): %s (status: %s): %w",
u.User, req.URL, resp.Status, ErrAuthenticationFailed)
}
return nil
}
// Logout closes the current session.
func (u *Unifi) Logout() error {
// a post is needed for logout
_, err := u.PostJSON(APILogoutPath)
return err
}
// with the release of controller version 5.12.55 on UDM in Jan 2020 the api paths
// changed and broke this library. This function runs when `NewUnifi()` is called to
// check if this is a newer controller or not. If it is, we set new to true.
// Setting new to true makes the path() method return different (new) paths.
func (u *Unifi) checkNewStyleAPI() error {
var (
ctx = context.Background()
cancel func()
)
if u.Config.Timeout != 0 {
ctx, cancel = context.WithTimeout(ctx, u.Config.Timeout)
defer cancel()
}
u.DebugLog("Requesting %s/ to determine API paths", u.URL)
req, err := http.NewRequestWithContext(ctx, "GET", u.URL+"/", nil)
if err != nil {
return fmt.Errorf("creating request: %w", err)
}
// We can't share these cookies with other requests, so make a new client.
// Checking the return code on the first request so don't follow a redirect.
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: !u.VerifySSL}, // nolint: gosec
},
}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("making request: %w", err)
}
defer resp.Body.Close() // we need no data here.
_, _ = io.Copy(ioutil.Discard, resp.Body) // avoid leaking.
if resp.StatusCode == http.StatusOK {
// The new version returns a "200" for a / request.
u.new = true
u.DebugLog("Using NEW UniFi controller API paths for %s", req.URL)
}
// The old version returns a "302" (to /manage) for a / request
return nil
}
// GetServerData sets the controller's version and UUID. Only call this if you
// previously called Login and suspect the controller version has changed.
func (u *Unifi) GetServerData() error {
var response struct {
Data server `json:"meta"`
}
u.server = &response.Data
return u.GetData(APIStatusPath, &response)
}
// GetData makes a unifi request and unmarshals the response into a provided pointer.
func (u *Unifi) GetData(apiPath string, v interface{}, params ...string) error {
start := time.Now()
body, err := u.GetJSON(apiPath, params...)
if err != nil {
return err
}
u.DebugLog("Requested %s: elapsed %v, returned %d bytes",
u.URL+u.path(apiPath), time.Since(start).Round(time.Millisecond), len(body))
return json.Unmarshal(body, v)
}
// PutData makes a unifi request and unmarshals the response into a provided pointer.
func (u *Unifi) PutData(apiPath string, v interface{}, params ...string) error {
start := time.Now()
body, err := u.PutJSON(apiPath, params...)
if err != nil {
return err
}
u.DebugLog("Requested %s: elapsed %v, returned %d bytes",
u.URL+u.path(apiPath), time.Since(start).Round(time.Millisecond), len(body))
return json.Unmarshal(body, v)
}
// UniReq is a small helper function that adds an Accept header.
// Use this if you're unmarshalling UniFi data into custom types.
// And if you're doing that... sumbut a pull request with your new struct. :)
// This is a helper method that is exposed for convenience.
func (u *Unifi) UniReq(apiPath string, params string) (*http.Request, error) {
var (
req *http.Request
err error
)
switch apiPath = u.path(apiPath); params {
case "":
req, err = http.NewRequest(http.MethodGet, u.URL+apiPath, nil)
default:
req, err = http.NewRequest(http.MethodPost, u.URL+apiPath, bytes.NewBufferString(params))
}
if err != nil {
return nil, fmt.Errorf("creating request: %w", err)
}
u.setHeaders(req, params)
return req, nil
}
// UniReqPut is the Put call equivalent to UniReq.
func (u *Unifi) UniReqPut(apiPath string, params string) (*http.Request, error) {
if params == "" {
return nil, ErrNoParams
}
apiPath = u.path(apiPath)
req, err := http.NewRequest(http.MethodPut, u.URL+apiPath, bytes.NewBufferString(params)) //nolint:noctx
if err != nil {
return nil, fmt.Errorf("creating request: %w", err)
}
u.setHeaders(req, params)
return req, nil
}
// UniReqPost is the Post call equivalent to UniReq.
func (u *Unifi) UniReqPost(apiPath string, params string) (*http.Request, error) {
apiPath = u.path(apiPath)
req, err := http.NewRequest(http.MethodPost, u.URL+apiPath, bytes.NewBufferString(params)) //nolint:noctx
if err != nil {
return nil, fmt.Errorf("creating request: %w", err)
}
u.setHeaders(req, params)
return req, nil
}
// GetJSON returns the raw JSON from a path. This is useful for debugging.
func (u *Unifi) GetJSON(apiPath string, params ...string) ([]byte, error) {
req, err := u.UniReq(apiPath, strings.Join(params, " "))
if err != nil {
return []byte{}, err
}
return u.do(req)
}
// PutJSON uses a PUT call and returns the raw JSON in the same way as GetData
// Use this if you want to change data via the REST API.
func (u *Unifi) PutJSON(apiPath string, params ...string) ([]byte, error) {
req, err := u.UniReqPut(apiPath, strings.Join(params, " "))
if err != nil {
return []byte{}, err
}
return u.do(req)
}
// PostJSON uses a POST call and returns the raw JSON in the same way as GetData
// Use this if you want to change data via the REST API.
func (u *Unifi) PostJSON(apiPath string, params ...string) ([]byte, error) {
req, err := u.UniReqPost(apiPath, strings.Join(params, " "))
if err != nil {
return []byte{}, err
}
return u.do(req)
}
func (u *Unifi) do(req *http.Request) ([]byte, error) {
var (
cancel func()
ctx = context.Background()
)
if u.Config.Timeout != 0 {
ctx, cancel = context.WithTimeout(ctx, u.Config.Timeout)
defer cancel()
}
resp, err := u.Do(req.WithContext(ctx))
if err != nil {
return []byte{}, fmt.Errorf("making request: %w", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return body, fmt.Errorf("reading response: %w", err)
}
// Save the returned CSRF header.
if csrf := resp.Header.Get("x-csrf-token"); csrf != "" {
u.csrf = resp.Header.Get("x-csrf-token")
}
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("%s: %s: %w", req.URL, resp.Status, ErrInvalidStatusCode)
}
return body, err
}
func (u *Unifi) setHeaders(req *http.Request, params string) {
// Add the saved CSRF header.
req.Header.Set("X-CSRF-Token", u.csrf)
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json; charset=utf-8")
if u.Client.Jar != nil {
parsedURL, _ := url.Parse(req.URL.String())
u.DebugLog("Requesting %s, with params: %v, cookies: %d", req.URL, params != "", len(u.Client.Jar.Cookies(parsedURL)))
} else {
u.DebugLog("Requesting %s, with params: %v,", req.URL, params != "")
}
}