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