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