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