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