Merge remote-tracking branch 'origin/routing-manager'
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / caprotocolmessage.c
1 /******************************************************************
2  *
3  * Copyright 2014 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  ******************************************************************/
20
21 // Defining _BSD_SOURCE or _DEFAULT_SOURCE causes header files to expose
22 // definitions that may otherwise be skipped. Skipping can cause implicit
23 // declaration warnings and/or bugs and subtle problems in code execution.
24 // For glibc information on feature test macros,
25 // Refer http://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html
26 //
27 // This file requires #define use due to random() and srandom()
28 // For details on compatibility and glibc support,
29 // Refer http://www.gnu.org/software/libc/manual/html_node/BSD-Random.html
30 #define _DEFAULT_SOURCE
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <stdbool.h>
36 #ifdef HAVE_TIME_H
37 #include <time.h>
38 #endif
39
40 #include "caprotocolmessage.h"
41 #include "logger.h"
42 #include "oic_malloc.h"
43 #include "oic_string.h"
44
45 // ARM GCC compiler doesnt define srandom function.
46 #if defined(ARDUINO) && !defined(ARDUINO_ARCH_SAM)
47 #define HAVE_SRANDOM 1
48 #endif
49
50 #define TAG "CA_PRTCL_MSG"
51
52 /**
53  * @def VERIFY_NON_NULL_RET
54  * @brief Macro to verify the validity of input argument
55  */
56 #define VERIFY_NON_NULL_RET(arg, log_tag, log_message,ret) \
57     if (NULL == arg ){ \
58         OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
59         return ret; \
60     }
61
62 #define CA_BUFSIZE (128)
63 #define CA_PDU_MIN_SIZE (4)
64 #define CA_PORT_BUFFER_SIZE (4)
65
66 static const char COAP_URI_HEADER[] = "coap://[::]/";
67
68 static unsigned int SEED = 0;
69
70 CAResult_t CAGetRequestInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
71                                    CARequestInfo_t *outReqInfo)
72 {
73     OIC_LOG(DEBUG, TAG, "IN");
74
75     if (NULL == pdu || NULL == outReqInfo)
76     {
77         OIC_LOG(ERROR, TAG, "parameter is null");
78         return CA_STATUS_INVALID_PARAM;
79     }
80
81     uint32_t code = CA_NOT_FOUND;
82     CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &(outReqInfo->info));
83     outReqInfo->method = code;
84
85     OIC_LOG(DEBUG, TAG, "OUT");
86     return ret;
87 }
88
89 CAResult_t CAGetResponseInfoFromPDU(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,
90                                     const CAEndpoint_t *endpoint)
91 {
92     OIC_LOG(DEBUG, TAG, "IN");
93
94     if (NULL == pdu || NULL == outResInfo)
95     {
96         OIC_LOG(ERROR, TAG, "parameter is null");
97         return CA_STATUS_INVALID_PARAM;
98     }
99
100     uint32_t code = CA_NOT_FOUND;
101     CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &(outResInfo->info));
102     outResInfo->result = code;
103
104     OIC_LOG(DEBUG, TAG, "OUT");
105     return ret;
106 }
107
108 CAResult_t CAGetErrorInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
109                                  CAErrorInfo_t *errorInfo)
110 {
111     OIC_LOG(DEBUG, TAG, "IN");
112
113     if (!pdu)
114     {
115         OIC_LOG(ERROR, TAG, "parameter is null");
116         return CA_STATUS_INVALID_PARAM;
117     }
118
119     uint32_t code = 0;
120     CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &errorInfo->info);
121     OIC_LOG(DEBUG, TAG, "OUT");
122     return ret;
123 }
124
125 coap_pdu_t *CAGeneratePDU(uint32_t code, const CAInfo_t *info, const CAEndpoint_t *endpoint)
126 {
127     OIC_LOG(DEBUG, TAG, "IN");
128
129     VERIFY_NON_NULL_RET(info, TAG, "info", NULL);
130     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", NULL);
131
132     coap_pdu_t *pdu = NULL;
133
134     // RESET have to use only 4byte (empty message)
135     // and ACKNOWLEDGE can use empty message when code is empty.
136     if (CA_MSG_RESET == info->type || (CA_EMPTY == code && CA_MSG_ACKNOWLEDGE == info->type))
137     {
138         OIC_LOG(DEBUG, TAG, "code is empty");
139         if (!(pdu = CAGeneratePDUImpl((code_t) code, info, endpoint, NULL)))
140         {
141             OIC_LOG(ERROR, TAG, "pdu NULL");
142             return NULL;
143         }
144     }
145     else
146     {
147         coap_list_t *optlist = NULL;
148
149         if (CA_MSG_ACKNOWLEDGE != info->type)
150         {
151             const char *uri = info->resourceUri;
152             if (NULL == uri)
153             {
154                 OIC_LOG(ERROR, TAG, "uri NULL");
155                 return NULL;
156             }
157
158             uint32_t length = strlen(uri);
159             if (CA_MAX_URI_LENGTH < length)
160             {
161                 OIC_LOG(ERROR, TAG, "URI len err");
162                 return NULL;
163             }
164
165             uint32_t uriLength = length + sizeof(COAP_URI_HEADER);
166             char *coapUri = (char *) OICCalloc(1, uriLength);
167             if (NULL == coapUri)
168             {
169                 OIC_LOG(ERROR, TAG, "out of memory");
170                 return NULL;
171             }
172             OICStrcat(coapUri, uriLength, COAP_URI_HEADER);
173             OICStrcat(coapUri, uriLength, uri);
174
175             // parsing options in URI
176             CAResult_t res = CAParseURI(coapUri, &optlist);
177             if (CA_STATUS_OK != res)
178             {
179                 if (optlist)
180                 {
181                     coap_delete_list(optlist);
182                 }
183                 OICFree(coapUri);
184                 return NULL;
185             }
186
187             OICFree(coapUri);
188         }
189         // parsing options in HeadOption
190         CAResult_t ret = CAParseHeadOption(code, info, &optlist);
191         if (CA_STATUS_OK != ret)
192         {
193             coap_delete_list(optlist);
194             return NULL;
195         }
196
197         pdu = CAGeneratePDUImpl((code_t) code, info, endpoint, optlist);
198         if (NULL == pdu)
199         {
200             OIC_LOG(ERROR, TAG, "pdu NULL");
201             coap_delete_list(optlist);
202             return NULL;
203         }
204
205         // free option list
206         coap_delete_list(optlist);
207     }
208
209     // pdu print method : coap_show_pdu(pdu);
210     OIC_LOG(DEBUG, TAG, "OUT");
211     return pdu;
212 }
213
214 coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode,
215                        const CAEndpoint_t *endpoint)
216 {
217     OIC_LOG(DEBUG, TAG, "IN");
218
219     if (NULL == data)
220     {
221         OIC_LOG(ERROR, TAG, "data is null");
222         return NULL;
223     }
224
225     coap_transport_type transport;
226 #ifdef TCP_ADAPTER
227     if (CA_ADAPTER_TCP == endpoint->adapter)
228     {
229         transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)data)[0] >> 4);
230     }
231     else
232 #endif
233     {
234         transport = coap_udp;
235     }
236
237     coap_pdu_t *outpdu = coap_new_pdu(transport, length);
238     if (NULL == outpdu)
239     {
240         OIC_LOG(ERROR, TAG, "outpdu is null");
241         return NULL;
242     }
243
244     OIC_LOG_V(DEBUG, TAG, "pdu parse-transport type : %d", transport);
245
246     int ret = coap_pdu_parse((unsigned char *) data, length, outpdu, transport);
247     OIC_LOG_V(DEBUG, TAG, "pdu parse ret: %d", ret);
248     if (0 >= ret)
249     {
250         OIC_LOG(ERROR, TAG, "pdu parse failed");
251         coap_delete_pdu(outpdu);
252         return NULL;
253     }
254
255 #ifdef TCP_ADAPTER
256     if (CA_ADAPTER_TCP == endpoint->adapter)
257     {
258         OIC_LOG(INFO, TAG, "there is no version info in coap header");
259     }
260     else
261 #endif
262     {
263         if (outpdu->hdr->coap_hdr_udp_t.version != COAP_DEFAULT_VERSION)
264         {
265             OIC_LOG_V(ERROR, TAG, "coap version is not available : %d",
266                       outpdu->hdr->coap_hdr_udp_t.version);
267             coap_delete_pdu(outpdu);
268             return NULL;
269         }
270         if (outpdu->hdr->coap_hdr_udp_t.token_length > CA_MAX_TOKEN_LEN)
271         {
272             OIC_LOG_V(ERROR, TAG, "token length has been exceed : %d",
273                       outpdu->hdr->coap_hdr_udp_t.token_length);
274             coap_delete_pdu(outpdu);
275             return NULL;
276         }
277     }
278
279     if (outCode)
280     {
281         (*outCode) = (uint32_t) CA_RESPONSE_CODE(coap_get_code(outpdu, transport));
282     }
283
284     OIC_LOG(DEBUG, TAG, "OUT");
285     return outpdu;
286 }
287
288 coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
289                               const CAEndpoint_t *endpoint, coap_list_t *options)
290 {
291     OIC_LOG(DEBUG, TAG, "IN");
292     VERIFY_NON_NULL_RET(info, TAG, "info", NULL);
293     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", NULL);
294
295     coap_transport_type transport;
296     unsigned int length = COAP_MAX_PDU_SIZE;
297 #ifdef TCP_ADAPTER
298     unsigned int headerLength = 0;
299     if (CA_ADAPTER_TCP == endpoint->adapter)
300     {
301         if (options)
302         {
303             for (coap_list_t *opt = options; opt; opt = opt->next)
304             {
305                 headerLength += COAP_OPTION_LENGTH(*(coap_option *) opt->data) + 1;
306             }
307         }
308
309         if (info->payloadSize > 0)
310         {
311             headerLength = headerLength + info->payloadSize + 1;
312         }
313         transport = coap_get_tcp_header_type_from_size(headerLength);
314         length = headerLength + coap_get_tcp_header_length_for_transport(transport)
315                 + info->tokenLength;
316     }
317     else
318 #endif
319     {
320         transport = coap_udp;
321     }
322
323     coap_pdu_t *pdu = coap_new_pdu(transport, length);
324
325     if (NULL == pdu)
326     {
327         OIC_LOG(ERROR, TAG, "malloc failed");
328         return NULL;
329     }
330
331     OIC_LOG_V(DEBUG, TAG, "transport type: %d, payload size: %d",
332               transport, info->payloadSize);
333
334 #ifdef TCP_ADAPTER
335     if (CA_ADAPTER_TCP == endpoint->adapter)
336     {
337         coap_add_length(pdu, transport, headerLength);
338     }
339     else
340 #endif
341     {
342         OIC_LOG_V(DEBUG, TAG, "msgID is %d", info->messageId);
343         uint16_t message_id;
344         if (0 == info->messageId)
345         {
346             /* initialize message id */
347             prng((uint8_t * ) &message_id, sizeof(message_id));
348
349             OIC_LOG_V(DEBUG, TAG, "gen msg id=%d", message_id);
350         }
351         else
352         {
353             /* use saved message id */
354             message_id = info->messageId;
355         }
356         pdu->hdr->coap_hdr_udp_t.id = message_id;
357         OIC_LOG_V(DEBUG, TAG, "messageId in pdu is %d, %d", message_id, pdu->hdr->coap_hdr_udp_t.id);
358
359         pdu->hdr->coap_hdr_udp_t.type = info->type;
360     }
361
362     coap_add_code(pdu, transport, code);
363
364     if (info->token && CA_EMPTY != code)
365     {
366         uint32_t tokenLength = info->tokenLength;
367         OIC_LOG_V(DEBUG, TAG, "token info token length: %d, token :", tokenLength);
368         OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *)info->token, tokenLength);
369
370         int32_t ret = coap_add_token(pdu, tokenLength, (unsigned char *)info->token, transport);
371         if (0 == ret)
372         {
373             OIC_LOG(ERROR, TAG, "can't add token");
374         }
375     }
376
377     if (options)
378     {
379         for (coap_list_t *opt = options; opt; opt = opt->next)
380         {
381             OIC_LOG_V(DEBUG, TAG, "[%s] opt will be added.",
382                       COAP_OPTION_DATA(*(coap_option *) opt->data));
383
384             OIC_LOG_V(DEBUG, TAG, "[%d] pdu length", pdu->length);
385             coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
386                             COAP_OPTION_LENGTH(*(coap_option *) opt->data),
387                             COAP_OPTION_DATA(*(coap_option *) opt->data), transport);
388         }
389     }
390
391     OIC_LOG_V(DEBUG, TAG, "[%d] pdu length after option", pdu->length);
392
393     bool enabledPayload = false;
394 #ifndef WITH_BWT
395     enabledPayload = true;
396 #endif
397
398     if (enabledPayload || CA_ADAPTER_GATT_BTLE == endpoint->adapter
399 #ifdef TCP_ADAPTER
400             || CA_ADAPTER_TCP == endpoint->adapter
401 #endif
402             )
403     {
404         if (NULL != info->payload && 0 < info->payloadSize)
405         {
406             OIC_LOG(DEBUG, TAG, "payload is added");
407             coap_add_data(pdu, info->payloadSize, (const unsigned char *) info->payload);
408         }
409     }
410
411     OIC_LOG(DEBUG, TAG, "OUT");
412     return pdu;
413 }
414
415 CAResult_t CAParseURI(const char *uriInfo, coap_list_t **optlist)
416 {
417     OIC_LOG(DEBUG, TAG, "IN");
418
419     if (NULL == uriInfo)
420     {
421         OIC_LOG(ERROR, TAG, "uriInfo is null");
422         return CA_STATUS_INVALID_PARAM;
423     }
424
425     OIC_LOG_V(DEBUG, TAG, "url : %s", uriInfo);
426
427     if (NULL == optlist)
428     {
429         OIC_LOG(ERROR, TAG, "optlist is null");
430         return CA_STATUS_INVALID_PARAM;
431     }
432
433     /* split arg into Uri-* options */
434     coap_uri_t uri;
435     coap_split_uri((unsigned char *) uriInfo, strlen(uriInfo), &uri);
436
437     if (uri.port != COAP_DEFAULT_PORT)
438     {
439         unsigned char portbuf[CA_PORT_BUFFER_SIZE] = { 0 };
440         int ret = coap_insert(optlist,
441                               CACreateNewOptionNode(COAP_OPTION_URI_PORT,
442                                                     coap_encode_var_bytes(portbuf, uri.port),
443                                                     (char *)portbuf),
444                               CAOrderOpts);
445         if (ret <= 0)
446         {
447             return CA_STATUS_INVALID_PARAM;
448         }
449     }
450
451     if (uri.path.s && uri.path.length)
452     {
453         CAResult_t ret = CAParseUriPartial(uri.path.s, uri.path.length,
454                                            COAP_OPTION_URI_PATH, optlist);
455         if (CA_STATUS_OK != ret)
456         {
457             OIC_LOG(ERROR, TAG, "CAParseUriPartial failed(uri path)");
458             return ret;
459         }
460     }
461
462     if (uri.query.s && uri.query.length)
463     {
464         CAResult_t ret = CAParseUriPartial(uri.query.s, uri.query.length, COAP_OPTION_URI_QUERY,
465                                            optlist);
466         if (CA_STATUS_OK != ret)
467         {
468             OIC_LOG(ERROR, TAG, "CAParseUriPartial failed(uri query)");
469             return ret;
470         }
471     }
472
473     OIC_LOG(DEBUG, TAG, "OUT");
474     return CA_STATUS_OK;
475 }
476
477 CAResult_t CAParseUriPartial(const unsigned char *str, size_t length, int target,
478                              coap_list_t **optlist)
479 {
480     if (!optlist)
481     {
482         OIC_LOG(ERROR, TAG, "optlist is null");
483         return CA_STATUS_INVALID_PARAM;
484     }
485
486     if ((target != COAP_OPTION_URI_PATH) && (target != COAP_OPTION_URI_QUERY))
487     {
488         // should never occur. Log just in case.
489         OIC_LOG(DEBUG, TAG, "Unexpected URI component.");
490         return CA_NOT_SUPPORTED;
491     }
492     else if (str && length)
493     {
494         unsigned char uriBuffer[CA_BUFSIZE] = { 0 };
495         unsigned char *pBuf = uriBuffer;
496         size_t buflen = sizeof(uriBuffer);
497         int res = (target == COAP_OPTION_URI_PATH) ? coap_split_path(str, length, pBuf, &buflen) :
498                                                      coap_split_query(str, length, pBuf, &buflen);
499
500         if (res > 0)
501         {
502             size_t prevIdx = 0;
503             while (res--)
504             {
505                 int ret = coap_insert(optlist,
506                                       CACreateNewOptionNode(target, COAP_OPT_LENGTH(pBuf),
507                                                             (char *)COAP_OPT_VALUE(pBuf)),
508                                       CAOrderOpts);
509                 if (ret <= 0)
510                 {
511                     return CA_STATUS_INVALID_PARAM;
512                 }
513
514                 size_t optSize = COAP_OPT_SIZE(pBuf);
515                 if ((prevIdx + optSize) < buflen)
516                 {
517                     pBuf += optSize;
518                     prevIdx += optSize;
519                 }
520             }
521         }
522         else
523         {
524             OIC_LOG_V(ERROR, TAG, "Problem parsing URI : %d for %d", res, target);
525             return CA_STATUS_FAILED;
526         }
527     }
528     else
529     {
530         OIC_LOG(ERROR, TAG, "str or length is not available");
531         return CA_STATUS_FAILED;
532     }
533
534     return CA_STATUS_OK;
535 }
536
537 CAResult_t CAParseHeadOption(uint32_t code, const CAInfo_t *info, coap_list_t **optlist)
538 {
539     (void)code;
540     OIC_LOG(DEBUG, TAG, "IN");
541     VERIFY_NON_NULL_RET(info, TAG, "info is NULL", CA_STATUS_INVALID_PARAM);
542
543     OIC_LOG_V(DEBUG, TAG, "parse Head Opt: %d", info->numOptions);
544
545     if (!optlist)
546     {
547         OIC_LOG(ERROR, TAG, "optlist is null");
548         return CA_STATUS_INVALID_PARAM;
549     }
550
551     for (uint32_t i = 0; i < info->numOptions; i++)
552     {
553         if(!(info->options + i))
554         {
555             OIC_LOG(ERROR, TAG, "options is not available");
556             return CA_STATUS_FAILED;
557         }
558
559         uint32_t id = (info->options + i)->optionID;
560         if (COAP_OPTION_URI_PATH == id || COAP_OPTION_URI_QUERY == id)
561         {
562             OIC_LOG_V(DEBUG, TAG, "not Header Opt: %d", id);
563         }
564         else
565         {
566             OIC_LOG_V(DEBUG, TAG, "Head opt ID: %d", id);
567             OIC_LOG_V(DEBUG, TAG, "Head opt data: %s", (info->options + i)->optionData);
568             OIC_LOG_V(DEBUG, TAG, "Head opt length: %d", (info->options + i)->optionLength);
569             int ret = coap_insert(optlist,
570                                   CACreateNewOptionNode(id, (info->options + i)->optionLength,
571                                                         (info->options + i)->optionData),
572                                   CAOrderOpts);
573             if (ret <= 0)
574             {
575                 return CA_STATUS_INVALID_PARAM;
576             }
577         }
578     }
579
580     // insert one extra header with the payload format if applicable.
581     if (CA_FORMAT_UNDEFINED != info->payloadFormat)
582     {
583         coap_list_t* node = NULL;
584         uint8_t buf[3] = {0};
585         switch (info->payloadFormat) {
586             case CA_FORMAT_APPLICATION_CBOR:
587                 node = CACreateNewOptionNode(
588                         COAP_OPTION_CONTENT_FORMAT,
589                         coap_encode_var_bytes(buf, (uint16_t)COAP_MEDIATYPE_APPLICATION_CBOR),
590                         (char *)buf);
591                 break;
592             default:
593                 OIC_LOG_V(ERROR, TAG, "format option:[%d] not supported", info->payloadFormat);
594         }
595         if (!node)
596         {
597             OIC_LOG(ERROR, TAG, "format option not created");
598             return CA_STATUS_INVALID_PARAM;
599         }
600         int ret = coap_insert(optlist, node, CAOrderOpts);
601         if (ret <= 0)
602         {
603             coap_delete(node);
604             OIC_LOG(ERROR, TAG, "format option not inserted in header");
605             return CA_STATUS_INVALID_PARAM;
606         }
607     }
608     if (CA_FORMAT_UNDEFINED != info->acceptFormat)
609     {
610         coap_list_t* node = NULL;
611         uint8_t buf[3] = {0};
612         switch (info->acceptFormat) {
613             case CA_FORMAT_APPLICATION_CBOR:
614                 node = CACreateNewOptionNode(
615                         COAP_OPTION_ACCEPT,
616                         coap_encode_var_bytes(buf, (uint16_t)COAP_MEDIATYPE_APPLICATION_CBOR),
617                         (char *)buf);
618                 break;
619             default:
620                 OIC_LOG_V(ERROR, TAG, "format option:[%d] not supported", info->acceptFormat);
621         }
622         if (!node)
623         {
624             OIC_LOG(ERROR, TAG, "format option not created");
625             return CA_STATUS_INVALID_PARAM;
626         }
627         int ret = coap_insert(optlist, node, CAOrderOpts);
628         if (ret <= 0)
629         {
630             coap_delete(node);
631             OIC_LOG(ERROR, TAG, "format option not inserted in header");
632             return CA_STATUS_INVALID_PARAM;
633         }
634     }
635
636     OIC_LOG(DEBUG, TAG, "OUT");
637     return CA_STATUS_OK;
638 }
639
640 coap_list_t *CACreateNewOptionNode(uint16_t key, uint32_t length, const char *data)
641 {
642     OIC_LOG(DEBUG, TAG, "IN");
643
644     if (!data)
645     {
646         OIC_LOG(ERROR, TAG, "invalid pointer parameter");
647         return NULL;
648     }
649
650     coap_option *option = coap_malloc(sizeof(coap_option) + length + 1);
651     if (!option)
652     {
653         OIC_LOG(ERROR, TAG, "Out of memory");
654         return NULL;
655     }
656     memset(option, 0, sizeof(coap_option) + length + 1);
657
658     COAP_OPTION_KEY(*option) = key;
659
660     coap_option_def_t* def = coap_opt_def(key);
661     if (NULL != def && coap_is_var_bytes(def))
662     {
663        if (length > def->max)
664         {
665             // make sure we shrink the value so it fits the coap option definition
666             // by truncating the value, disregard the leading bytes.
667             OIC_LOG_V(DEBUG, TAG, "Option [%d] data size [%d] shrunk to [%d]",
668                     def->key, length, def->max);
669             data = &(data[length-def->max]);
670             length = def->max;
671         }
672         // Shrink the encoding length to a minimum size for coap
673         // options that support variable length encoding.
674          COAP_OPTION_LENGTH(*option) = coap_encode_var_bytes(
675                 COAP_OPTION_DATA(*option),
676                 coap_decode_var_bytes((unsigned char *)data, length));
677     }
678     else
679     {
680         COAP_OPTION_LENGTH(*option) = length;
681         memcpy(COAP_OPTION_DATA(*option), data, length);
682     }
683
684     /* we can pass NULL here as delete function since option is released automatically  */
685     coap_list_t *node = coap_new_listnode(option, NULL);
686
687     if (!node)
688     {
689         OIC_LOG(ERROR, TAG, "node is NULL");
690         coap_free(option);
691         return NULL;
692     }
693
694     OIC_LOG(DEBUG, TAG, "OUT");
695     return node;
696 }
697
698 int CAOrderOpts(void *a, void *b)
699 {
700     OIC_LOG(DEBUG, TAG, "IN");
701     if (!a || !b)
702     {
703         return a < b ? -1 : 1;
704     }
705
706     if (COAP_OPTION_KEY(*(coap_option *) a) < COAP_OPTION_KEY(*(coap_option * ) b))
707     {
708         return -1;
709     }
710
711     OIC_LOG(DEBUG, TAG, "OUT");
712     return COAP_OPTION_KEY(*(coap_option *) a) == COAP_OPTION_KEY(*(coap_option * ) b);
713 }
714
715 uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter)
716 {
717     OIC_LOG(DEBUG, TAG, "IN");
718     uint32_t count = 0;
719     coap_opt_t *option;
720
721     while ((option = coap_option_next(&opt_iter)))
722     {
723         if (COAP_OPTION_URI_PATH != opt_iter.type && COAP_OPTION_URI_QUERY != opt_iter.type
724             && COAP_OPTION_BLOCK1 != opt_iter.type && COAP_OPTION_BLOCK2 != opt_iter.type
725             && COAP_OPTION_SIZE1 != opt_iter.type && COAP_OPTION_SIZE2 != opt_iter.type
726             && COAP_OPTION_CONTENT_FORMAT != opt_iter.type
727             && COAP_OPTION_ACCEPT != opt_iter.type)
728         {
729             count++;
730         }
731     }
732
733     OIC_LOG(DEBUG, TAG, "OUT");
734     return count;
735 }
736
737 CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
738                             uint32_t *outCode, CAInfo_t *outInfo)
739 {
740     OIC_LOG(DEBUG, TAG, "IN");
741
742     if (!pdu || !outCode || !outInfo)
743     {
744         OIC_LOG(ERROR, TAG, "NULL pointer param");
745         return CA_STATUS_INVALID_PARAM;
746     }
747
748     coap_transport_type transport;
749 #ifdef TCP_ADAPTER
750     if (CA_ADAPTER_TCP == endpoint->adapter)
751     {
752         transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)pdu->hdr)[0] >> 4);
753     }
754     else
755 #endif
756     {
757         transport = coap_udp;
758     }
759
760     coap_opt_iterator_t opt_iter;
761     coap_option_iterator_init((coap_pdu_t *) pdu, &opt_iter, COAP_OPT_ALL, transport);
762
763     if (outCode)
764     {
765         (*outCode) = (uint32_t) CA_RESPONSE_CODE(coap_get_code(pdu, transport));
766     }
767
768     // init HeaderOption list
769     uint32_t count = CAGetOptionCount(opt_iter);
770     memset(outInfo, 0, sizeof(*outInfo));
771
772     outInfo->numOptions = count;
773
774 #ifdef TCP_ADAPTER
775     if (CA_ADAPTER_TCP == endpoint->adapter)
776     {
777         // set type
778         outInfo->type = CA_MSG_NONCONFIRM;
779         outInfo->payloadFormat = CA_FORMAT_UNDEFINED;
780     }
781     else
782 #endif
783     {
784         // set type
785         outInfo->type = pdu->hdr->coap_hdr_udp_t.type;
786
787         // set message id
788         outInfo->messageId = pdu->hdr->coap_hdr_udp_t.id;
789         outInfo->payloadFormat = CA_FORMAT_UNDEFINED;
790         outInfo->acceptFormat = CA_FORMAT_UNDEFINED;
791     }
792
793     if (count > 0)
794     {
795         outInfo->options = (CAHeaderOption_t *) OICCalloc(count, sizeof(CAHeaderOption_t));
796         if (NULL == outInfo->options)
797         {
798             OIC_LOG(ERROR, TAG, "Out of memory");
799             return CA_MEMORY_ALLOC_FAILED;
800         }
801     }
802
803     coap_opt_t *option;
804     char optionResult[CA_MAX_URI_LENGTH] = {0};
805     uint32_t idx = 0;
806     uint32_t optionLength = 0;
807     bool isfirstsetflag = false;
808     bool isQueryBeingProcessed = false;
809
810     while ((option = coap_option_next(&opt_iter)))
811     {
812         char buf[COAP_MAX_PDU_SIZE] = {0};
813         uint32_t bufLength =
814             CAGetOptionData(opt_iter.type, (uint8_t *)(COAP_OPT_VALUE(option)),
815                     COAP_OPT_LENGTH(option), (uint8_t *)buf, sizeof(buf));
816         if (bufLength)
817         {
818             OIC_LOG_V(DEBUG, TAG, "COAP URI element : %s", buf);
819             if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type)
820             {
821                 if (false == isfirstsetflag)
822                 {
823                     isfirstsetflag = true;
824                     optionResult[optionLength] = '/';
825                     optionLength++;
826                     // Make sure there is enough room in the optionResult buffer
827                     if ((optionLength + bufLength) < sizeof(optionResult))
828                     {
829                         memcpy(&optionResult[optionLength], buf, bufLength);
830                         optionLength += bufLength;
831                     }
832                     else
833                     {
834                         goto exit;
835                     }
836                 }
837                 else
838                 {
839                     if (COAP_OPTION_URI_PATH == opt_iter.type)
840                     {
841                         // Make sure there is enough room in the optionResult buffer
842                         if (optionLength < sizeof(optionResult))
843                         {
844                             optionResult[optionLength] = '/';
845                             optionLength++;
846                         }
847                         else
848                         {
849                             goto exit;
850                         }
851                     }
852                     else if (COAP_OPTION_URI_QUERY == opt_iter.type)
853                     {
854                         if (false == isQueryBeingProcessed)
855                         {
856                             // Make sure there is enough room in the optionResult buffer
857                             if (optionLength < sizeof(optionResult))
858                             {
859                                 optionResult[optionLength] = '?';
860                                 optionLength++;
861                                 isQueryBeingProcessed = true;
862                             }
863                             else
864                             {
865                                 goto exit;
866                             }
867                         }
868                         else
869                         {
870                             // Make sure there is enough room in the optionResult buffer
871                             if (optionLength < sizeof(optionResult))
872                             {
873                                 optionResult[optionLength] = ';';
874                                 optionLength++;
875                             }
876                             else
877                             {
878                                 goto exit;
879                             }
880                         }
881                     }
882                     // Make sure there is enough room in the optionResult buffer
883                     if ((optionLength + bufLength) < sizeof(optionResult))
884                     {
885                         memcpy(&optionResult[optionLength], buf, bufLength);
886                         optionLength += bufLength;
887                     }
888                     else
889                     {
890                         goto exit;
891                     }
892                 }
893             }
894             else if (COAP_OPTION_BLOCK1 == opt_iter.type || COAP_OPTION_BLOCK2 == opt_iter.type
895                     || COAP_OPTION_SIZE1 == opt_iter.type || COAP_OPTION_SIZE2 == opt_iter.type)
896             {
897                 OIC_LOG_V(DEBUG, TAG, "option[%d] will be filtering", opt_iter.type);
898             }
899             else if (COAP_OPTION_CONTENT_FORMAT == opt_iter.type)
900             {
901                 if (1 == COAP_OPT_LENGTH(option))
902                 {
903                     outInfo->payloadFormat = CAConvertFormat((uint8_t)buf[0]);
904                 }
905                 else
906                 {
907                     outInfo->payloadFormat = CA_FORMAT_UNSUPPORTED;
908                     OIC_LOG_V(DEBUG, TAG, "option[%d] has an unsupported format [%d]",
909                             opt_iter.type, (uint8_t)buf[0]);
910                 }
911             }
912             else if (COAP_OPTION_ACCEPT == opt_iter.type)
913             {
914                 if (1 == COAP_OPT_LENGTH(option))
915                 {
916                     outInfo->acceptFormat = CAConvertFormat((uint8_t)buf[0]);
917                 }
918                 else
919                 {
920                     outInfo->acceptFormat = CA_FORMAT_UNSUPPORTED;
921                 }
922                 OIC_LOG_V(DEBUG, TAG, "option[%d] has an unsupported format [%d]",
923                         opt_iter.type, (uint8_t)buf[0]);
924             }
925             else
926             {
927                 if (idx < count)
928                 {
929                     if (bufLength <= sizeof(outInfo->options[0].optionData))
930                     {
931                         outInfo->options[idx].optionID = opt_iter.type;
932                         outInfo->options[idx].optionLength = bufLength;
933                         outInfo->options[idx].protocolID = CA_COAP_ID;
934                         memcpy(outInfo->options[idx].optionData, buf, bufLength);
935                         idx++;
936                     }
937                 }
938             }
939         }
940     }
941
942     unsigned char* token = NULL;
943     unsigned int token_length = 0;
944     coap_get_token(pdu->hdr, transport, &token, &token_length);
945
946     // set token data
947     if (token_length > 0)
948     {
949         OIC_LOG_V(DEBUG, TAG, "inside token length : %d", token_length);
950         outInfo->token = (char *) OICMalloc(token_length);
951         if (NULL == outInfo->token)
952         {
953             OIC_LOG(ERROR, TAG, "Out of memory");
954             OICFree(outInfo->options);
955             return CA_MEMORY_ALLOC_FAILED;
956         }
957         memcpy(outInfo->token, token, token_length);
958     }
959
960     outInfo->tokenLength = token_length;
961
962     // set payload data
963     size_t dataSize;
964     uint8_t *data;
965     if (coap_get_data(pdu, &dataSize, &data))
966     {
967         OIC_LOG(DEBUG, TAG, "inside pdu->data");
968         outInfo->payload = (uint8_t *) OICMalloc(dataSize);
969         if (NULL == outInfo->payload)
970         {
971             OIC_LOG(ERROR, TAG, "Out of memory");
972             OICFree(outInfo->options);
973             OICFree(outInfo->token);
974             return CA_MEMORY_ALLOC_FAILED;
975         }
976         memcpy(outInfo->payload, pdu->data, dataSize);
977         outInfo->payloadSize = dataSize;
978     }
979
980     if (optionResult[0] != '\0')
981     {
982         OIC_LOG_V(DEBUG, TAG, "URL length:%d", strlen(optionResult));
983         outInfo->resourceUri = OICStrdup(optionResult);
984         if (!outInfo->resourceUri)
985         {
986             OIC_LOG(ERROR, TAG, "Out of memory");
987             OICFree(outInfo->options);
988             OICFree(outInfo->token);
989             return CA_MEMORY_ALLOC_FAILED;
990         }
991     }
992
993     OIC_LOG(DEBUG, TAG, "OUT");
994     return CA_STATUS_OK;
995
996 exit:
997     OIC_LOG(ERROR, TAG, "buffer too small");
998     OICFree(outInfo->options);
999     return CA_STATUS_FAILED;
1000 }
1001
1002 CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo,
1003                              const CAEndpoint_t *endpoint)
1004 {
1005     OIC_LOG(DEBUG, TAG, "IN");
1006     if (NULL == pdu_hdr)
1007     {
1008         OIC_LOG(ERROR, TAG, "pdu_hdr is null");
1009         return CA_STATUS_INVALID_PARAM;
1010     }
1011
1012     if (NULL == outInfo)
1013     {
1014         OIC_LOG(ERROR, TAG, "outInfo is null");
1015         return CA_STATUS_INVALID_PARAM;
1016     }
1017
1018     coap_transport_type transport;
1019 #ifdef TCP_ADAPTER
1020     if (CA_ADAPTER_TCP == endpoint->adapter)
1021     {
1022         transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)pdu_hdr)[0] >> 4);
1023     }
1024     else
1025 #endif
1026     {
1027         transport = coap_udp;
1028     }
1029
1030     unsigned char* token = NULL;
1031     unsigned int token_length = 0;
1032     coap_get_token(pdu_hdr, transport, &token, &token_length);
1033
1034     // set token data
1035     if (token_length > 0)
1036     {
1037         OIC_LOG_V(DEBUG, TAG, "token len:%d", token_length);
1038         outInfo->token = (char *) OICMalloc(token_length);
1039         if (NULL == outInfo->token)
1040         {
1041             OIC_LOG(ERROR, TAG, "Out of memory");
1042             return CA_MEMORY_ALLOC_FAILED;
1043         }
1044         memcpy(outInfo->token, token, token_length);
1045     }
1046
1047     outInfo->tokenLength = token_length;
1048
1049     OIC_LOG(DEBUG, TAG, "OUT");
1050
1051     return CA_STATUS_OK;
1052 }
1053
1054 CAResult_t CAGenerateTokenInternal(CAToken_t *token, uint8_t tokenLength)
1055 {
1056     OIC_LOG(DEBUG, TAG, "IN");
1057
1058     if (!token)
1059     {
1060         OIC_LOG(ERROR, TAG, "invalid token pointer");
1061         return CA_STATUS_INVALID_PARAM;
1062     }
1063
1064     if ((tokenLength > CA_MAX_TOKEN_LEN) || (0 == tokenLength))
1065     {
1066         OIC_LOG(ERROR, TAG, "invalid token length");
1067         return CA_STATUS_INVALID_PARAM;
1068     }
1069
1070     if (SEED == 0)
1071     {
1072 #ifdef ARDUINO
1073         SEED = now();
1074 #else
1075         SEED = time(NULL);
1076 #endif
1077         if (SEED == (unsigned int)((time_t)-1))
1078         {
1079             OIC_LOG(ERROR, TAG, "seed is not made");
1080             SEED = 0;
1081             return CA_STATUS_FAILED;
1082         }
1083 #if HAVE_SRANDOM
1084         srandom(SEED);
1085 #else
1086         srand(SEED);
1087 #endif
1088     }
1089
1090     // memory allocation
1091     char *temp = (char *) OICCalloc(tokenLength, sizeof(char));
1092     if (NULL == temp)
1093     {
1094         OIC_LOG(ERROR, TAG, "Out of memory");
1095         return CA_MEMORY_ALLOC_FAILED;
1096     }
1097
1098     // set random byte
1099     for (uint8_t index = 0; index < tokenLength; index++)
1100     {
1101         // use valid characters
1102 #ifdef ARDUINO
1103         temp[index] = rand() & 0x00FF;
1104 #else
1105         temp[index] = random() & 0x00FF;
1106 #endif
1107     }
1108
1109     // save token
1110     *token = temp;
1111
1112     OIC_LOG_V(DEBUG, TAG, "token len:%d, token:", tokenLength);
1113     OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *)(*token), tokenLength);
1114
1115     OIC_LOG(DEBUG, TAG, "OUT");
1116     return CA_STATUS_OK;
1117 }
1118
1119 void CADestroyTokenInternal(CAToken_t token)
1120 {
1121     OIC_LOG(DEBUG, TAG, "IN");
1122     OICFree(token);
1123     OIC_LOG(DEBUG, TAG, "OUT");
1124 }
1125
1126 void CADestroyInfo(CAInfo_t *info)
1127 {
1128     OIC_LOG(DEBUG, TAG, "IN");
1129
1130     if (NULL != info)
1131     {
1132         OIC_LOG(DEBUG, TAG, "free options");
1133         OICFree(info->options);
1134
1135         OIC_LOG(DEBUG, TAG, "free token");
1136         OICFree(info->token);
1137
1138         OIC_LOG(DEBUG, TAG, "free payload");
1139         OICFree(info->payload);
1140     }
1141
1142     OIC_LOG(DEBUG, TAG, "OUT");
1143 }
1144
1145 uint32_t CAGetOptionData(uint16_t key, const uint8_t *data, uint32_t len,
1146         uint8_t *option, uint32_t buflen)
1147 {
1148     if (0 == buflen)
1149     {
1150         OIC_LOG(ERROR, TAG, "buflen 0");
1151         return 0;
1152     }
1153
1154     if (buflen <= len)
1155     {
1156         OIC_LOG(ERROR, TAG, "option buffer too small");
1157         return 0;
1158     }
1159
1160     coap_option_def_t* def = coap_opt_def(key);
1161     if(NULL != def && coap_is_var_bytes(def) && 0 == len) {
1162         // A 0 length option is permitted in CoAP but the
1163         // rest or the stack is unaware of variable byte encoding
1164         // should remain that way so a 0 byte of length 1 is inserted.
1165         len = 1;
1166         option[0]=0;
1167     } else {
1168         memcpy(option, data, len);
1169         option[len] = '\0';
1170     }
1171
1172     return len;
1173 }
1174
1175 CAMessageType_t CAGetMessageTypeFromPduBinaryData(const void *pdu, uint32_t size)
1176 {
1177     if (NULL == pdu)
1178     {
1179         OIC_LOG(ERROR, TAG, "pdu is null");
1180         return CA_MSG_NONCONFIRM;
1181     }
1182
1183     // pdu minimum size is 4 byte.
1184     if (size < CA_PDU_MIN_SIZE)
1185     {
1186         OIC_LOG(ERROR, TAG, "min size");
1187         return CA_MSG_NONCONFIRM;
1188     }
1189
1190     coap_hdr_t *hdr = (coap_hdr_t *) pdu;
1191
1192     return (CAMessageType_t) hdr->coap_hdr_udp_t.type;
1193 }
1194
1195 uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size)
1196 {
1197     if (NULL == pdu)
1198     {
1199         OIC_LOG(ERROR, TAG, "pdu is null");
1200         return 0;
1201     }
1202
1203     // pdu minimum size is 4 byte.
1204     if (size < CA_PDU_MIN_SIZE)
1205     {
1206         OIC_LOG(ERROR, TAG, "min size");
1207         return 0;
1208     }
1209
1210     coap_hdr_t *hdr = (coap_hdr_t *) pdu;
1211
1212     return hdr->coap_hdr_udp_t.id;
1213 }
1214
1215 CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size)
1216 {
1217     if (NULL == pdu)
1218     {
1219         OIC_LOG(ERROR, TAG, "pdu is null");
1220         return CA_NOT_FOUND;
1221     }
1222
1223     // pdu minimum size is 4 byte.
1224     if (size < CA_PDU_MIN_SIZE)
1225     {
1226         OIC_LOG(ERROR, TAG, "min size");
1227         return CA_NOT_FOUND;
1228     }
1229
1230     coap_hdr_t *hdr = (coap_hdr_t *) pdu;
1231
1232     return (CAResponseResult_t) CA_RESPONSE_CODE(hdr->coap_hdr_udp_t.code);
1233 }
1234
1235 CAPayloadFormat_t CAConvertFormat(uint8_t format)
1236 {
1237     switch (format)
1238     {
1239         case COAP_MEDIATYPE_TEXT_PLAIN:
1240             return CA_FORMAT_TEXT_PLAIN;
1241         case COAP_MEDIATYPE_APPLICATION_LINK_FORMAT:
1242             return CA_FORMAT_APPLICATION_LINK_FORMAT;
1243         case COAP_MEDIATYPE_APPLICATION_XML:
1244             return CA_FORMAT_APPLICATION_XML;
1245         case COAP_MEDIATYPE_APPLICATION_OCTET_STREAM:
1246             return CA_FORMAT_APPLICATION_OCTET_STREAM;
1247         case COAP_MEDIATYPE_APPLICATION_RDF_XML:
1248             return CA_FORMAT_APPLICATION_RDF_XML;
1249         case COAP_MEDIATYPE_APPLICATION_EXI:
1250             return CA_FORMAT_APPLICATION_EXI;
1251         case COAP_MEDIATYPE_APPLICATION_JSON:
1252             return CA_FORMAT_APPLICATION_JSON;
1253         case COAP_MEDIATYPE_APPLICATION_CBOR:
1254             return CA_FORMAT_APPLICATION_CBOR;
1255         default:
1256             return CA_FORMAT_UNSUPPORTED;
1257     }
1258 }