-
Notifications
You must be signed in to change notification settings - Fork 43
/
server.go
446 lines (380 loc) · 10.4 KB
/
server.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
package hap
import (
"github.com/brutella/dnssd"
"github.com/brutella/hap/accessory"
"github.com/brutella/hap/characteristic"
"github.com/brutella/hap/log"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"golang.org/x/text/secure/precis"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
"bytes"
"context"
"crypto/sha512"
"encoding/base64"
"errors"
"fmt"
"github.com/xiam/to"
"net"
"net/http"
"reflect"
"strconv"
"strings"
"unicode"
)
// A server handles incoming HTTP request for an accessory.
// The server uses dnssd to announce the accessory on the local network.
type Server struct {
// Pin specifies the pincode used to pair
// with the accessory.
Pin string
// Addr specifies the tcp address for the server
// to listen to in form of "host:port".
// If empty, a random port is used.
Addr string
MfiCompliant bool // default false
Protocol string // default "1.0"
SetupId string
Key KeyPair // public and private key (generated and stored on disk)
st *storer // stores data
ss *http.Server // http server
a *accessory.A // main accessory
as []*accessory.A // bridged accessories
version uint16 // version of accessory content – relates to configHash
uuid string // internal identifier (generated and stored on disk)
port int // listen port (can be different than in Addr)
ln *net.TCPListener
// for dnssd stuff
responder dnssd.Responder
handle dnssd.ServiceHandle
}
// A ServeMux lets you attach handlers to http url paths.
type ServeMux interface {
// Handle registers the handler for the given pattern.
Handle(pattern string, handler http.Handler)
// HandleFuncs registers the handler function for the given pattern.
HandleFunc(pattern string, handler http.HandlerFunc)
}
// NewServer returns a new server given a store (to persist data) and accessories.
// If more than one accessory is added to the server, *a* acts as a bridge.
func NewServer(store Store, a *accessory.A, as ...*accessory.A) (*Server, error) {
r := chi.NewRouter()
r.Use(middleware.RequestLogger(&middleware.DefaultLogFormatter{Logger: log.Debug, NoColor: true}))
st := &storer{store}
if err := migrate(st); err != nil {
log.Info.Panic(err)
}
s := &Server{
ss: &http.Server{
Handler: r,
ConnState: connStateEvent,
},
st: st,
a: a,
as: as,
}
// Load the stored uuid or generate a new one.
if s.uuid == "" {
uuid, err := s.st.Get("uuid")
if err != nil {
uuid = []byte(mac48Address(randHex()))
if err := s.st.Set("uuid", uuid); err != nil {
return nil, err
}
}
s.uuid = string(uuid)
}
// Load the stored version or set to 1.
if s.version == 0 {
b, err := s.st.Get("version")
if err == nil {
s.version = uint16(to.Uint64(string(b)))
} else {
s.version = 1
}
}
arr := []*accessory.A{a}
arr = append(arr, as[:]...)
if err := s.add(arr); err != nil {
return nil, err
}
// Group handlers for tlv8 and json encoded content.
r.Group(func(r chi.Router) {
r.Use(middleware.SetHeader("Content-Type", HTTPContentTypePairingTLV8))
r.Post("/pair-setup", s.pairSetup)
r.Post("/pair-verify", s.pairVerify)
r.Post("/identify", s.identify)
})
// The json encoded content is encrypted. The encryption keys
// are stored in a session. The de-/encryption is done by a Conn.
r.Group(func(r chi.Router) {
r.Use(middleware.SetHeader("Content-Type", HTTPContentTypeHAPJson))
r.Get("/accessories", s.getAccessories)
r.Get("/characteristics", s.getCharacteristics)
r.Put("/characteristics", s.putCharacteristics)
r.Post("/pairings", s.pairings)
})
return s, nil
}
// ServeMux returns the http handler.
func (s *Server) ServeMux() ServeMux {
return s.ss.Handler.(*chi.Mux)
}
// ListenAndServe starts the server.
func (s *Server) ListenAndServe(ctx context.Context) error {
err := s.prepare()
if err != nil {
return err
}
return s.listenAndServe(ctx)
}
func (s *Server) listenAndServe(ctx context.Context) error {
// Listen with a tcp socket on a given addr/port.
tcpLn, err := net.Listen("tcp", s.Addr)
if err != nil {
return err
}
ln := &listener{tcpLn.(*net.TCPListener)}
// Get the port from the listener address because it
// it might be different than specified in Port.
_, port, _ := net.SplitHostPort(ln.Addr().String())
i, err := strconv.Atoi(port)
if err != nil {
return err
}
s.port = i
// Announce the server using dnssd.
resp, err := dnssd.NewResponder()
if err != nil {
return fmt.Errorf("dnssd: %s", err)
}
s.responder = resp
service, err := s.service()
if err != nil {
return fmt.Errorf("dnssd: %s", err)
}
h, err := resp.Add(service)
if err != nil {
return err
}
s.handle = h
dnsCtx, dnsCancel := context.WithCancel(ctx)
defer dnsCancel()
dnsStop := make(chan struct{})
go func() {
resp.Respond(dnsCtx)
log.Debug.Println("dnssd responder stopped")
dnsStop <- struct{}{}
}()
log.Debug.Println("listening at", ln.Addr())
serverCtx, serverCancel := context.WithCancel(ctx)
defer serverCancel()
serverStop := make(chan struct{})
go func() {
<-serverCtx.Done()
ln.Close()
s.ss.Close()
log.Debug.Println("http server stopped")
serverStop <- struct{}{}
}()
err = s.ss.Serve(ln)
<-dnsStop
<-serverStop
return err
}
func (s *Server) add(as []*accessory.A) error {
aid := uint64(1)
for _, a := range as {
if a.Name() == "" {
return errors.New("invalid accessory name")
}
if a.Id == 0 {
a.Id = aid
aid++
}
var iid uint64 = 1
for _, s := range a.Ss {
s.Id = iid
iid++
for _, c := range s.Cs {
// Create a local variable before
// capturing them in a function.
a := a
c.Id = iid
iid++
// If the value of a characteristic changes, we notify all connected clients.
// The identify characteristic is a special case where we all accessory.IdentifyFunc.
if c.Type == characteristic.TypeIdentify {
c.OnCValueUpdate(func(c *characteristic.C, new, old interface{}, req *http.Request) {
if b, ok := new.(bool); ok && b && a.IdentifyFunc != nil {
a.IdentifyFunc(req)
}
})
} else {
c.OnCValueUpdate(func(c *characteristic.C, new, old interface{}, req *http.Request) {
// send notification to all subscribed clients
sendNotification(a, c, req)
})
}
}
}
}
// The server keeps track of previously published accessories.
// If the accessory changed (added service or characteristics)
// from last time, we have to update the version flag.
var oldHash, newHash []byte
if b, err := s.st.Get("configHash"); err == nil && len(b) > 0 {
oldHash = b
}
newHash = configHash(as)
if !reflect.DeepEqual(oldHash, newHash) {
s.version += 1
s.st.Set("version", []byte(fmt.Sprintf("%d", s.version)))
s.st.Set("configHash", newHash)
}
return nil
}
func (s *Server) prepare() error {
if allZero(s.Key.Public[:]) || allZero(s.Key.Private[:]) {
// Load keypair or generate a new one.
keypair, err := s.st.KeyPair()
if err != nil {
keypair, err := generateKeyPair()
if err != nil {
return fmt.Errorf("generating keypair failed: %v", err)
}
s.Key = keypair
if err := s.st.SaveKeyPair(keypair); err != nil {
return fmt.Errorf("saving keypair failed: %v", err)
}
} else {
s.Key = keypair
}
}
if s.Pin == "" {
s.Pin = "00102003" // default pincode
}
if s.Protocol == "" {
s.Protocol = "1.0"
}
if len(s.Pin) != 8 {
return fmt.Errorf("invald pin length %d", len(s.Pin))
} else if _, found := InvalidPins[s.Pin]; found {
return fmt.Errorf("insecure pin %s", s.Pin)
}
return nil
}
func (s *Server) savePairing(p Pairing) error {
err := s.st.SavePairing(p)
if err != nil {
return err
}
s.updateTxtRecords()
return nil
}
func (s *Server) deletePairing(p Pairing) error {
err := s.st.DeletePairing(p.Name)
if err != nil {
return err
}
s.updateTxtRecords()
return nil
}
func (s *Server) isPaired() bool {
return len(s.st.Pairings()) > 0
}
func (s *Server) pairedWithAdmin() bool {
for _, p := range s.st.Pairings() {
if p.Permission == PermissionAdmin {
return true
}
}
return false
}
func (s *Server) txtRecords() map[string]string {
return map[string]string{
"pv": s.Protocol,
"id": s.uuid,
"c#": fmt.Sprintf("%d", s.version),
"s#": "1",
"sf": fmt.Sprintf("%d", to.Int64(!s.isPaired())),
"ff": fmt.Sprintf("%d", to.Int64(s.MfiCompliant)),
"md": s.a.Name(),
"ci": fmt.Sprintf("%d", s.a.Type),
"sh": s.setupHash(),
}
}
func (s *Server) setupHash() string {
hashvalue := fmt.Sprintf("%s%s", s.SetupId, s.uuid)
sum := sha512.Sum512([]byte(hashvalue))
// use only first 4 bytes
code := []byte{sum[0], sum[1], sum[2], sum[3]}
encoded := base64.StdEncoding.EncodeToString(code)
return encoded
}
func (s *Server) updateTxtRecords() {
if s.handle != nil {
s.handle.UpdateText(s.txtRecords(), s.responder)
}
}
func (s *Server) service() (dnssd.Service, error) {
// 2016-03-14(brutella): Replace whitespaces (" ") from service name
// with underscores ("_")to fix invalid http host header field value
// produces by iOS.
//
// [Radar] http://openradar.appspot.com/radar?id=4931940373233664
stripped := strings.Replace(s.a.Info.Name.Value(), " ", "_", -1)
cfg := dnssd.Config{
Name: removeAccentsFromString(stripped),
Type: "_hap._tcp",
Domain: "local",
// Host: strings.Replace(s.uuid, ":", "", -1), // use the id (without the colons) to get unique hostnames
Text: s.txtRecords(),
Port: s.port,
}
return dnssd.NewService(cfg)
}
var InvalidPins = map[string]bool{
"00000000": true,
"11111111": true,
"22222222": true,
"33333333": true,
"44444444": true,
"55555555": true,
"66666666": true,
"77777777": true,
"88888888": true,
"99999999": true,
"12345678": true,
"87654321": true,
}
func (s *Server) fmtPin() string {
runes := bytes.Runes([]byte(s.Pin))
first := string(runes[:3])
second := string(runes[3:5])
third := string(runes[5:])
return first + "-" + second + "-" + third
}
// RemoveAccentsFromString removes accent characters from string
// From https://stackoverflow.com/a/40405242/424814
func removeAccentsFromString(v string) string {
var loosecompare = precis.NewIdentifier(
precis.AdditionalMapping(func() transform.Transformer {
return transform.Chain(norm.NFD, transform.RemoveFunc(func(r rune) bool {
return unicode.Is(unicode.Mn, r)
}))
}),
precis.Norm(norm.NFC), // This is the default; be explicit though.
)
p, _ := loosecompare.String(v)
return p
}
func allZero(s []byte) bool {
for _, v := range s {
if v != 0 {
return false
}
}
return true
}