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