-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathcantcoap.cpp
1924 lines (1731 loc) · 54.8 KB
/
cantcoap.cpp
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
/*
Copyright (c) 2013, Ashley Mills.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// version, 2 bits
// type, 2 bits
// 00 Confirmable
// 01 Non-confirmable
// 10 Acknowledgement
// 11 Reset
// token length, 4 bits
// length of token in bytes (only 0 to 8 bytes allowed)
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include "cantcoap.h"
#include "arpa/inet.h"
#include "sysdep.h"
/// Memory-managed constructor. Buffer for PDU is dynamically sized and allocated by the object.
/**
* When using this constructor, the CoapPDU class will allocate space for the PDU.
* Contrast this with the parameterized constructors, which allow the use of an external buffer.
*
* Note, the PDU container and space can be reused by issuing a CoapPDU::reset(). If the new PDU exceeds the
* space of the previously allocated memory, then further memory will be dynamically allocated.
*
* Deleting the object will free the Object container and all dynamically allocated memory.
*
* \note It would have been nice to use something like UDP_CORK or MSG_MORE, to allow separate buffers
* for token, options, and payload but these FLAGS aren't implemented for UDP in LwIP so stuck with one buffer for now.
*
* CoAP version defaults to 1.
*
* \sa CoapPDU::CoapPDU(uint8_t *pdu, int pduLength), CoapPDU::CoapPDU::(uint8_t *buffer, int bufferLength, int pduLength),
* CoapPDU:CoapPDU()~
*
*/
CoapPDU::CoapPDU() {
// pdu
_pdu = (uint8_t*)calloc(4,sizeof(uint8_t));
_pduLength = 4;
_bufferLength = _pduLength;
//options
_numOptions = 0;
_maxAddedOptionNumber = 0;
// payload
_payloadPointer = NULL;
_payloadLength = 0;
_constructedFromBuffer = 0;
setVersion(1);
}
/// Construct a PDU using an external buffer. No copy of the buffer is made.
/**
* This constructor is normally used where a PDU has been received over the network, and it's length is known.
* In this case the CoapPDU object is probably going to be used as a temporary container to access member values.
*
* It is assumed that \b pduLength is the length of the actual CoAP PDU, and consequently the buffer will also be this size,
* contrast this with CoapPDU::CoapPDU(uint8_t *buffer, int bufferLength, int pduLength) which allows the buffer to
* be larger than the PDU.
*
* A PDU constructed in this manner must be validated with CoapPDU::validate() before the member variables will be accessible.
*
* \warning The validation call parses the PDU structure to set some internal parameters. If you do
* not validate the PDU, then the behaviour of member access functions will be undefined.
*
* The buffer can be reused by issuing a CoapPDU::reset() but the class will not change the size of the buffer. If the
* newly constructed PDU exceeds the size of the buffer, the function called (for example CoapPDU::addOption) will fail.
*
* Deleting this object will only delete the Object container and will not delete the PDU buffer.
*
* @param pdu A pointer to an array of bytes which comprise the CoAP PDU
* @param pduLength The length of the CoAP PDU pointed to by \b pdu
* \sa CoapPDU::CoapPDU(), CoapPDU::CoapPDU(uint8_t *buffer, int bufferLength, int pduLength)
*/
CoapPDU::CoapPDU(uint8_t *pdu, int pduLength) : CoapPDU(pdu,pduLength,pduLength) {
// delegated to CoapPDU::CoapPDU(uint8_t *buffer, int bufferLength, int pduLength)
}
/// Construct object from external buffer that may be larger than actual PDU.
/**
* This differs from CoapPDU::CoapPDU(uint8_t *pdu, int pduLength) in that the buffer may be larger
* than the actual CoAP PDU contained int the buffer. This is typically used when a large buffer is reused
* multiple times. Note that \b pduLength can be 0.
*
* If an actual CoAP PDU is passed in the buffer, \b pduLength should match its length. CoapPDU::validate() must
* be called to initiate the object before member functions can be used.
*
* A PDU constructed in this manner must be validated with CoapPDU::validate() before the member variables will be accessible.
*
* \warning The validation call parses the PDU structure to set some internal parameters. If you do
* not validate the PDU, then the behaviour of member access functions will be undefined.
*
* The buffer can be reused by issuing a CoapPDU::reset() but the class will not change the size of the buffer. If the
* newly constructed PDU exceeds the size of the buffer, the function called (for example CoapPDU::addOption) will fail.
*
* Deleting this object will only delete the Object container and will not delete the PDU buffer.
*
* \param buffer A buffer which either contains a CoAP PDU or is intended to be used to construct one.
* \param bufferLength The length of the buffer
* \param pduLength If the buffer contains a CoAP PDU, this specifies the length of the PDU within the buffer.
*
* \sa CoapPDU::CoapPDU(), CoapPDU::CoapPDU(uint8_t *pdu, int pduLength)
*/
CoapPDU::CoapPDU(uint8_t *buffer, int bufferLength, int pduLength) {
// sanity
if(pduLength<4&&pduLength!=0) {
DBG("PDU cannot have a length less than 4");
}
// pdu
_pdu = buffer;
_bufferLength = bufferLength;
if(pduLength==0) {
// this is actually a fresh pdu, header always exists
_pduLength = 4;
// make sure header is zeroed
_pdu[0] = 0x00; _pdu[1] = 0x00; _pdu[2] = 0x00; _pdu[3] = 0x00;
setVersion(1);
} else {
_pduLength = pduLength;
}
_constructedFromBuffer = 1;
// options
_numOptions = 0;
_maxAddedOptionNumber = 0;
// payload
_payloadPointer = NULL;
_payloadLength = 0;
}
/// Reset CoapPDU container so it can be reused to build a new PDU.
/**
* This resets the CoapPDU container, setting the pdu length, option count, etc back to zero. The
* PDU can then be populated as if it were newly constructed.
*
* Note that the space available will depend on how the CoapPDU was originally constructed:
* -# CoapPDU::CoapPDU()
*
* Available space initially be \b _pduLength. But further space will be allocated as needed on demand,
* limited only by the OS/environment.
*
* -# CoapPDU::CoapPDU(uint8_t *pdu, int pduLength)
*
* Space is limited by the variable \b pduLength. The PDU cannot exceed \b pduLength bytes.
*
* -# CoapPDU::CoapPDU(uint8_t *buffer, int bufferLength, int pduLength)
*
* Space is limited by the variable \b bufferLength. The PDU cannot exceed \b bufferLength bytes.
*
* \return 0 on success, 1 on failure.
*/
int CoapPDU::reset() {
// pdu
memset(_pdu,0x00,_bufferLength);
// packet always has at least a header
_pduLength = 4;
// options
_numOptions = 0;
_maxAddedOptionNumber = 0;
// payload
_payloadPointer = NULL;
_payloadLength = 0;
return 0;
}
/// Validates a PDU constructed using an external buffer.
/**
* When a CoapPDU is constructed using an external buffer, the programmer must call this function to
* check that the received PDU is a valid CoAP PDU.
*
* \warning The validation call parses the PDU structure to set some internal parameters. If you do
* not validate the PDU, then the behaviour of member access functions will be undefined.
*
* \return 1 if the PDU validates correctly, 0 if not. XXX maybe add some error codes
*/
int CoapPDU::validate() {
if(_pduLength<4) {
DBG("PDU has to be a minimum of 4 bytes. This: %d bytes",_pduLength);
return 0;
}
// check header
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |Ver| T | TKL | Code | Message ID |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Token (if any, TKL bytes) ...
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Options (if any) ...
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |1 1 1 1 1 1 1 1| Payload (if any) ...
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// version must be 1
int version = getVersion();
if (version != 1) {
DBG("Invalid version: %d", version);
return 0;
}
DBG("Version: %d", version);
DBG("Type: %d", getType());
// token length must be between 0 and 8
int tokenLength = getTokenLength();
if(tokenLength<0||tokenLength>8) {
DBG("Invalid token length: %d",tokenLength);
return 0;
}
DBG("Token length: %d",tokenLength);
// check total length
if((COAP_HDR_SIZE+tokenLength)>_pduLength) {
DBG("Token length would make pdu longer than actual length.");
return 0;
}
// check that code is valid
CoapPDU::Code code = getCode();
uint8_t cclass=((unsigned)code)>>5;
if(code<COAP_EMPTY || cclass>5) {
DBG("Invalid CoAP code: %d",code);
return 0;
}
DBG("CoAP code: %d",code);
// token can be anything so nothing to check
// check that options all make sense
uint16_t optionDelta =0, optionNumber = 0, optionValueLength = 0;
int totalLength = 0;
// first option occurs after token
int optionPos = COAP_HDR_SIZE + getTokenLength();
// may be 0 options
if(optionPos==_pduLength) {
DBG("No options. No payload.");
_numOptions = 0;
_payloadLength = 0;
return 1;
}
int bytesRemaining = _pduLength-optionPos;
int numOptions = 0;
uint8_t upperNibble = 0x00, lowerNibble = 0x00;
// walk over options and record information
while(1) {
// check for payload marker
if(bytesRemaining>0) {
uint8_t optionHeader = _pdu[optionPos];
if(optionHeader==0xFF) {
// payload
if(bytesRemaining>1) {
_payloadPointer = &_pdu[optionPos+1];
_payloadLength = (bytesRemaining-1);
_numOptions = numOptions;
DBG("Payload found, length: %d",_payloadLength);
return 1;
}
// payload marker but no payload
_payloadPointer = NULL;
_payloadLength = 0;
DBG("Payload marker but no payload.");
return 0;
}
// check that option delta and option length are valid values
upperNibble = (optionHeader & 0xF0) >> 4;
lowerNibble = (optionHeader & 0x0F);
if(upperNibble==0x0F||lowerNibble==0x0F) {
DBG("Expected option header or payload marker, got: 0x%x%x",upperNibble,lowerNibble);
return 0;
}
DBG("Option header byte appears sane: 0x%x%x",upperNibble,lowerNibble);
} else {
DBG("No more data. No payload.");
_payloadPointer = NULL;
_payloadLength = 0;
_numOptions = numOptions;
return 1;
}
// skip over option header byte
bytesRemaining--;
// check that there is enough space for the extended delta and length bytes (if any)
int headerBytesNeeded = computeExtraBytes(upperNibble);
DBG("%d extra bytes needed for extended delta",headerBytesNeeded);
if(headerBytesNeeded>bytesRemaining) {
DBG("Not enough space for extended option delta, needed %d, have %d.",headerBytesNeeded,bytesRemaining);
return 0;
}
headerBytesNeeded += computeExtraBytes(lowerNibble);
if(headerBytesNeeded>bytesRemaining) {
DBG("Not enough space for extended option length, needed %d, have %d.",
(headerBytesNeeded-computeExtraBytes(upperNibble)),bytesRemaining);
return 0;
}
DBG("Enough space for extended delta and length: %d, continuing.",headerBytesNeeded);
// extract option details
optionDelta = getOptionDelta(&_pdu[optionPos]);
optionNumber += optionDelta;
optionValueLength = getOptionValueLength(&_pdu[optionPos]);
DBG("Got option: %d with length %d",optionNumber,optionValueLength);
// compute total length
totalLength = 1; // mandatory header
totalLength += computeExtraBytes(optionDelta);
totalLength += computeExtraBytes(optionValueLength);
totalLength += optionValueLength;
// check there is enough space
if(optionPos+totalLength>_pduLength) {
DBG("Not enough space for option payload, needed %d, have %d.",(totalLength-headerBytesNeeded-1),_pduLength-optionPos);
return 0;
}
DBG("Enough space for option payload: %d %d",optionValueLength,(totalLength-headerBytesNeeded-1));
// recompute bytesRemaining
bytesRemaining -= totalLength;
bytesRemaining++; // correct for previous --
// move to next option
optionPos += totalLength;
// inc number of options XXX
numOptions++;
}
return 1;
}
/// Destructor. Does not free buffer if constructor passed an external buffer.
/**
* The destructor acts differently, depending on how the object was initially constructed (from buffer or not):
*
* -# CoapPDU::CoapPDU()
*
* Complete object is destroyed.
*
* -# CoapPDU::CoapPDU(uint8_t *pdu, int pduLength)
*
* Only object container is destroyed. \b pdu is left intact.
*
* -# CoapPDU::CoapPDU(uint8_t *buffer, int bufferLength, int pduLength)
*
* Only object container is destroyed. \b pdu is left intact.
*
*/
CoapPDU::~CoapPDU() {
if(!_constructedFromBuffer) {
free(_pdu);
}
}
/// Returns a pointer to the internal buffer.
uint8_t* CoapPDU::getPDUPointer() {
return _pdu;
}
/// Set the PDU length to the length specified.
/**
* This is used when re-using a PDU container before calling CoapPDU::validate() as it
* is not possible to deduce the length of a PDU since the payload has no length marker.
* \param len The length of the PDU
*/
void CoapPDU::setPDULength(int len) {
_pduLength = len;
}
/// Shorthand function for setting a resource URI.
/**
* Calls CoapPDU::setURI(uri,strlen(uri).
*/
int CoapPDU::setURI(char *uri) {
return setURI(uri,strlen(uri));
}
/// Shorthand function for setting a resource URI.
/**
* This will parse the supplied \b uri and construct enough URI_PATH and URI_QUERY options to encode it.
* The options are added to the PDU.
*
* At present only simple URI formatting is handled, only '/','?', and '&' separators, and no port or protocol specificaiton.
*
* The function will split on '/' and create URI_PATH elements until it either reaches the end of the string
* in which case it will stop or if it reaches '?' it will start splitting on '&' and create URI_QUERY elements
* until it reaches the end of the string.
*
* Here is an example:
*
* /a/b/c/d?x=1&y=2&z=3
*
* Will be broken into four URI_PATH elements "a", "b", "c", "d", and three URI_QUERY elements "x=1", "y=2", "z=3"
*
* TODO: Add protocol extraction, port extraction, and some malformity checking.
*
* \param uri The uri to parse.
* \param urilen The length of the uri to parse.
*
* \return 1 on success, 0 on failure.
*/
int CoapPDU::setURI(char *uri, int urilen) {
// only '/', '?', '&' and ascii chars allowed
// sanitation
if(urilen<=0||uri==NULL) {
DBG("Null or zero-length uri passed.");
return 1;
}
// single character URI path (including '/' case)
if(urilen==1) {
addOption(COAP_OPTION_URI_PATH,1,(uint8_t*)uri);
return 0;
}
// TODO, queries
// extract ? to mark where to stop processing path components
// and then process the query params
// local vars
char *startP=uri,*endP=NULL;
int oLen = 0;
char splitChar = '/';
int queryStageTriggered = 0;
uint16_t optionType = COAP_OPTION_URI_PATH;
while(1) {
// stop at end of string or query
if(*startP==0x00||*(startP+1)==0x00) {
break;
}
// ignore leading slash
if(*startP==splitChar) {
DBG("Skipping leading slash");
startP++;
}
// find next split point
endP = strchr(startP,splitChar);
// might not be another slash
if(endP==NULL) {
DBG("Ending out of slash");
// check if there is a ?
endP = strchr(startP,'?');
// done if no queries
if(endP==NULL) {
endP = uri+urilen;
} else {
queryStageTriggered = 1;
}
}
// get length of segment
oLen = endP-startP;
#ifdef DEBUG
char *b = (char*)malloc(oLen+1);
memcpy(b,startP,oLen);
b[oLen] = 0x00;
DBG("Adding URI_PATH %s",b);
free(b);
#endif
// add option
if(addOption(optionType,oLen,(uint8_t*)startP)!=0) {
DBG("Error adding option");
return 1;
}
startP = endP;
if(queryStageTriggered) {
splitChar = '&';
optionType = COAP_OPTION_URI_QUERY;
startP++;
queryStageTriggered = false;
}
}
return 0;
}
/// Shorthand for adding a URI QUERY to the option list.
/**
* Adds a new option to the CoAP PDU that encodes a URI_QUERY.
*
* \param query The uri query to encode.
* \return 0 on success, 1 on failure.
*/
int CoapPDU::addURIQuery(char *query) {
return addOption(COAP_OPTION_URI_QUERY,strlen(query),(uint8_t*)query);
}
/// Concatenates any URI_PATH elements and URI_QUERY elements into a single string.
/**
* Parses the PDU options and extracts all URI_PATH and URI_QUERY elements,
* concatenating them into a single string with slash and amphersand separators accordingly.
*
* The produced string will be NULL terminated.
*
* \param dst Buffer into which to copy the concatenated path elements.
* \param dstlen Length of buffer.
* \param outLen Pointer to integer, into which URI length will be placed.
*
* \return 0 on success, 1 on failure. \b outLen will contain the length of the concatenated elements.
*/
int CoapPDU::getURI(char *dst, int dstlen, int *outLen) {
if(outLen==NULL) {
DBG("Output length pointer is NULL");
return 1;
}
if(dst==NULL) {
DBG("NULL destination buffer");
*outLen = 0;
return 1;
}
// check destination space
if(dstlen<=0) {
*dst = 0x00;
*outLen = 0;
DBG("Destination buffer too small (0)!");
return 1;
}
// check option count
if(_numOptions==0) {
*dst = 0x00;
*outLen = 0;
return 0;
}
// get options
CoapPDU::CoapOption *options = getOptions();
if(options==NULL) {
*dst = 0x00;
*outLen = 0;
return 0;
}
// iterate over options to construct URI
CoapOption *o = NULL;
int bytesLeft = dstlen-1; // space for 0x00
int oLen = 0;
// add slash at beggining
if(bytesLeft>=1) {
*dst = '/';
dst++;
bytesLeft--;
} else {
DBG("No space for initial slash needed 1, got %d",bytesLeft);
free(options);
return 1;
}
char separator = '/';
int firstQuery = 1;
for(int i=0; i<_numOptions; i++) {
o = &options[i];
oLen = o->optionValueLength;
if(o->optionNumber==COAP_OPTION_URI_PATH||o->optionNumber==COAP_OPTION_URI_QUERY) {
// if the option is a query, change the separator to &
if(o->optionNumber==COAP_OPTION_URI_QUERY) {
if(firstQuery) {
// change previous '/' to a '?'
*(dst-1) = '?';
firstQuery = 0;
}
separator = '&';
}
// check space
if(oLen>bytesLeft) {
DBG("Destination buffer too small, needed %d, got %d",oLen,bytesLeft);
free(options);
return 1;
}
// case where single '/' exists
if(oLen==1&&o->optionValuePointer[0]=='/') {
*dst = 0x00;
*outLen = 1;
free(options);
return 0;
}
// copy URI path or query component
memcpy(dst,o->optionValuePointer,oLen);
// adjust counters
dst += oLen;
bytesLeft -= oLen;
// add separator following (don't know at this point if another option is coming)
if(bytesLeft>=1) {
*dst = separator;
dst++;
bytesLeft--;
} else {
DBG("Ran out of space after processing option");
free(options);
return 1;
}
}
}
// remove terminating separator
dst--;
bytesLeft++;
// add null terminating byte (always space since reserved)
*dst = 0x00;
*outLen = (dstlen-1)-bytesLeft;
free(options);
return 0;
}
/// Sets the CoAP version.
/**
* \param version CoAP version between 0 and 3.
* \return 0 on success, 1 on failure.
*/
int CoapPDU::setVersion(uint8_t version) {
if(version>3) {
return 0;
}
_pdu[0] &= 0x3F;
_pdu[0] |= (version << 6);
return 1;
}
/**
* Gets the CoAP Version.
* @return The CoAP version between 0 and 3.
*/
uint8_t CoapPDU::getVersion() {
return (_pdu[0]&0xC0)>>6;
}
/**
* Sets the type of this CoAP PDU.
* \param mt The type, one of:
* - COAP_CONFIRMABLE
* - COAP_NON_CONFIRMABLE
* - COAP_ACKNOWLEDGEMENT
* - COAP_RESET.
*/
void CoapPDU::setType(CoapPDU::Type mt) {
_pdu[0] &= 0xCF;
_pdu[0] |= mt;
}
/// Returns the type of the PDU.
CoapPDU::Type CoapPDU::getType() {
return (CoapPDU::Type)(_pdu[0]&0x30);
}
/// Set the token length.
/**
* \param tokenLength The length of the token in bytes, between 0 and 8.
* \return 0 on success, 1 on failure.
*/
int CoapPDU::setTokenLength(uint8_t tokenLength) {
if(tokenLength>8)
return 1;
_pdu[0] &= 0xF0;
_pdu[0] |= tokenLength;
return 0;
}
/// Returns the token length.
int CoapPDU::getTokenLength() {
return _pdu[0] & 0x0F;
}
/// Returns a pointer to the PDU token.
uint8_t* CoapPDU::getTokenPointer() {
if(getTokenLength()==0) {
return NULL;
}
return &_pdu[4];
}
/// Set the PDU token to the supplied byte sequence.
/**
* This sets the PDU token to \b token and sets the token length to \b tokenLength.
* \param token A sequence of bytes representing the token.
* \param tokenLength The length of the byte sequence.
* \return 0 on success, 1 on failure.
*/
int CoapPDU::setToken(uint8_t *token, uint8_t tokenLength) {
DBG("Setting token");
if(token==NULL) {
DBG("NULL pointer passed as token reference");
return 1;
}
if(tokenLength==0) {
DBG("Token has zero length");
return 1;
}
// if tokenLength has not changed, just copy the new value
uint8_t oldTokenLength = getTokenLength();
if(tokenLength==oldTokenLength) {
memcpy((void*)&_pdu[4],token,tokenLength);
return 0;
}
// otherwise compute new length of PDU
uint8_t oldPDULength = _pduLength;
_pduLength -= oldTokenLength;
_pduLength += tokenLength;
// now, have to shift old memory around, but shift direction depends
// whether pdu is now bigger or smaller
if(_pduLength>oldPDULength) {
// new PDU is bigger, need to allocate space for new PDU
if(!_constructedFromBuffer) {
uint8_t *newMemory = (uint8_t*)realloc(_pdu,_pduLength);
if(newMemory==NULL) {
// malloc failed
DBG("Failed to allocate memory for token");
_pduLength = oldPDULength;
return 1;
}
_pdu = newMemory;
_bufferLength = _pduLength;
} else {
// constructed from buffer, check space
if(_pduLength>_bufferLength) {
DBG("Buffer too small to contain token, needed %d, got %d.",_pduLength-oldPDULength,_bufferLength-oldPDULength);
_pduLength = oldPDULength;
return 1;
}
}
// and then shift everything after token up to end of new PDU
// memory overlaps so do this manually so to avoid additional mallocs
int shiftOffset = _pduLength-oldPDULength;
int shiftAmount = _pduLength-tokenLength-COAP_HDR_SIZE; // everything after token
shiftPDUUp(shiftOffset,shiftAmount);
// now copy the token into the new space and set official token length
memcpy((void*)&_pdu[4],token,tokenLength);
setTokenLength(tokenLength);
// and return success
return 0;
}
// new PDU is smaller, copy the new token value over the old one
memcpy((void*)&_pdu[4],token,tokenLength);
// and shift everything after the new token down
int startLocation = COAP_HDR_SIZE+tokenLength;
int shiftOffset = oldPDULength-_pduLength;
int shiftAmount = oldPDULength-oldTokenLength-COAP_HDR_SIZE;
shiftPDUDown(startLocation,shiftOffset,shiftAmount);
// then reduce size of buffer
if(!_constructedFromBuffer) {
uint8_t *newMemory = (uint8_t*)realloc(_pdu,_pduLength);
if(newMemory==NULL) {
// malloc failed, PDU in inconsistent state
DBG("Failed to shrink PDU for new token. PDU probably broken");
return 1;
}
_pdu = newMemory;
_bufferLength = _pduLength;
}
// and officially set the new tokenLength
setTokenLength(tokenLength);
return 0;
}
/// Sets the CoAP response code
void CoapPDU::setCode(CoapPDU::Code code) {
_pdu[1] = code;
// there is a limited set of response codes
}
/// Gets the CoAP response code
CoapPDU::Code CoapPDU::getCode() {
return (CoapPDU::Code)_pdu[1];
}
/// Converts a http status code as an integer, to a CoAP code.
/**
* \param httpStatus the HTTP status code as an integer (e.g 200)
* \return The correct corresponding CoapPDU::Code on success,
* CoapPDU::COAP_UNDEFINED_CODE on failure.
*/
CoapPDU::Code CoapPDU::httpStatusToCode(int httpStatus) {
switch(httpStatus) {
case 1:
return CoapPDU::COAP_GET;
case 2:
return CoapPDU::COAP_POST;
case 3:
return CoapPDU::COAP_PUT;
case 4:
return CoapPDU::COAP_DELETE;
case 201:
return CoapPDU::COAP_CREATED;
case 202:
return CoapPDU::COAP_DELETED;
case 203:
return CoapPDU::COAP_VALID;
case 204:
return CoapPDU::COAP_CHANGED;
case 205:
return CoapPDU::COAP_CONTENT;
case 400:
return CoapPDU::COAP_BAD_REQUEST;
case 401:
return CoapPDU::COAP_UNAUTHORIZED;
case 402:
return CoapPDU::COAP_BAD_OPTION;
case 403:
return CoapPDU::COAP_FORBIDDEN;
case 404:
return CoapPDU::COAP_NOT_FOUND;
case 405:
return CoapPDU::COAP_METHOD_NOT_ALLOWED;
case 406:
return CoapPDU::COAP_NOT_ACCEPTABLE;
case 412:
return CoapPDU::COAP_PRECONDITION_FAILED;
case 413:
return CoapPDU::COAP_REQUEST_ENTITY_TOO_LARGE;
case 415:
return CoapPDU::COAP_UNSUPPORTED_CONTENT_FORMAT;
case 500:
return CoapPDU::COAP_INTERNAL_SERVER_ERROR;
case 501:
return CoapPDU::COAP_NOT_IMPLEMENTED;
case 502:
return CoapPDU::COAP_BAD_GATEWAY;
case 503:
return CoapPDU::COAP_SERVICE_UNAVAILABLE;
case 504:
return CoapPDU::COAP_GATEWAY_TIMEOUT;
case 505:
return CoapPDU::COAP_PROXYING_NOT_SUPPORTED;
default:
return CoapPDU::COAP_UNDEFINED_CODE;
}
}
/// Set messageID to the supplied value.
/**
* \param messageID A 16bit message id.
* \return 0 on success, 1 on failure.
*/
int CoapPDU::setMessageID(uint16_t messageID) {
// message ID is stored in network byte order
uint8_t *to = &_pdu[2];
endian_store16(to, messageID);
return 0;
}
/// Returns the 16 bit message ID of the PDU.
uint16_t CoapPDU::getMessageID() {
// mesasge ID is stored in network byteorder
uint8_t *from = &_pdu[2];
uint16_t messageID = endian_load16(uint16_t, from);
return messageID;
}
/// Returns the length of the PDU.
int CoapPDU::getPDULength() {
return _pduLength;
}
/// Return the number of options that the PDU has.
int CoapPDU::getNumOptions() {
return _numOptions;
}
/**
* This returns the options as a sequence of structs.
*/
CoapPDU::CoapOption* CoapPDU::getOptions() {
DBG("getOptions() called, %d options.",_numOptions);
uint16_t optionDelta =0, optionNumber = 0, optionValueLength = 0;
int totalLength = 0;
if(_numOptions==0) {
return NULL;
}
// malloc space for options
CoapOption *options = (CoapOption*)malloc(_numOptions*sizeof(CoapOption));
if(options==NULL) {
DBG("Failed to allocate memory for options.");
return NULL;
}
// first option occurs after token
int optionPos = COAP_HDR_SIZE + getTokenLength();
// walk over options and record information
for(int i=0; i<_numOptions; i++) {
// extract option details
optionDelta = getOptionDelta(&_pdu[optionPos]);
optionNumber += optionDelta;
optionValueLength = getOptionValueLength(&_pdu[optionPos]);
// compute total length
totalLength = 1; // mandatory header
totalLength += computeExtraBytes(optionDelta);
totalLength += computeExtraBytes(optionValueLength);
totalLength += optionValueLength;
// record option details
options[i].optionNumber = optionNumber;
options[i].optionDelta = optionDelta;
options[i].optionValueLength = optionValueLength;
options[i].totalLength = totalLength;
options[i].optionPointer = &_pdu[optionPos];
options[i].optionValuePointer = &_pdu[optionPos+totalLength-optionValueLength];
// move to next option
optionPos += totalLength;
}
return options;
}
/// Add an option to the PDU.
/**
* Unlike other implementations, options can be added in any order, and in-memory manipulation will be
* performed to ensure the correct ordering of options (they use a delta encoding of option numbers).
* Re-ordering memory like this incurs a small performance cost, so if you care about this, then you
* might want to add options in ascending order of option number.
* \param optionNumber The number of the option, see the enum CoapPDU::Option for shorthand notations.
* \param optionLength The length of the option payload in bytes.
* \param optionValue A pointer to the byte sequence that is the option payload (bytes will be copied).
* \return 0 on success, 1 on failure.
*/
int CoapPDU::addOption(uint16_t insertedOptionNumber, uint16_t optionValueLength, uint8_t *optionValue) {
// this inserts the option in memory, and re-computes the deltas accordingly
// prevOption <-- insertionPosition
// nextOption
// find insertion location and previous option number
uint16_t prevOptionNumber = 0; // option number of option before insertion point
int insertionPosition = findInsertionPosition(insertedOptionNumber,&prevOptionNumber);
DBG("inserting option at position %d, after option with number: %hu",insertionPosition,prevOptionNumber);
// compute option delta length
uint16_t optionDelta = insertedOptionNumber-prevOptionNumber;
uint8_t extraDeltaBytes = computeExtraBytes(optionDelta);
// compute option length length
uint16_t extraLengthBytes = computeExtraBytes(optionValueLength);
// compute total length of option
uint16_t optionLength = COAP_OPTION_HDR_BYTE + extraDeltaBytes + extraLengthBytes + optionValueLength;
// if this is at the end of the PDU, job is done, just malloc and insert