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