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