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