-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathserver.py
More file actions
978 lines (818 loc) · 30.1 KB
/
server.py
File metadata and controls
978 lines (818 loc) · 30.1 KB
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
"""Python Web Thing server implementation."""
from zeroconf import ServiceInfo, Zeroconf
import json
import socket
import tornado.concurrent
import tornado.gen
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket
from .errors import PropertyError
from .subscriber import Subscriber
from .utils import get_addresses, get_ip
@tornado.gen.coroutine
def perform_action(action):
"""Perform an Action in a coroutine."""
action.start()
class SingleThing:
"""A container for a single thing."""
def __init__(self, thing):
"""
Initialize the container.
thing -- the thing to store
"""
self.thing = thing
def get_thing(self, _=None):
"""Get the thing at the given index."""
return self.thing
def get_things(self):
"""Get the list of things."""
return [self.thing]
def get_name(self):
"""Get the mDNS server name."""
return self.thing.title
class MultipleThings:
"""A container for multiple things."""
def __init__(self, things, name):
"""
Initialize the container.
things -- the things to store
name -- the mDNS server name
"""
self.things = things
self.name = name
def get_thing(self, idx):
"""
Get the thing at the given index.
idx -- the index
"""
try:
idx = int(idx)
except ValueError:
return None
if idx < 0 or idx >= len(self.things):
return None
return self.things[idx]
def get_things(self):
"""Get the list of things."""
return self.things
def get_name(self):
"""Get the mDNS server name."""
return self.name
class BaseHandler(tornado.web.RequestHandler):
"""Base handler that is initialized with a thing."""
def initialize(self, things, hosts, disable_host_validation):
"""
Initialize the handler.
things -- list of Things managed by this server
hosts -- list of allowed hostnames
disable_host_validation -- whether or not to disable host validation --
note that this can lead to DNS rebinding
attacks
"""
self.things = things
self.hosts = hosts
self.disable_host_validation = disable_host_validation
def prepare(self):
"""Validate Host header."""
host = self.request.headers.get('Host', None)
if self.disable_host_validation or (
host is not None and host in self.hosts):
return
raise tornado.web.HTTPError(403)
def get_thing(self, thing_id):
"""
Get the thing this request is for.
thing_id -- ID of the thing to get, in string form
Returns the thing, or None if not found.
"""
return self.things.get_thing(thing_id)
def set_default_headers(self, *args, **kwargs):
"""Set the default headers for all requests."""
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept')
self.set_header('Access-Control-Allow-Methods',
'GET, HEAD, PUT, POST, DELETE')
def options(self, *args, **kwargs):
"""Handle an OPTIONS request."""
self.set_status(204)
class ThingsHandler(BaseHandler):
"""Handle a request to / when the server manages multiple things."""
def get(self):
"""
Handle a GET request.
property_name -- the name of the property from the URL path
"""
self.set_header('Content-Type', 'application/json')
ws_href = '{}://{}'.format(
'wss' if self.request.protocol == 'https' else 'ws',
self.request.headers.get('Host', '')
)
descriptions = []
for thing in self.things.get_things():
description = thing.as_thing_description()
description['href'] = thing.get_href()
description['links'].append({
'rel': 'alternate',
'href': '{}{}'.format(ws_href, thing.get_href()),
})
description['base'] = '{}://{}{}'.format(
self.request.protocol,
self.request.headers.get('Host', ''),
thing.get_href()
)
description['securityDefinitions'] = {
'nosec_sc': {
'scheme': 'nosec',
},
}
description['security'] = 'nosec_sc'
descriptions.append(description)
self.write(json.dumps(descriptions))
class ThingHandler(tornado.websocket.WebSocketHandler, Subscriber):
"""Handle a request to /."""
def initialize(self, things, hosts, disable_host_validation):
"""
Initialize the handler.
things -- list of Things managed by this server
hosts -- list of allowed hostnames
disable_host_validation -- whether or not to disable host validation --
note that this can lead to DNS rebinding
attacks
"""
self.things = things
self.hosts = hosts
self.disable_host_validation = disable_host_validation
def prepare(self):
"""Validate Host header."""
host = self.request.headers.get('Host', None)
if self.disable_host_validation or (
host is not None and host in self.hosts):
return
raise tornado.web.HTTPError(403)
def set_default_headers(self, *args, **kwargs):
"""Set the default headers for all requests."""
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept')
self.set_header('Access-Control-Allow-Methods',
'GET, HEAD, PUT, POST, DELETE')
def options(self, *args, **kwargs):
"""Handle an OPTIONS request."""
self.set_status(204)
def get_thing(self, thing_id):
"""
Get the thing this request is for.
thing_id -- ID of the thing to get, in string form
Returns the thing, or None if not found.
"""
return self.things.get_thing(thing_id)
@tornado.gen.coroutine
def get(self, thing_id='0'):
"""
Handle a GET request, including websocket requests.
thing_id -- ID of the thing this request is for
"""
self.thing = self.get_thing(thing_id)
if self.thing is None:
self.set_status(404)
self.finish()
return
if self.request.headers.get('Upgrade', '').lower() == 'websocket':
yield tornado.websocket.WebSocketHandler.get(self)
return
self.set_header('Content-Type', 'application/json')
ws_href = '{}://{}'.format(
'wss' if self.request.protocol == 'https' else 'ws',
self.request.headers.get('Host', '')
)
description = self.thing.as_thing_description()
description['links'].append({
'rel': 'alternate',
'href': '{}{}'.format(ws_href, self.thing.get_href()),
})
description['base'] = '{}://{}{}'.format(
self.request.protocol,
self.request.headers.get('Host', ''),
self.thing.get_href()
)
description['securityDefinitions'] = {
'nosec_sc': {
'scheme': 'nosec',
},
}
description['security'] = 'nosec_sc'
self.write(json.dumps(description))
self.finish()
def open(self):
"""Handle a new connection."""
self.thing.add_subscriber(self)
def on_message(self, message):
"""
Handle an incoming message.
message -- message to handle
"""
try:
message = json.loads(message)
except ValueError:
try:
self.write_message(json.dumps({
'messageType': 'error',
'data': {
'status': '400 Bad Request',
'message': 'Parsing request failed',
},
}))
except tornado.websocket.WebSocketClosedError:
pass
return
if 'messageType' not in message or 'data' not in message:
try:
self.write_message(json.dumps({
'messageType': 'error',
'data': {
'status': '400 Bad Request',
'message': 'Invalid message',
},
}))
except tornado.websocket.WebSocketClosedError:
pass
return
msg_type = message['messageType']
if msg_type == 'setProperty':
for property_name, property_value in message['data'].items():
try:
self.thing.set_property(property_name, property_value)
except PropertyError as e:
self.write_message(json.dumps({
'messageType': 'error',
'data': {
'status': '400 Bad Request',
'message': str(e),
},
}))
elif msg_type == 'requestAction':
for action_name, action_params in message['data'].items():
input_ = None
if 'input' in action_params:
input_ = action_params['input']
action = self.thing.perform_action(action_name, input_)
if action:
tornado.ioloop.IOLoop.current().spawn_callback(
perform_action,
action,
)
else:
self.write_message(json.dumps({
'messageType': 'error',
'data': {
'status': '400 Bad Request',
'message': 'Invalid action request',
'request': message,
},
}))
elif msg_type == 'addEventSubscription':
for event_name in message['data'].keys():
self.thing.add_event_subscriber(event_name, self)
else:
try:
self.write_message(json.dumps({
'messageType': 'error',
'data': {
'status': '400 Bad Request',
'message': 'Unknown messageType: ' + msg_type,
'request': message,
},
}))
except tornado.websocket.WebSocketClosedError:
pass
def on_close(self):
"""Handle a close event on the socket."""
self.thing.remove_subscriber(self)
def check_origin(self, origin):
"""Allow connections from all origins."""
return True
def update_property(self, property_):
"""
Send an update about a Property.
:param property_: Property
"""
message = json.dumps({
'messageType': 'propertyStatus',
'data': {
property_.name: property_.get_value(),
}
})
self.write_message(message)
def update_action(self, action):
"""
Send an update about an Action.
:param action: Action
"""
message = json.dumps({
'messageType': 'actionStatus',
'data': action.as_action_description(),
})
self.write_message(message)
def update_event(self, event):
"""
Send an update about an Event.
:param event: Event
"""
message = json.dumps({
'messageType': 'event',
'data': event.as_event_description(),
})
self.write_message(message)
class PropertiesHandler(BaseHandler):
"""Handle a request to /properties."""
def get(self, thing_id='0'):
"""
Handle a GET request.
thing_id -- ID of the thing this request is for
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_status(404)
return
self.set_header('Content-Type', 'application/json')
self.write(json.dumps(thing.get_properties()))
def put(self, thing_id='0'):
"""
Handle a PUT request.
thing_id -- ID of the thing this request is for
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_status(404)
return
try:
properties = json.loads(self.request.body.decode())
except ValueError:
self.set_status(400)
return
for property_name, value in properties.items():
if thing.has_property(property_name):
try:
thing.set_property(property_name, value)
except PropertyError:
self.set_status(400)
return
else:
self.set_status(404)
return
self.set_status(204)
class PropertyHandler(BaseHandler):
"""Handle a request to /properties/<property>."""
def get(self, thing_id='0', property_name=None):
"""
Handle a GET request.
thing_id -- ID of the thing this request is for
property_name -- the name of the property from the URL path
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_status(404)
return
if thing.has_property(property_name):
self.set_header('Content-Type', 'application/json')
self.write(json.dumps(thing.get_property(property_name)))
else:
self.set_status(404)
def put(self, thing_id='0', property_name=None):
"""
Handle a PUT request.
thing_id -- ID of the thing this request is for
property_name -- the name of the property from the URL path
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_status(404)
return
try:
value = json.loads(self.request.body.decode())
except ValueError:
self.set_status(400)
return
if thing.has_property(property_name):
try:
thing.set_property(property_name, value)
except PropertyError:
self.set_status(400)
return
self.set_status(204)
else:
self.set_status(404)
class ActionsHandler(BaseHandler):
"""Handle a request to /actions.""" # TODO: Should this feature be removed?
def get(self, thing_id='0'):
"""
Handle a GET request.
thing_id -- ID of the thing this request is for
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_status(404)
return
self.set_header('Content-Type', 'application/json')
self.write(json.dumps(thing.get_action_descriptions()))
def post(self, thing_id='0'):
"""
Handle a POST request.
thing_id -- ID of the thing this request is for
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_status(404)
return
try:
message = json.loads(self.request.body.decode())
except ValueError:
self.set_status(400)
return
keys = list(message.keys())
if len(keys) != 1:
self.set_status(400)
return
action_name = keys[0]
action_params = message[action_name]
input_ = None
if 'input' in action_params:
input_ = action_params['input']
action = thing.perform_action(action_name, input_)
if action:
response = action.as_action_description()
# Start the action
tornado.ioloop.IOLoop.current().spawn_callback(
perform_action,
action,
)
self.set_status(201)
self.write(json.dumps(response))
else:
self.set_status(400)
class ActionHandler(BaseHandler):
"""Handle a request to /actions/<action_name>."""
def get(self, thing_id='0', action_name=None):
"""
Handle a GET request.
thing_id -- ID of the thing this request is for
action_name -- name of the action from the URL path
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_status(404)
return
self.set_header('Content-Type', 'application/json')
self.write(json.dumps(thing.get_action_descriptions(
action_name=action_name)))
def post(self, thing_id='0', action_name=None):
"""
Handle a POST request.
thing_id -- ID of the thing this request is for
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_status(404)
return
try:
input_ = json.loads(self.request.body.decode())
except ValueError:
self.set_status(400)
return
# Allow payloads wrapped inside `value` field
#TODO: remove this in the future
if 'value' in input_:
input_ = input_['value']
action = thing.perform_action(action_name, input_)
if action:
# Start the action
tornado.ioloop.IOLoop.current().spawn_callback(
perform_action,
action,
)
self.set_header('Content-Type', 'application/json')
self.set_status(200)
self.write(json.dumps(action.get_output()))
else:
self.set_status(400)
class ActionIDHandler(BaseHandler):
"""Handle a request to /actions/<action_name>/<action_id>.""" # TODO: Should this feature be removed?
def get(self, thing_id='0', action_name=None, action_id=None):
"""
Handle a GET request.
thing_id -- ID of the thing this request is for
action_name -- name of the action from the URL path
action_id -- the action ID from the URL path
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_status(404)
return
action = thing.get_action(action_name, action_id)
if action is None:
self.set_status(404)
return
self.set_header('Content-Type', 'application/json')
self.write(json.dumps(action.as_action_description()))
def put(self, thing_id='0', action_name=None, action_id=None):
"""
Handle a PUT request.
TODO: this is not yet defined in the spec
thing_id -- ID of the thing this request is for
action_name -- name of the action from the URL path
action_id -- the action ID from the URL path
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_status(404)
return
self.set_status(200)
def delete(self, thing_id='0', action_name=None, action_id=None):
"""
Handle a DELETE request.
thing_id -- ID of the thing this request is for
action_name -- name of the action from the URL path
action_id -- the action ID from the URL path
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_status(404)
return
if thing.remove_action(action_name, action_id):
self.set_status(204)
else:
self.set_status(404)
class EventsHandler(BaseHandler):
"""Handle a request to /events."""
def get(self, thing_id='0'):
"""
Handle a GET request.
thing_id -- ID of the thing this request is for
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_status(404)
return
self.set_header('Content-Type', 'application/json')
self.write(json.dumps(thing.get_event_descriptions()))
class EventHandler(BaseHandler):
"""Handle a request to /events/<event_name>."""
def get(self, thing_id='0', event_name=None):
"""
Handle a GET request.
thing_id -- ID of the thing this request is for
event_name -- name of the event from the URL path
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_status(404)
return
self.set_header('Content-Type', 'application/json')
self.write(json.dumps(thing.get_event_descriptions(
event_name=event_name)))
class WebThingServer:
"""Server to represent a Web Thing over HTTP."""
def __init__(self, things, port=80, hostname=None, ssl_options=None,
additional_routes=None, base_path='',
disable_host_validation=False):
"""
Initialize the WebThingServer.
For documentation on the additional route format, see:
https://www.tornadoweb.org/en/stable/web.html#tornado.web.Application
things -- things managed by this server -- should be of type
SingleThing or MultipleThings
port -- port to listen on (defaults to 80)
hostname -- Optional host name, i.e. mything.com
ssl_options -- dict of SSL options to pass to the tornado server
additional_routes -- list of additional routes to add to the server
base_path -- base URL path to use, rather than '/'
disable_host_validation -- whether or not to disable host validation --
note that this can lead to DNS rebinding
attacks
"""
self.things = things
self.name = things.get_name()
self.port = port
self.hostname = hostname
self.base_path = base_path.rstrip('/')
self.disable_host_validation = disable_host_validation
system_hostname = socket.gethostname().lower()
self.hosts = [
'localhost',
'localhost:{}'.format(self.port),
'{}.local'.format(system_hostname),
'{}.local:{}'.format(system_hostname, self.port),
]
for address in get_addresses():
self.hosts.extend([
address,
'{}:{}'.format(address, self.port),
])
if self.hostname is not None:
self.hostname = self.hostname.lower()
self.hosts.extend([
self.hostname,
'{}:{}'.format(self.hostname, self.port),
])
if isinstance(self.things, MultipleThings):
for idx, thing in enumerate(self.things.get_things()):
thing.set_href_prefix('{}/{}'.format(self.base_path, idx))
handlers = [
[
r'/?',
ThingsHandler,
dict(
things=self.things,
hosts=self.hosts,
disable_host_validation=self.disable_host_validation,
),
],
[
r'/(?P<thing_id>\d+)/?',
ThingHandler,
dict(
things=self.things,
hosts=self.hosts,
disable_host_validation=self.disable_host_validation,
),
],
[
r'/(?P<thing_id>\d+)/properties/?',
PropertiesHandler,
dict(
things=self.things,
hosts=self.hosts,
disable_host_validation=self.disable_host_validation,
),
],
[
r'/(?P<thing_id>\d+)/properties/' +
r'(?P<property_name>[^/]+)/?',
PropertyHandler,
dict(
things=self.things,
hosts=self.hosts,
disable_host_validation=self.disable_host_validation,
),
],
[
r'/(?P<thing_id>\d+)/actions/?',
ActionsHandler,
dict(
things=self.things,
hosts=self.hosts,
disable_host_validation=self.disable_host_validation,
),
],
[
r'/(?P<thing_id>\d+)/actions/(?P<action_name>[^/]+)/?',
ActionHandler,
dict(
things=self.things,
hosts=self.hosts,
disable_host_validation=self.disable_host_validation,
),
],
[
r'/(?P<thing_id>\d+)/actions/' +
r'(?P<action_name>[^/]+)/(?P<action_id>[^/]+)/?',
ActionIDHandler,
dict(
things=self.things,
hosts=self.hosts,
disable_host_validation=self.disable_host_validation,
),
],
[
r'/(?P<thing_id>\d+)/events/?',
EventsHandler,
dict(
things=self.things,
hosts=self.hosts,
disable_host_validation=self.disable_host_validation,
),
],
[
r'/(?P<thing_id>\d+)/events/(?P<event_name>[^/]+)/?',
EventHandler,
dict(
things=self.things,
hosts=self.hosts,
disable_host_validation=self.disable_host_validation,
),
],
]
else:
self.things.get_thing().set_href_prefix(self.base_path)
handlers = [
[
r'/?',
ThingHandler,
dict(
things=self.things,
hosts=self.hosts,
disable_host_validation=self.disable_host_validation,
),
],
[
r'/properties/?',
PropertiesHandler,
dict(
things=self.things,
hosts=self.hosts,
disable_host_validation=self.disable_host_validation,
),
],
[
r'/properties/(?P<property_name>[^/]+)/?',
PropertyHandler,
dict(
things=self.things,
hosts=self.hosts,
disable_host_validation=self.disable_host_validation,
),
],
[
r'/actions/?',
ActionsHandler,
dict(
things=self.things,
hosts=self.hosts,
disable_host_validation=self.disable_host_validation,
),
],
[
r'/actions/(?P<action_name>[^/]+)/?',
ActionHandler,
dict(
things=self.things,
hosts=self.hosts,
disable_host_validation=self.disable_host_validation,
),
],
[
r'/actions/(?P<action_name>[^/]+)/(?P<action_id>[^/]+)/?',
ActionIDHandler,
dict(
things=self.things,
hosts=self.hosts,
disable_host_validation=self.disable_host_validation,
),
],
[
r'/events/?',
EventsHandler,
dict(
things=self.things,
hosts=self.hosts,
disable_host_validation=self.disable_host_validation,
),
],
[
r'/events/(?P<event_name>[^/]+)/?',
EventHandler,
dict(
things=self.things,
hosts=self.hosts,
disable_host_validation=self.disable_host_validation,
),
],
]
if isinstance(additional_routes, list):
handlers = additional_routes + handlers
if self.base_path:
for h in handlers:
h[0] = self.base_path + h[0]
self.app = tornado.web.Application(handlers)
self.app.is_tls = ssl_options is not None
self.server = tornado.httpserver.HTTPServer(self.app,
ssl_options=ssl_options)
def start(self):
"""Start listening for incoming connections."""
args = [
'_webthing._tcp.local.',
'{}._webthing._tcp.local.'.format(self.name),
]
kwargs = {
'addresses': [socket.inet_aton(get_ip())],
'port': self.port,
'properties': {
'path': '/',
},
'server': '{}.local.'.format(socket.gethostname()),
}
if self.app.is_tls:
kwargs['properties']['tls'] = '1'
self.service_info = ServiceInfo(*args, **kwargs)
self.zeroconf = Zeroconf()
self.zeroconf.register_service(self.service_info)
self.server.listen(self.port)
tornado.ioloop.IOLoop.current().start()
def stop(self):
"""Stop listening."""
self.zeroconf.unregister_service(self.service_info)
self.zeroconf.close()
self.server.stop()