-
Notifications
You must be signed in to change notification settings - Fork 43
/
coap.py
1491 lines (1265 loc) · 59.1 KB
/
coap.py
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
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Created on 08-09-2012
@author: Maciej Wasilak
'''
from itertools import chain
import codecs
import collections
import copy
import random
import struct
import sys
from twisted.internet import protocol, defer, reactor
from twisted.python import log, failure
import txthings.error as error
from ipaddress import ip_address
import six
COAP_PORT = 5683
"""The IANA-assigned standard port for COAP services."""
# +-------------------+---------------+
# | name | default value |
# +-------------------+---------------+
# | ACK_TIMEOUT | 2 seconds |
# | ACK_RANDOM_FACTOR | 1.5 |
# | MAX_RETRANSMIT | 4 |
# | NSTART | 1 |
# | DEFAULT_LEISURE | 5 seconds |
# | PROBING_RATE | 1 Byte/second |
# +-------------------+---------------+
ACK_TIMEOUT = 2.0
"""The time, in seconds, to wait for an acknowledgement of a
confirmable message. The inter-transmission time doubles
for each retransmission."""
ACK_RANDOM_FACTOR = 1.5
"""Timeout multiplier for anti-synchronization."""
MAX_RETRANSMIT = 4
"""The number of retransmissions of confirmable messages to
non-multicast endpoints before the infrastructure assumes no
acknowledgement will be received."""
NSTART = 1
"""Maximum number of simultaneous outstanding interactions
that endpoint maintains to a given server (including proxies)"""
# +-------------------+---------------+
# | name | default value |
# +-------------------+---------------+
# | MAX_TRANSMIT_SPAN | 45 s |
# | MAX_TRANSMIT_WAIT | 93 s |
# | MAX_LATENCY | 100 s |
# | PROCESSING_DELAY | 2 s |
# | MAX_RTT | 202 s |
# | EXCHANGE_LIFETIME | 247 s |
# | NON_LIFETIME | 145 s |
# +-------------------+---------------+
MAX_TRANSMIT_SPAN = ACK_TIMEOUT * (2 ** MAX_RETRANSMIT - 1) * ACK_RANDOM_FACTOR
"""Maximum time from the first transmission
of a confirmable message to its last retransmission."""
MAX_TRANSMIT_WAIT = ACK_TIMEOUT * (2 ** (MAX_RETRANSMIT + 1) - 1) * ACK_RANDOM_FACTOR
"""Maximum time from the first transmission
of a confirmable message to the time when the sender gives up on
receiving an acknowledgement or reset."""
MAX_LATENCY = 100.0
"""Maximum time a datagram is expected to take from the start
of its transmission to the completion of its reception."""
PROCESSING_DELAY = ACK_TIMEOUT
""""Time a node takes to turn around a
confirmable message into an acknowledgement."""
MAX_RTT = 2 * MAX_LATENCY + PROCESSING_DELAY
"""Maximum round-trip time."""
EXCHANGE_LIFETIME = MAX_TRANSMIT_SPAN + MAX_RTT
"""time from starting to send a confirmable
message to the time when an acknowledgement is no longer expected,
i.e. message layer information about the message exchange can be purged"""
DEFAULT_BLOCK_SIZE_EXP = 2 # Block size 64
"""Default size exponent for blockwise transfers."""
EMPTY_ACK_DELAY = 0.1
"""After this time protocol sends empty ACK, and separate response"""
REQUEST_TIMEOUT = MAX_TRANSMIT_WAIT
"""Time after which server assumes it won't receive any answer.
It is not defined by IETF documents.
For human-operated devices it might be preferable to set some small value
(for example 10 seconds)
For M2M it's application dependent."""
CON = 0
"""Confirmable message type."""
NON = 1
"""Non-confirmable message type."""
ACK = 2
"""Acknowledgement message type."""
RST = 3
"""Reset message type"""
types = {0: 'CON',
1: 'NON',
2: 'ACK',
3: 'RST'}
EMPTY = 0
GET = 1
POST = 2
PUT = 3
DELETE = 4
CREATED = 65
DELETED = 66
VALID = 67
CHANGED = 68
CONTENT = 69
CONTINUE = 95
BAD_REQUEST = 128
UNAUTHORIZED = 129
BAD_OPTION = 130
FORBIDDEN = 131
NOT_FOUND = 132
METHOD_NOT_ALLOWED = 133
NOT_ACCEPTABLE = 134
REQUEST_ENTITY_INCOMPLETE = 136
PRECONDITION_FAILED = 140
REQUEST_ENTITY_TOO_LARGE = 141
UNSUPPORTED_CONTENT_FORMAT = 143
INTERNAL_SERVER_ERROR = 160
NOT_IMPLEMENTED = 161
BAD_GATEWAY = 162
SERVICE_UNAVAILABLE = 163
GATEWAY_TIMEOUT = 164
PROXYING_NOT_SUPPORTED = 165
requests = {1: 'GET',
2: 'POST',
3: 'PUT',
4: 'DELETE'}
requests_rev = {v:k for k, v in requests.items()}
responses = {65: '2.01 Created',
66: '2.02 Deleted',
67: '2.03 Valid',
68: '2.04 Changed',
69: '2.05 Content',
95: '2.31 Continue',
128: '4.00 Bad Request',
129: '4.01 Unauthorized',
130: '4.02 Bad Option',
131: '4.03 Forbidden',
132: '4.04 Not Found',
133: '4.05 Method Not Allowed',
134: '4.06 Not Acceptable',
136: '4.08 Request Entity Incomplete',
140: '4.12 Precondition Failed',
141: '4.13 Request Entity Too Large',
143: '4.15 Unsupported Content-Format',
160: '5.00 Internal Server Error',
161: '5.01 Not Implemented',
162: '5.02 Bad Gateway',
163: '5.03 Service Unavailable',
164: '5.04 Gateway Timeout',
165: '5.05 Proxying Not Supported'}
responses_rev = {v:k for k, v in responses.items()}
#=============================================================================
# RFC7252, block-14, observe-11
#=============================================================================
# +-----+---+---+---+---+----------------+------------+--------+-------------+
# | No. | C | U | N | R | Name | Format | Length | Default |
# +-----+---+---+---+---+----------------+------------+--------+-------------+
# | 1 | x | | | x | If-Match | opaque | 0-8 | (none) |
# | 3 | x | x | - | | Uri-Host | string | 1-255 | (see below) |
# | 4 | | | | x | ETag | opaque | 1-8 | (none) |
# | 5 | x | | | | If-None-Match | empty | 0 | (none) |
# | 6 | | x | | | Observe | empty/uint | ? | (none) |
# | 7 | x | x | - | | Uri-Port | uint | 0-2 | (see below) |
# | 8 | | | | x | Location-Path | string | 0-255 | (none) |
# | 11 | x | x | - | x | Uri-Path | string | 0-255 | (none) |
# | 12 | | | | | Content-Format | uint | 0-2 | (none) |
# | 14 | | x | | | Max-Age | uint | 0-4 | 60 |
# | 15 | x | x | - | x | Uri-Query | string | 0-255 | (none) |
# | 17 | x | | | | Accept | uint | 0-2 | (none) |
# | 20 | | | | x | Location-Query | string | 0-255 | (none) |
# | 23 | x | x | - | - | Block2 | uint | 0-3 | (see below) |
# | 27 | x | x | - | - | Block1 | uint | 0-3 | (see below) |
# | 28 | | | x | | Size2 | uint | 0-4 | (none) |
# | 35 | x | x | - | | Proxy-Uri | string | 1-1034 | (none) |
# | 39 | x | x | - | | Proxy-Scheme | string | 1-255 | (none) |
# | 60 | | | x | | Size1 | uint | 0-4 | (none) |
# +-----+---+---+---+---+----------------+------------+--------+-------------+
#=============================================================================
#
# This table should serve as a reference only. It does not confirm that
# txThings conforms to the documents above
#
IF_MATCH = 1
URI_HOST = 3
ETAG = 4
IF_NONE_MATCH = 5
OBSERVE = 6
URI_PORT = 7
LOCATION_PATH = 8
URI_PATH = 11
CONTENT_FORMAT = 12
MAX_AGE = 14
URI_QUERY = 15
ACCEPT = 17
LOCATION_QUERY = 20
BLOCK2 = 23
BLOCK1 = 27
SIZE2 = 28
PROXY_URI = 35
PROXY_SCHEME = 39
SIZE1 = 60
options = {1: 'If-Match',
3: 'Uri-Host',
4: 'ETag',
5: 'If-None-Match',
6: 'Observe',
7: 'Uri-Port',
8: 'Location-Path',
11: 'Uri-Path',
12: 'Content-Format',
14: 'Max-Age',
15: 'Uri-Query',
17: 'Accept',
20: 'Location-Query',
23: 'Block2',
27: 'Block1',
28: 'Size2',
35: 'Proxy-Uri',
39: 'Proxy-Scheme',
60: 'Size1'}
options_rev = {v:k for k, v in options.items()}
media_types = {0: 'text/plain',
40: 'application/link-format',
41: 'application/xml',
42: 'application/octet-stream',
47: 'application/exi',
50: 'application/json',
60: 'application/cbor'}
"""A map from CoAP-assigned integral codes to Internet media type descriptions."""
media_types_rev = {v:k for k, v in media_types.items()}
class Message(object):
"""A CoAP Message."""
def __init__(self, mtype=None, mid=None, code=EMPTY, payload=b'', token=b''):
self.version = 1
self.mtype = mtype
self.mid = mid
self.code = code
self.token = token
self.payload = payload
self.opt = Options()
self.response_type = None
self.remote = None
self.prepath = None
self.postpath = None
if self.payload is None:
raise TypeError("Payload must not be None. Use empty string instead.")
@classmethod
def decode(cls, rawdata, remote=None, protocol=None):
"""Create Message object from binary representation of message."""
(vttkl, code, mid) = struct.unpack('!BBH', rawdata[:4])
version = (vttkl & 0xC0) >> 6
if version is not 1:
raise ValueError("Fatal Error: Protocol Version must be 1")
mtype = (vttkl & 0x30) >> 4
token_length = (vttkl & 0x0F)
msg = Message(mtype=mtype, mid=mid, code=code)
msg.token = rawdata[4:4 + token_length]
msg.payload = msg.opt.decode(rawdata[4 + token_length:])
msg.remote = remote
msg.protocol = protocol
return msg
def encode(self):
"""Create binary representation of message from Message object."""
if self.mtype is None or self.mid is None:
raise TypeError("Fatal Error: Message Type and Message ID must not be None.")
rawdata = six.int2byte((self.version << 6) + ((self.mtype & 0x03) << 4) + (len(self.token) & 0x0F))
rawdata += struct.pack('!BH', self.code, self.mid)
rawdata += self.token
rawdata += self.opt.encode()
if len(self.payload) > 0:
rawdata += six.int2byte(0xFF)
rawdata += self.payload
return rawdata
def extractBlock(self, number, size_exp):
"""Extract block from current message."""
size = 2 ** (size_exp + 4)
start = number * size
if start < len(self.payload):
end = start + size if start + size < len(self.payload) else len(self.payload)
block = copy.deepcopy(self)
block.payload = block.payload[start:end]
block.mid = None
more = True if end < len(self.payload) else False
if isRequest(block.code):
block.opt.block1 = (number, more, size_exp)
block.opt.size1 = len(self.payload)
else:
block.opt.block2 = (number, more, size_exp)
block.opt.size2 = len(self.payload)
return block
def appendRequestBlock(self, next_block):
"""Append next block to current request message.
Used when assembling incoming blockwise requests."""
if isRequest(self.code):
block1 = next_block.opt.block1
if block1.block_number * (2 ** (block1.size_exponent + 4)) == len(self.payload):
self.payload += next_block.payload
self.opt.block1 = block1
self.token = next_block.token
self.mid = next_block.mid
self.response_type = None
else:
raise error.NotImplemented()
else:
raise ValueError("Fatal Error: called appendRequestBlock on non-request message!!!")
def appendResponseBlock(self, next_block):
"""Append next block to current response message.
Used when assembling incoming blockwise responses."""
if isResponse(self.code):
## @TODO: check etags for consistency
block2 = next_block.opt.block2
if block2.block_number * (2 ** (block2.size_exponent + 4)) != len(self.payload):
raise error.NotImplemented()
if next_block.opt.etag != self.opt.etag:
raise error.ResourceChanged()
self.payload += next_block.payload
self.opt.block2 = block2
self.token = next_block.token
self.mid = next_block.mid
else:
raise ValueError("Fatal Error: called appendResponseBlock on non-response message!!!")
def generateNextBlock2Request(self, response):
"""Generate a request for next response block.
This method is used by client after receiving
blockwise response from server with "more" flag set."""
request = copy.deepcopy(self)
request.payload = b""
request.mid = None
if response.opt.block2.block_number == 0 and response.opt.block2.size_exponent > DEFAULT_BLOCK_SIZE_EXP:
new_size_exponent = DEFAULT_BLOCK_SIZE_EXP
new_block_number = 2 ** (response.opt.block2.size_exponent - new_size_exponent)
request.opt.block2 = (new_block_number, False, new_size_exponent)
else:
request.opt.block2 = (response.opt.block2.block_number + 1, False, response.opt.block2.size_exponent)
request.opt.deleteOption(BLOCK1)
request.opt.deleteOption(OBSERVE)
return request
def generateNextBlock1Response(self):
"""Generate a response to acknowledge incoming request block.
This method is used by server after receiving
blockwise request from client with "more" flag set."""
response = Message(code=CHANGED, token=self.token )
response.remote = self.remote
if self.opt.block1.block_number == 0 and self.opt.block1.size_exponent > DEFAULT_BLOCK_SIZE_EXP:
new_size_exponent = DEFAULT_BLOCK_SIZE_EXP
response.opt.block1 = (0, True, new_size_exponent)
else:
response.opt.block1 = (self.opt.block1.block_number, True, self.opt.block1.size_exponent)
return response
def debugString(self):
"""Generate pretty string with message contents for debugging purposes"""
output = []
output.append("v:%d " % self.version)
output.append("t:%s " % types[self.mtype])
output.append("tkl:%d " % len(self.token))
output.append("")
return output
class Options(object):
"""Represent CoAP Header Options."""
def __init__(self):
self._options = {}
def decode(self, rawdata):
"""Decode all options in message from raw binary data."""
option_number = 0
while len(rawdata) > 0:
dllen = struct.unpack('!B', rawdata[:1])[0]
if dllen == 0xFF:
return rawdata[1:]
delta = (dllen & 0xF0) >> 4
length = (dllen & 0x0F)
rawdata = rawdata[1:]
(delta, rawdata) = readExtendedFieldValue(delta, rawdata)
(length, rawdata) = readExtendedFieldValue(length, rawdata)
option_number += delta
option = option_formats.get(option_number, OpaqueOption)(option_number)
option.decode(rawdata[:length])
self.addOption(option)
rawdata = rawdata[length:]
return ''
def encode(self):
"""Encode all options in option header into string of bytes."""
data = []
current_opt_num = 0
option_list = self.optionList()
for option in option_list:
delta, extended_delta = writeExtendedFieldValue(option.number - current_opt_num)
length, extended_length = writeExtendedFieldValue(option.length)
data.append(six.int2byte((((int(delta) & 0x0F) << 4) + (int(length) & 0x0F))))
data.append(extended_delta)
data.append(extended_length)
data.append(option.encode())
current_opt_num = option.number
return b"".join(data)
def addOption(self, option):
"""Add option into option header."""
self._options.setdefault(option.number, []).append(option)
def deleteOption(self, number):
"""Delete option from option header."""
if number in self._options:
self._options.pop(number)
def getOption (self, number):
"""Get option with specified number."""
return self._options.get(number)
def optionList(self):
return chain.from_iterable(sorted(self._options.values(), key=lambda x: x[0].number))
def _setUriPath(self, segments):
"""Convenience setter: Uri-Path option"""
if isinstance(segments, six.binary_type):
raise ValueError("URI Path should be passed as a list or tuple of segments")
self.deleteOption(number=URI_PATH)
for segment in segments:
self.addOption(StringOption(number=URI_PATH, value=six.binary_type(segment)))
def _getUriPath(self):
"""Convenience getter: Uri-Path option"""
segment_list = []
uri_path = self.getOption(number=URI_PATH)
if uri_path is not None:
for segment in uri_path:
segment_list.append(segment.value)
return segment_list
uri_path = property(_getUriPath, _setUriPath)
def _setUriQuery(self, segments):
"""Convenience setter: Uri-Query option"""
if isinstance(segments, six.binary_type):
raise ValueError("URI Query should be passed as a list or tuple of segments")
self.deleteOption(number=URI_QUERY)
for segment in segments:
self.addOption(StringOption(number=URI_QUERY, value=six.binary_type(segment)))
def _getUriQuery(self):
"""Convenience getter: Uri-Query option"""
segment_list = []
uri_query = self.getOption(number=URI_QUERY)
if uri_query is not None:
for segment in uri_query:
segment_list.append(segment.value)
return segment_list
uri_query = property(_getUriQuery, _setUriQuery)
def _setBlock2(self, block_tuple):
"""Convenience setter: Block2 option"""
self.deleteOption(number=BLOCK2)
self.addOption(BlockOption(number=BLOCK2, value=block_tuple))
def _getBlock2(self):
"""Convenience getter: Block2 option"""
block2 = self.getOption(number=BLOCK2)
if block2 is not None:
return block2[0].value
else:
return None
block2 = property(_getBlock2, _setBlock2)
def _setBlock1(self, block_tuple):
"""Convenience setter: Block1 option"""
self.deleteOption(number=BLOCK1)
self.addOption(BlockOption(number=BLOCK1, value=block_tuple))
def _getBlock1(self):
"""Convenience getter: Block1 option"""
block1 = self.getOption(number=BLOCK1)
if block1 is not None:
return block1[0].value
else:
return None
block1 = property(_getBlock1, _setBlock1)
def _setSize1(self, size1):
"""Convenience setter: Size1 option"""
self.deleteOption(number=SIZE1)
self.addOption(UintOption(number=SIZE1, value=size1))
def _getSize1(self):
"""Convenience getter: Size1 option"""
return self.getOption(number=SIZE1)
size1 = property(_getSize1, _setSize1)
def _setSize2(self, size2):
"""Convenience setter: Size2 option"""
self.deleteOption(number=SIZE2)
self.addOption(UintOption(number=SIZE2, value=size2))
def _getSize2(self):
"""Convenience getter: Size2 option"""
return self.getOption(number=SIZE2)
size2 = property(_getSize2, _setSize2)
def _setContentFormat(self, content_format):
"""Convenience setter: Content-Format option"""
self.deleteOption(number=CONTENT_FORMAT)
self.addOption(UintOption(number=CONTENT_FORMAT, value=content_format))
def _getContentFormat(self):
"""Convenience getter: Content-Format option"""
content_format = self.getOption(number=CONTENT_FORMAT)
if content_format is not None:
return content_format[0].value
else:
return None
content_format = property(_getContentFormat, _setContentFormat)
def _setETag(self, etag):
"""Convenience setter: ETag option"""
self.deleteOption(number=ETAG)
if etag is not None:
self.addOption(OpaqueOption(number=ETAG, value=etag))
def _getETag(self):
"""Convenience getter: ETag option"""
etag = self.getOption(number=ETAG)
if etag is not None:
return etag[0].value
else:
return None
etag = property(_getETag, _setETag, None, "Access to a single ETag on the message (as used in responses)")
def _setETags(self, etags):
self.deleteOption(number=ETAG)
for tag in etags:
self.addOption(OpaqueOption(number=ETAG, value=tag))
def _getETags(self):
etag = self.getOption(number=ETAG)
return [] if etag is None else [tag.value for tag in etag]
etags = property(_getETags, _setETags, None, "Access to a list of ETags on the message (as used in requests)")
def _setObserve(self, observe):
self.deleteOption(number=OBSERVE)
if observe is not None:
self.addOption(UintOption(number=OBSERVE, value=observe))
def _getObserve(self):
observe = self.getOption(number=OBSERVE)
if observe is not None:
return observe[0].value
else:
return None
observe = property(_getObserve, _setObserve)
def _setAccept(self, accept):
self.deleteOption(number=ACCEPT)
if accept is not None:
self.addOption(UintOption(number=ACCEPT, value=accept))
def _getAccept(self):
accept = self.getOption(number=ACCEPT)
if accept is not None:
return accept[0].value
else:
return None
accept = property(_getAccept, _setAccept)
def _setLocationPath(self, segments):
"""Convenience setter: Location-Path option"""
if isinstance(segments, six.binary_type):
raise ValueError("Location Path should be passed as a list or tuple of segments")
self.deleteOption(number=LOCATION_PATH)
for segment in segments:
self.addOption(StringOption(number=LOCATION_PATH, value=six.binary_type(segment)))
def _getLocationPath(self):
"""Convenience getter: Location-Path option"""
segment_list = []
location_path = self.getOption(number=LOCATION_PATH)
if location_path is not None:
for segment in location_path:
segment_list.append(segment.value)
return segment_list
location_path = property(_getLocationPath, _setLocationPath)
def readExtendedFieldValue(value, rawdata):
"""Used to decode large values of option delta and option length
from raw binary form."""
if value >= 0 and value < 13:
return (value, rawdata)
elif value == 13:
return (struct.unpack('!B', rawdata[:1])[0] + 13, rawdata[1:])
elif value == 14:
return (struct.unpack('!H', rawdata[:2])[0] + 269, rawdata[2:])
else:
raise ValueError("Value out of range.")
def writeExtendedFieldValue(value):
"""Used to encode large values of option delta and option length
into raw binary form.
In CoAP option delta and length can be represented by a variable
number of bytes depending on the value."""
if value >= 0 and value < 13:
return (value, b'')
elif value >= 13 and value < 269:
return (13, struct.pack('!B', value - 13))
elif value >= 269 and value < 65804:
return (14, struct.pack('!H', value - 269))
else:
raise ValueError("Value out of range.")
class OpaqueOption(object):
"""Opaque CoAP option - used to represent opaque options.
This is a default option type."""
def __init__(self, number, value=""):
self.value = value
self.number = number
def encode(self):
rawdata = self.value
return rawdata
def decode(self, rawdata):
self.value = rawdata # if rawdata is not None else ""
def _length(self):
return len(self.value)
length = property(_length)
class StringOption(object):
"""String CoAP option - used to represent string options."""
def __init__(self, number, value=""):
self.value = value
self.number = number
def encode(self):
rawdata = self.value
return rawdata
def decode(self, rawdata):
self.value = rawdata # if rawdata is not None else ""
def _length(self):
return len(self.value)
length = property(_length)
class UintOption(object):
"""Uint CoAP option - used to represent uint options."""
def __init__(self, number, value=0):
self.value = value
self.number = number
def encode(self):
rawdata = struct.pack("!L", self.value)
return rawdata.lstrip(six.int2byte(0))
def decode(self, rawdata):
value = 0
for byte in six.iterbytes(rawdata):
value = (value * 256) + byte
self.value = value
return self
def _length(self):
if self.value > 0:
return (self.value.bit_length() - 1) // 8 + 1
else:
return 0
length = property(_length)
class BlockOption(object):
"""Block CoAP option - special option used only for Block1 and Block2 options.
Currently it is the only type of CoAP options that has
internal structure."""
BlockwiseTuple = collections.namedtuple('BlockwiseTuple', ['block_number', 'more', 'size_exponent'])
def __init__(self, number, value=(0, None, 0)):
self.value = self.BlockwiseTuple._make(value)
self.number = number
def encode(self):
as_integer = (self.value[0] << 4) + (self.value[1] * 0x08) + self.value[2]
rawdata = struct.pack("!L", as_integer)
return rawdata.lstrip(six.int2byte(0))
def decode(self, rawdata):
as_integer = 0
for byte in six.iterbytes(rawdata):
as_integer = (as_integer * 256) + byte
self.value = self.BlockwiseTuple(block_number=(as_integer >> 4), more=bool(as_integer & 0x08), size_exponent=(as_integer & 0x07))
def _length(self):
return ((self.value[0].bit_length() + 3) / 8 + 1)
length = property(_length)
option_formats = {3: StringOption,
6: UintOption,
7: UintOption,
8: StringOption,
11: StringOption,
12: UintOption,
14: UintOption,
15: StringOption,
16: UintOption,
20: StringOption,
23: BlockOption,
27: BlockOption,
28: UintOption,
35: StringOption,
39: StringOption,
60: UintOption}
"""Dictionary used to assign option type to option numbers."""
def isRequest(code):
return True if (code >= 1 and code < 32) else False
def isResponse(code):
return True if (code >= 64 and code < 192) else False
def isSuccessful(code):
return True if (code >= 64 and code < 96) else False
def uriPathAsString(segment_list):
return b'/' + b'/'.join(segment_list)
class Coap(protocol.DatagramProtocol):
def __init__(self, endpoint):
"""Initialize a CoAP protocol instance."""
self.message_id = random.randint(0, 65535)
self.token = random.randint(0, 65535)
self.endpoint = endpoint
self.recent_local_ids = {} # recently received messages with IDs generated locally (identified by message ID and remote)
self.recent_remote_ids = {} # recently received messages with IDs generated by remote endpoints (identified by message ID and remote)
self.active_exchanges = {} # active exchanges i.e. sent CON messages (identified by message ID and remote)
self.outgoing_requests = {} # unfinished outgoing requests (identified by token and remote)
self.incoming_requests = {} # unfinished incoming requests (identified by URL path and remote)
self.observations = {} # outgoing observations. (token, remote) -> callback
def datagramReceived(self, data, remote):
host, port = remote
log.msg("Received %r from %s:%d" % (data, host, port))
message = Message.decode(data, (ip_address(host), port), self)
if self.deduplicateMessage(message) is True:
return
if isRequest(message.code):
self.processRequest(message)
elif isResponse(message.code):
self.processResponse(message)
elif message.code is EMPTY:
self.processEmpty(message)
def deduplicateMessage(self, message):
"""Check incoming message if it's a duplicate.
Duplicate is a message with the same Message ID (mid)
and sender (remote), as message received within last
EXCHANGE_LIFETIME seconds (usually 247 seconds)."""
def addMessageToRecent(cache, key):
expiration = reactor.callLater(EXCHANGE_LIFETIME, removeMessageFromRecent, cache, key)
cache[key] = (message, expiration)
def removeMessageFromRecent(cache, key):
cache.pop(key)
key = (message.mid, message.remote)
log.msg("Incoming Message ID: %d" % message.mid)
if message.mtype in (CON, NON):
if key in self.recent_remote_ids:
if message.mtype is CON:
if len(self.recent_remote_ids[key]) == 3:
log.msg('Duplicate CON received, sending old response again')
self.sendMessage(self.recent_remote_ids[key][2])
else:
log.msg('Duplicate CON received, no response to send')
else:
log.msg('Duplicate NON received')
return True
else:
log.msg('New unique CON or NON message received')
addMessageToRecent(self.recent_remote_ids, key)
return False
else:
if key in self.recent_local_ids:
log.msg('Duplicate ACK or RST received')
return True
else:
log.msg('New unique ACK or RST message received')
addMessageToRecent(self.recent_local_ids, key)
return False
def processResponse(self, response):
"""Method used for incoming response processing."""
def resetUnrecognized():
log.msg("Response not recognized - sending RST.")
rst = Message(mtype=RST, mid=response.mid, code=EMPTY, payload='')
rst.remote = response.remote
self.sendMessage(rst)
def ackIfConfirmable():
if response.mtype is CON:
ack = Message(mtype=ACK, mid=response.mid, code=EMPTY, payload="")
ack.remote = response.remote
self.sendMessage(ack)
if response.mtype is RST:
return
if response.mtype is ACK:
if response.mid in self.active_exchanges:
self.removeExchange(response)
else:
return
log.msg("Received Response, token: %s, host: %s, port: %s" % (codecs.encode(response.token, 'hex'), response.remote[0], response.remote[1]))
if (response.token, response.remote) in self.outgoing_requests:
self.outgoing_requests.pop((response.token, response.remote)).handleResponse(response)
ackIfConfirmable()
elif (response.token, response.remote) in self.observations:
## @TODO: deduplication based on observe option value
callback_tuple, original_request_uri_path = self.observations[(response.token, response.remote)]
callback, args, kw = callback_tuple
args = args or ()
kw = kw or {}
block2 = response.opt.block2
if block2 is None:
ackIfConfirmable()
callback(response, *args, **kw)
elif block2.block_number == 0:
ackIfConfirmable()
if block2.more is False:
callback(response, *args, **kw)
else:
request = Message(code=GET)
request.opt.uri_path = original_request_uri_path
request.remote = response.remote
request = request.generateNextBlock2Request(response)
requester = Requester(response.protocol, request, None, None, None,
None, None, None,
None, None, None)
requester.assembled_response = response
d = requester.deferred
d.addCallback( callback, *args, **kw)
else:
resetUnrecognized()
if response.opt.observe is None:
del self.observations[(response.token, response.remote)]
else:
resetUnrecognized()
def processRequest(self, request):
"""Method used for incoming request processing."""
if request.mtype not in (CON, NON):
response = Message(code=BAD_REQUEST, payload='Wrong message type for request!')
self.respond(response, request)
return
if (uriPathAsString(request.opt.uri_path), request.remote) in self.incoming_requests:
log.msg("Request pertains to earlier blockwise requests.")
self.incoming_requests.pop((uriPathAsString(request.opt.uri_path), request.remote)).handleNextRequest(request)
else:
responder = Responder(self, request)
def processEmpty(self, message):
if message.mtype is CON:
log.msg('Empty CON message received (CoAP Ping) - replying with RST.')
rst = Message(mtype=RST, mid=message.mid, code=EMPTY, payload='')
rst.remote = message.remote
self.sendMessage(rst)
#TODO: passing ACK/RESET info to application
#Currently it doesn't matter if empty ACK or RST is received - in both cases exchange has to be removed
if message.mid in self.active_exchanges and message.mtype in (ACK, RST):
self.removeExchange(message)
def sendMessage(self, message):
"""Set Message ID, encode and send message.
Also if message is Confirmable (CON) add Exchange"""
address, port = message.remote
host = str(address)
target = (host, port)
log.msg("Sending message to %s:%d" % (host, port))
recent_key = (message.mid, message.remote)
if recent_key in self.recent_remote_ids:
if len(self.recent_remote_ids[recent_key]) != 3:
self.recent_remote_ids[recent_key] = self.recent_remote_ids[recent_key] + (message,)
if message.mid is None:
message.mid = self.nextMessageID()
msg = message.encode()
self.transport.write(msg, target)
if message.mtype is CON:
self.addExchange(message)
log.msg("Message %r sent successfully" % msg)
def nextMessageID(self):
"""Reserve and return a new message ID."""
message_id = self.message_id
self.message_id = 0xFFFF & (1 + self.message_id)
return message_id
def nextToken(self):
"""Reserve and return a new Token for request."""
#TODO: add proper Token handling
token = self.token
self.token = (self.token + 1) & 0xffffffffffffffff
return codecs.decode((b"%08x" % self.token), "hex")
def addExchange(self, message):
"""Add an "exchange" for outgoing CON message.
CON (Confirmable) messages are automatically
retransmitted by protocol until ACK or RST message
with the same Message ID is received from target host."""
timeout = random.uniform(ACK_TIMEOUT, ACK_TIMEOUT * ACK_RANDOM_FACTOR)
retransmission_counter = 0
next_retransmission = reactor.callLater(timeout, self.retransmit, message, timeout, retransmission_counter)
self.active_exchanges[message.mid] = (message, next_retransmission)
log.msg("Exchange added, Message ID: %d." % message.mid)
def removeExchange(self, message):
"""Remove exchange from active exchanges and cancel the timeout
to next retransmission."""
self.active_exchanges.pop(message.mid)[1].cancel()