Development of CoAP-HTTP Proxy
[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 #ifdef WITH_CHPROXY
55 static char g_chproxyUri[CA_MAX_URI_LENGTH];
56
57 CAResult_t CASetProxyUri(const char *uri)
58 {
59     VERIFY_NON_NULL(uri, TAG, "uri");
60     OICStrcpy(g_chproxyUri, sizeof (g_chproxyUri), uri);
61     return CA_STATUS_OK;
62 }
63 #endif
64
65 CAResult_t CAGetRequestInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
66                                    CARequestInfo_t *outReqInfo)
67 {
68     VERIFY_NON_NULL(pdu, TAG, "pdu");
69     VERIFY_NON_NULL(outReqInfo, TAG, "outReqInfo");
70
71     uint32_t code = CA_NOT_FOUND;
72     CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &(outReqInfo->info));
73     outReqInfo->method = code;
74
75     return ret;
76 }
77
78 CAResult_t CAGetResponseInfoFromPDU(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,
79                                     const CAEndpoint_t *endpoint)
80 {
81     VERIFY_NON_NULL(pdu, TAG, "pdu");
82     VERIFY_NON_NULL(outResInfo, TAG, "outResInfo");
83
84     uint32_t code = CA_NOT_FOUND;
85     CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &(outResInfo->info));
86     outResInfo->result = code;
87
88     return ret;
89 }
90
91 CAResult_t CAGetErrorInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
92                                  CAErrorInfo_t *errorInfo)
93 {
94     VERIFY_NON_NULL(pdu, TAG, "pdu");
95
96     uint32_t code = 0;
97     CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &errorInfo->info);
98
99     return ret;
100 }
101
102 coap_pdu_t *CAGeneratePDU(uint32_t code, const CAInfo_t *info, const CAEndpoint_t *endpoint,
103                           coap_list_t **optlist, coap_transport_type *transport)
104 {
105     VERIFY_NON_NULL_RET(info, TAG, "info", NULL);
106     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", NULL);
107     VERIFY_NON_NULL_RET(optlist, TAG, "optlist", NULL);
108
109     coap_pdu_t *pdu = NULL;
110
111     // RESET have to use only 4byte (empty message)
112     // and ACKNOWLEDGE can use empty message when code is empty.
113     if (CA_MSG_RESET == info->type || (CA_EMPTY == code && CA_MSG_ACKNOWLEDGE == info->type))
114     {
115         if (CA_EMPTY != code)
116         {
117             OIC_LOG(ERROR, TAG, "reset is not empty message");
118             return NULL;
119         }
120
121         if (info->payloadSize > 0 || info->payload || info->token || info->tokenLength > 0)
122         {
123             OIC_LOG(ERROR, TAG, "Empty message has unnecessary data after messageID");
124             return NULL;
125         }
126
127         OIC_LOG(DEBUG, TAG, "code is empty");
128         if (!(pdu = CAGeneratePDUImpl((code_t) code, info, endpoint, NULL, transport)))
129         {
130             OIC_LOG(ERROR, TAG, "pdu NULL");
131             return NULL;
132         }
133     }
134     else
135     {
136         if (info->resourceUri)
137         {
138             uint32_t length = strlen(info->resourceUri);
139             if (CA_MAX_URI_LENGTH < length)
140             {
141                 OIC_LOG(ERROR, TAG, "URI len err");
142                 return NULL;
143             }
144
145             uint32_t uriLength = length + sizeof(COAP_URI_HEADER);
146             char *coapUri = (char *) OICCalloc(1, uriLength);
147             if (NULL == coapUri)
148             {
149                 OIC_LOG(ERROR, TAG, "out of memory");
150                 return NULL;
151             }
152             OICStrcat(coapUri, uriLength, COAP_URI_HEADER);
153             OICStrcat(coapUri, uriLength, info->resourceUri);
154
155             // parsing options in URI
156             CAResult_t res = CAParseURI(coapUri, optlist);
157             if (CA_STATUS_OK != res)
158             {
159                 OICFree(coapUri);
160                 return NULL;
161             }
162
163             OICFree(coapUri);
164         }
165         // parsing options in HeadOption
166         CAResult_t ret = CAParseHeadOption(code, info, optlist);
167         if (CA_STATUS_OK != ret)
168         {
169             return NULL;
170         }
171
172         pdu = CAGeneratePDUImpl((code_t) code, info, endpoint, *optlist, transport);
173         if (NULL == pdu)
174         {
175             OIC_LOG(ERROR, TAG, "pdu NULL");
176             return NULL;
177         }
178     }
179
180     // pdu print method : coap_show_pdu(pdu);
181     return pdu;
182 }
183
184 coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode,
185                        const CAEndpoint_t *endpoint)
186 {
187     VERIFY_NON_NULL_RET(data, TAG, "data", NULL);
188     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", NULL);
189
190     coap_transport_type transport;
191 #ifdef WITH_TCP
192     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
193     {
194         transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)data)[0] >> 4);
195     }
196     else
197 #endif
198     {
199         transport = coap_udp;
200     }
201
202     coap_pdu_t *outpdu = coap_new_pdu(transport, length);
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_parse((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->hdr->coap_hdr_udp_t.version != COAP_DEFAULT_VERSION)
228         {
229             OIC_LOG_V(ERROR, TAG, "coap version is not available : %d",
230                       outpdu->hdr->coap_hdr_udp_t.version);
231             goto exit;
232         }
233         if (outpdu->hdr->coap_hdr_udp_t.token_length > CA_MAX_TOKEN_LEN)
234         {
235             OIC_LOG_V(ERROR, TAG, "token length has been exceed : %d",
236                       outpdu->hdr->coap_hdr_udp_t.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_type *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_pdu(*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->hdr->coap_hdr_udp_t.id = message_id;
341         OIC_LOG_V(DEBUG, TAG, "messageId in pdu is %d, %d", message_id, pdu->hdr->coap_hdr_udp_t.id);
342
343         pdu->hdr->coap_hdr_udp_t.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_token(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             coap_add_option(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     }
386
387     OIC_LOG_V(DEBUG, TAG, "[%d] pdu length after option", pdu->length);
388
389     if (NULL != info->payload && 0 < info->payloadSize)
390     {
391         OIC_LOG(DEBUG, TAG, "payload is added");
392         coap_add_data(pdu, info->payloadSize, (const unsigned char *) info->payload);
393     }
394
395     return pdu;
396 }
397
398 CAResult_t CAParseURI(const char *uriInfo, coap_list_t **optlist)
399 {
400     VERIFY_NON_NULL(uriInfo, TAG, "uriInfo");
401     VERIFY_NON_NULL(optlist, TAG, "optlist");
402
403     OIC_LOG_V(DEBUG, TAG, "url : %s", uriInfo);
404
405     /* split arg into Uri-* options */
406     coap_uri_t uri;
407     coap_split_uri((unsigned char *) uriInfo, strlen(uriInfo), &uri);
408
409     if (uri.port != COAP_DEFAULT_PORT)
410     {
411         unsigned char portbuf[CA_ENCODE_BUFFER_SIZE] = { 0 };
412         int ret = coap_insert(optlist,
413                               CACreateNewOptionNode(COAP_OPTION_URI_PORT,
414                                                     coap_encode_var_bytes(portbuf, uri.port),
415                                                     (char *)portbuf),
416                               CAOrderOpts);
417         if (ret <= 0)
418         {
419             return CA_STATUS_INVALID_PARAM;
420         }
421     }
422
423     if (uri.path.s && uri.path.length)
424     {
425         CAResult_t ret = CAParseUriPartial(uri.path.s, uri.path.length,
426                                            COAP_OPTION_URI_PATH, optlist);
427         if (CA_STATUS_OK != ret)
428         {
429             OIC_LOG(ERROR, TAG, "CAParseUriPartial failed(uri path)");
430             return ret;
431         }
432     }
433
434     if (uri.query.s && uri.query.length)
435     {
436         CAResult_t ret = CAParseUriPartial(uri.query.s, uri.query.length, COAP_OPTION_URI_QUERY,
437                                            optlist);
438         if (CA_STATUS_OK != ret)
439         {
440             OIC_LOG(ERROR, TAG, "CAParseUriPartial failed(uri query)");
441             return ret;
442         }
443     }
444
445     return CA_STATUS_OK;
446 }
447
448 CAResult_t CAParseUriPartial(const unsigned char *str, size_t length, int target,
449                              coap_list_t **optlist)
450 {
451     VERIFY_NON_NULL(optlist, TAG, "optlist");
452
453     if ((target != COAP_OPTION_URI_PATH) && (target != COAP_OPTION_URI_QUERY))
454     {
455         // should never occur. Log just in case.
456         OIC_LOG(DEBUG, TAG, "Unexpected URI component.");
457         return CA_NOT_SUPPORTED;
458     }
459     else if (str && length)
460     {
461         unsigned char uriBuffer[CA_MAX_URI_LENGTH] = { 0 };
462         unsigned char *pBuf = uriBuffer;
463         size_t buflen = sizeof(uriBuffer);
464         int res = (target == COAP_OPTION_URI_PATH) ? coap_split_path(str, length, pBuf, &buflen) :
465                                                      coap_split_query(str, length, pBuf, &buflen);
466
467         if (res > 0)
468         {
469             size_t prevIdx = 0;
470             while (res--)
471             {
472                 int ret = coap_insert(optlist,
473                                       CACreateNewOptionNode(target, COAP_OPT_LENGTH(pBuf),
474                                                             (char *)COAP_OPT_VALUE(pBuf)),
475                                       CAOrderOpts);
476                 if (ret <= 0)
477                 {
478                     return CA_STATUS_INVALID_PARAM;
479                 }
480
481                 size_t optSize = COAP_OPT_SIZE(pBuf);
482                 if ((prevIdx + optSize) < buflen)
483                 {
484                     pBuf += optSize;
485                     prevIdx += optSize;
486                 }
487             }
488         }
489         else
490         {
491             OIC_LOG_V(ERROR, TAG, "Problem parsing URI : %d for %d", res, target);
492             return CA_STATUS_FAILED;
493         }
494     }
495     else
496     {
497         OIC_LOG(ERROR, TAG, "str or length is not available");
498         return CA_STATUS_FAILED;
499     }
500
501     return CA_STATUS_OK;
502 }
503
504 CAResult_t CAParseHeadOption(uint32_t code, const CAInfo_t *info, coap_list_t **optlist)
505 {
506     (void)code;
507     VERIFY_NON_NULL_RET(info, TAG, "info", CA_STATUS_INVALID_PARAM);
508
509     OIC_LOG_V(DEBUG, TAG, "parse Head Opt: %d", info->numOptions);
510
511     if (!optlist)
512     {
513         OIC_LOG(ERROR, TAG, "optlist is null");
514         return CA_STATUS_INVALID_PARAM;
515     }
516
517     for (uint32_t i = 0; i < info->numOptions; i++)
518     {
519         if(!(info->options + i))
520         {
521             OIC_LOG(ERROR, TAG, "options is not available");
522             return CA_STATUS_FAILED;
523         }
524
525         uint32_t id = (info->options + i)->optionID;
526         if (COAP_OPTION_URI_PATH == id || COAP_OPTION_URI_QUERY == id)
527         {
528             OIC_LOG_V(DEBUG, TAG, "not Header Opt: %d", id);
529         }
530         else
531         {
532             OIC_LOG_V(DEBUG, TAG, "Head opt ID: %d", id);
533             OIC_LOG_V(DEBUG, TAG, "Head opt data: %s", (info->options + i)->optionData);
534             OIC_LOG_V(DEBUG, TAG, "Head opt length: %d", (info->options + i)->optionLength);
535             int ret = coap_insert(optlist,
536                                   CACreateNewOptionNode(id, (info->options + i)->optionLength,
537                                                         (info->options + i)->optionData),
538                                   CAOrderOpts);
539             if (ret <= 0)
540             {
541                 return CA_STATUS_INVALID_PARAM;
542             }
543         }
544     }
545
546     // insert one extra header with the payload format if applicable.
547     if (CA_FORMAT_UNDEFINED != info->payloadFormat)
548     {
549         coap_list_t* node = NULL;
550         uint8_t buf[CA_ENCODE_BUFFER_SIZE] = {0};
551         switch (info->payloadFormat)
552         {
553             case CA_FORMAT_APPLICATION_CBOR:
554                 node = CACreateNewOptionNode(
555                         COAP_OPTION_CONTENT_FORMAT,
556                         coap_encode_var_bytes(buf, (unsigned short)COAP_MEDIATYPE_APPLICATION_CBOR),
557                         (char *)buf);
558                 break;
559             default:
560                 OIC_LOG_V(ERROR, TAG, "format option:[%d] not supported", info->payloadFormat);
561         }
562         if (!node)
563         {
564             OIC_LOG(ERROR, TAG, "format option not created");
565             return CA_STATUS_INVALID_PARAM;
566         }
567         int ret = coap_insert(optlist, node, CAOrderOpts);
568         if (ret <= 0)
569         {
570             coap_delete(node);
571             OIC_LOG(ERROR, TAG, "format option not inserted in header");
572             return CA_STATUS_INVALID_PARAM;
573         }
574     }
575     if (CA_FORMAT_UNDEFINED != info->acceptFormat)
576     {
577         coap_list_t* node = NULL;
578         uint8_t buf[CA_ENCODE_BUFFER_SIZE] = {0};
579         switch (info->acceptFormat)
580         {
581             case CA_FORMAT_APPLICATION_CBOR:
582                 node = CACreateNewOptionNode(
583                         COAP_OPTION_ACCEPT,
584                         coap_encode_var_bytes(buf, (unsigned short)COAP_MEDIATYPE_APPLICATION_CBOR),
585                         (char *)buf);
586                 break;
587             default:
588                 OIC_LOG_V(ERROR, TAG, "format option:[%d] not supported", info->acceptFormat);
589         }
590         if (!node)
591         {
592             OIC_LOG(ERROR, TAG, "format option not created");
593             return CA_STATUS_INVALID_PARAM;
594         }
595         int ret = coap_insert(optlist, node, CAOrderOpts);
596         if (ret <= 0)
597         {
598             coap_delete(node);
599             OIC_LOG(ERROR, TAG, "format option not inserted in header");
600             return CA_STATUS_INVALID_PARAM;
601         }
602     }
603
604     return CA_STATUS_OK;
605 }
606
607 coap_list_t *CACreateNewOptionNode(uint16_t key, uint32_t length, const char *data)
608 {
609     VERIFY_NON_NULL_RET(data, TAG, "data", NULL);
610
611     coap_option *option = coap_malloc(sizeof(coap_option) + length + 1);
612     if (!option)
613     {
614         OIC_LOG(ERROR, TAG, "Out of memory");
615         return NULL;
616     }
617     memset(option, 0, sizeof(coap_option) + length + 1);
618
619     COAP_OPTION_KEY(*option) = key;
620
621     coap_option_def_t* def = coap_opt_def(key);
622     if (NULL != def && coap_is_var_bytes(def))
623     {
624        if (length > def->max)
625         {
626             // make sure we shrink the value so it fits the coap option definition
627             // by truncating the value, disregard the leading bytes.
628             OIC_LOG_V(DEBUG, TAG, "Option [%d] data size [%d] shrunk to [%d]",
629                     def->key, length, def->max);
630             data = &(data[length-def->max]);
631             length = def->max;
632         }
633         // Shrink the encoding length to a minimum size for coap
634         // options that support variable length encoding.
635          COAP_OPTION_LENGTH(*option) = coap_encode_var_bytes(
636                 COAP_OPTION_DATA(*option),
637                 coap_decode_var_bytes((unsigned char *)data, length));
638     }
639     else
640     {
641         COAP_OPTION_LENGTH(*option) = length;
642         memcpy(COAP_OPTION_DATA(*option), data, length);
643     }
644
645     /* we can pass NULL here as delete function since option is released automatically  */
646     coap_list_t *node = coap_new_listnode(option, NULL);
647
648     if (!node)
649     {
650         OIC_LOG(ERROR, TAG, "node is NULL");
651         coap_free(option);
652         return NULL;
653     }
654
655     return node;
656 }
657
658 int CAOrderOpts(void *a, void *b)
659 {
660     if (!a || !b)
661     {
662         return a < b ? -1 : 1;
663     }
664
665     if (COAP_OPTION_KEY(*(coap_option *) a) < COAP_OPTION_KEY(*(coap_option * ) b))
666     {
667         return -1;
668     }
669
670     return COAP_OPTION_KEY(*(coap_option *) a) == COAP_OPTION_KEY(*(coap_option * ) b);
671 }
672
673 uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter)
674 {
675     uint32_t count = 0;
676     coap_opt_t *option = NULL;
677
678     while ((option = coap_option_next(&opt_iter)))
679     {
680         if (COAP_OPTION_URI_PATH != opt_iter.type && COAP_OPTION_URI_QUERY != opt_iter.type
681             && COAP_OPTION_BLOCK1 != opt_iter.type && COAP_OPTION_BLOCK2 != opt_iter.type
682             && COAP_OPTION_SIZE1 != opt_iter.type && COAP_OPTION_SIZE2 != opt_iter.type
683             && COAP_OPTION_CONTENT_FORMAT != opt_iter.type
684             && COAP_OPTION_ACCEPT != opt_iter.type
685             && COAP_OPTION_URI_HOST != opt_iter.type && COAP_OPTION_URI_PORT != opt_iter.type
686             && COAP_OPTION_ETAG != opt_iter.type && COAP_OPTION_MAXAGE != opt_iter.type
687             && COAP_OPTION_PROXY_SCHEME != opt_iter.type)
688         {
689             count++;
690         }
691     }
692
693     return count;
694 }
695
696 CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
697                             uint32_t *outCode, CAInfo_t *outInfo)
698 {
699     VERIFY_NON_NULL(pdu, TAG, "pdu");
700     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
701     VERIFY_NON_NULL(outCode, TAG, "outCode");
702     VERIFY_NON_NULL(outInfo, TAG, "outInfo");
703
704     coap_transport_type transport;
705 #ifdef WITH_TCP
706     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
707     {
708         transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)pdu->hdr)[0] >> 4);
709     }
710     else
711 #endif
712     {
713         transport = coap_udp;
714     }
715
716     coap_opt_iterator_t opt_iter;
717     coap_option_iterator_init((coap_pdu_t *) pdu, &opt_iter, COAP_OPT_ALL, transport);
718
719     if (outCode)
720     {
721         (*outCode) = (uint32_t) CA_RESPONSE_CODE(coap_get_code(pdu, transport));
722     }
723
724     // init HeaderOption list
725     uint32_t count = CAGetOptionCount(opt_iter);
726     memset(outInfo, 0, sizeof(*outInfo));
727
728     outInfo->numOptions = count;
729
730 #ifdef WITH_TCP
731     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
732     {
733         // set type
734         outInfo->type = CA_MSG_NONCONFIRM;
735         outInfo->payloadFormat = CA_FORMAT_UNDEFINED;
736     }
737     else
738 #else
739     (void) endpoint;
740 #endif
741     {
742         // set type
743         outInfo->type = pdu->hdr->coap_hdr_udp_t.type;
744
745         // set message id
746         outInfo->messageId = pdu->hdr->coap_hdr_udp_t.id;
747         outInfo->payloadFormat = CA_FORMAT_UNDEFINED;
748         outInfo->acceptFormat = CA_FORMAT_UNDEFINED;
749     }
750
751     if (count > 0)
752     {
753         outInfo->options = (CAHeaderOption_t *) OICCalloc(count, sizeof(CAHeaderOption_t));
754         if (NULL == outInfo->options)
755         {
756             OIC_LOG(ERROR, TAG, "Out of memory");
757             return CA_MEMORY_ALLOC_FAILED;
758         }
759     }
760
761     coap_opt_t *option = NULL;
762     char optionResult[CA_MAX_URI_LENGTH] = {0};
763     uint32_t idx = 0;
764     uint32_t optionLength = 0;
765     bool isfirstsetflag = false;
766     bool isQueryBeingProcessed = false;
767 #ifdef WITH_CHPROXY
768     bool isProxyRequest = false;
769 #endif
770
771     while ((option = coap_option_next(&opt_iter)))
772     {
773         char buf[COAP_MAX_PDU_SIZE] = {0};
774         uint32_t bufLength =
775             CAGetOptionData(opt_iter.type, (uint8_t *)(COAP_OPT_VALUE(option)),
776                     COAP_OPT_LENGTH(option), (uint8_t *)buf, sizeof(buf));
777         if (bufLength)
778         {
779             OIC_LOG_V(DEBUG, TAG, "COAP URI element : %s", buf);
780             if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type)
781             {
782                 if (false == isfirstsetflag)
783                 {
784                     isfirstsetflag = true;
785                     optionResult[optionLength] = '/';
786                     optionLength++;
787                     // Make sure there is enough room in the optionResult buffer
788                     if ((optionLength + bufLength) < sizeof(optionResult))
789                     {
790                         memcpy(&optionResult[optionLength], buf, bufLength);
791                         optionLength += bufLength;
792                     }
793                     else
794                     {
795                         goto exit;
796                     }
797                 }
798                 else
799                 {
800                     if (COAP_OPTION_URI_PATH == opt_iter.type)
801                     {
802                         // Make sure there is enough room in the optionResult buffer
803                         if (optionLength < sizeof(optionResult))
804                         {
805                             optionResult[optionLength] = '/';
806                             optionLength++;
807                         }
808                         else
809                         {
810                             goto exit;
811                         }
812                     }
813                     else if (COAP_OPTION_URI_QUERY == opt_iter.type)
814                     {
815                         if (false == isQueryBeingProcessed)
816                         {
817                             // Make sure there is enough room in the optionResult buffer
818                             if (optionLength < sizeof(optionResult))
819                             {
820                                 optionResult[optionLength] = '?';
821                                 optionLength++;
822                                 isQueryBeingProcessed = true;
823                             }
824                             else
825                             {
826                                 goto exit;
827                             }
828                         }
829                         else
830                         {
831                             // Make sure there is enough room in the optionResult buffer
832                             if (optionLength < sizeof(optionResult))
833                             {
834                                 optionResult[optionLength] = ';';
835                                 optionLength++;
836                             }
837                             else
838                             {
839                                 goto exit;
840                             }
841                         }
842                     }
843                     // Make sure there is enough room in the optionResult buffer
844                     if ((optionLength + bufLength) < sizeof(optionResult))
845                     {
846                         memcpy(&optionResult[optionLength], buf, bufLength);
847                         optionLength += bufLength;
848                     }
849                     else
850                     {
851                         goto exit;
852                     }
853                 }
854             }
855             else if (COAP_OPTION_BLOCK1 == opt_iter.type || COAP_OPTION_BLOCK2 == opt_iter.type
856                     || COAP_OPTION_SIZE1 == opt_iter.type || COAP_OPTION_SIZE2 == opt_iter.type)
857             {
858                 OIC_LOG_V(DEBUG, TAG, "option[%d] will be filtering", opt_iter.type);
859             }
860             else if (COAP_OPTION_CONTENT_FORMAT == opt_iter.type)
861             {
862                 if (1 == COAP_OPT_LENGTH(option))
863                 {
864                     outInfo->payloadFormat = CAConvertFormat((uint8_t)buf[0]);
865                 }
866                 else
867                 {
868                     outInfo->payloadFormat = CA_FORMAT_UNSUPPORTED;
869                     OIC_LOG_V(DEBUG, TAG, "option[%d] has an unsupported format [%d]",
870                               opt_iter.type, (uint8_t)buf[0]);
871                 }
872             }
873             else if (COAP_OPTION_ACCEPT == opt_iter.type)
874             {
875                 if (1 == COAP_OPT_LENGTH(option))
876                 {
877                     outInfo->acceptFormat = CAConvertFormat((uint8_t)buf[0]);
878                 }
879                 else
880                 {
881                     outInfo->acceptFormat = CA_FORMAT_UNSUPPORTED;
882                 }
883                 OIC_LOG_V(DEBUG, TAG, "option[%d] has an unsupported format [%d]",
884                           opt_iter.type, (uint8_t)buf[0]);
885             }
886             else if (COAP_OPTION_URI_PORT == opt_iter.type ||
887                     COAP_OPTION_URI_HOST == opt_iter.type ||
888                     COAP_OPTION_ETAG == opt_iter.type ||
889                     COAP_OPTION_MAXAGE == opt_iter.type ||
890                     COAP_OPTION_PROXY_SCHEME== opt_iter.type)
891             {
892                 OIC_LOG_V(INFO, TAG, "option[%d] has an unsupported format [%d]",
893                           opt_iter.type, (uint8_t)buf[0]);
894             }
895             else
896             {
897 #ifdef WITH_CHPROXY
898                 if (COAP_OPTION_PROXY_URI == opt_iter.type)
899                 {
900                     isProxyRequest = true;
901                 }
902 #endif
903                 if (idx < count)
904                 {
905                     if (bufLength <= sizeof(outInfo->options[0].optionData))
906                     {
907                         outInfo->options[idx].optionID = opt_iter.type;
908                         outInfo->options[idx].optionLength = bufLength;
909                         outInfo->options[idx].protocolID = CA_COAP_ID;
910                         memcpy(outInfo->options[idx].optionData, buf, bufLength);
911                         idx++;
912                     }
913                 }
914             }
915         }
916     }
917
918     unsigned char* token = NULL;
919     unsigned int token_length = 0;
920     coap_get_token(pdu->hdr, transport, &token, &token_length);
921
922     // set token data
923     if (token_length > 0)
924     {
925         OIC_LOG_V(DEBUG, TAG, "inside token length : %d", token_length);
926         outInfo->token = (char *) OICMalloc(token_length);
927         if (NULL == outInfo->token)
928         {
929             OIC_LOG(ERROR, TAG, "Out of memory");
930             OICFree(outInfo->options);
931             return CA_MEMORY_ALLOC_FAILED;
932         }
933         memcpy(outInfo->token, token, token_length);
934     }
935
936     outInfo->tokenLength = token_length;
937
938     // set payload data
939     size_t dataSize;
940     uint8_t *data;
941     if (coap_get_data(pdu, &dataSize, &data))
942     {
943         OIC_LOG(DEBUG, TAG, "inside pdu->data");
944         outInfo->payload = (uint8_t *) OICMalloc(dataSize);
945         if (NULL == outInfo->payload)
946         {
947             OIC_LOG(ERROR, TAG, "Out of memory");
948             OICFree(outInfo->options);
949             OICFree(outInfo->token);
950             return CA_MEMORY_ALLOC_FAILED;
951         }
952         memcpy(outInfo->payload, pdu->data, dataSize);
953         outInfo->payloadSize = dataSize;
954     }
955
956     if (optionResult[0] != '\0')
957     {
958         OIC_LOG_V(DEBUG, TAG, "URL length:%zu", strlen(optionResult));
959         outInfo->resourceUri = OICStrdup(optionResult);
960         if (!outInfo->resourceUri)
961         {
962             OIC_LOG(ERROR, TAG, "Out of memory");
963             OICFree(outInfo->options);
964             OICFree(outInfo->token);
965             return CA_MEMORY_ALLOC_FAILED;
966         }
967     }
968 #ifdef WITH_CHPROXY
969     else if(isProxyRequest && g_chproxyUri[0] != '\0')
970     {
971        /*
972         *   A request for CoAP-HTTP Proxy will not have any uri element as per CoAP specs
973         *   and only COAP_OPTION_PROXY_URI will be present. Use preset proxy uri
974         *   for such requests.
975         */
976         outInfo->resourceUri = OICStrdup(g_chproxyUri);
977         if (!outInfo->resourceUri)
978         {
979             OIC_LOG(ERROR, TAG, "Out of memory");
980             OICFree(outInfo->options);
981             OICFree(outInfo->token);
982             return CA_MEMORY_ALLOC_FAILED;
983         }
984     }
985 #endif
986     return CA_STATUS_OK;
987
988 exit:
989     OIC_LOG(ERROR, TAG, "buffer too small");
990     OICFree(outInfo->options);
991     return CA_STATUS_FAILED;
992 }
993
994 CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo,
995                              const CAEndpoint_t *endpoint)
996 {
997     VERIFY_NON_NULL(pdu_hdr, TAG, "pdu_hdr");
998     VERIFY_NON_NULL(outInfo, TAG, "outInfo");
999     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
1000
1001     coap_transport_type transport = coap_udp;
1002 #ifdef WITH_TCP
1003     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
1004     {
1005         transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)pdu_hdr)[0] >> 4);
1006     }
1007 #endif
1008
1009     unsigned char* token = NULL;
1010     unsigned int token_length = 0;
1011     coap_get_token(pdu_hdr, transport, &token, &token_length);
1012
1013     // set token data
1014     if (token_length > 0)
1015     {
1016         OIC_LOG_V(DEBUG, TAG, "token len:%d", token_length);
1017         outInfo->token = (char *) OICMalloc(token_length);
1018         if (NULL == outInfo->token)
1019         {
1020             OIC_LOG(ERROR, TAG, "Out of memory");
1021             return CA_MEMORY_ALLOC_FAILED;
1022         }
1023         memcpy(outInfo->token, token, token_length);
1024     }
1025
1026     outInfo->tokenLength = token_length;
1027
1028     return CA_STATUS_OK;
1029 }
1030
1031 CAResult_t CAGenerateTokenInternal(CAToken_t *token, uint8_t tokenLength)
1032 {
1033     VERIFY_NON_NULL(token, TAG, "token");
1034
1035     if ((tokenLength > CA_MAX_TOKEN_LEN) || (0 == tokenLength))
1036     {
1037         OIC_LOG(ERROR, TAG, "invalid token length");
1038         return CA_STATUS_INVALID_PARAM;
1039     }
1040
1041     // memory allocation
1042     char *temp = (char *) OICCalloc(tokenLength, sizeof(char));
1043     if (NULL == temp)
1044     {
1045         OIC_LOG(ERROR, TAG, "Out of memory");
1046         return CA_MEMORY_ALLOC_FAILED;
1047     }
1048
1049     OCFillRandomMem((uint8_t *)temp, tokenLength);
1050
1051     // save token
1052     *token = temp;
1053
1054     OIC_LOG_V(DEBUG, TAG, "token len:%d, token:", tokenLength);
1055     OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *)(*token), tokenLength);
1056
1057     return CA_STATUS_OK;
1058 }
1059
1060 void CADestroyTokenInternal(CAToken_t token)
1061 {
1062     OICFree(token);
1063 }
1064
1065 uint32_t CAGetOptionData(uint16_t key, const uint8_t *data, uint32_t len,
1066         uint8_t *option, uint32_t buflen)
1067 {
1068     if (0 == buflen)
1069     {
1070         OIC_LOG(ERROR, TAG, "buflen 0");
1071         return 0;
1072     }
1073
1074     if (buflen <= len)
1075     {
1076         OIC_LOG(ERROR, TAG, "option buffer too small");
1077         return 0;
1078     }
1079
1080     coap_option_def_t* def = coap_opt_def(key);
1081     if (NULL != def && coap_is_var_bytes(def) && 0 == len)
1082     {
1083         // A 0 length option is permitted in CoAP but the
1084         // rest or the stack is unaware of variable byte encoding
1085         // should remain that way so a 0 byte of length 1 is inserted.
1086         len = 1;
1087         option[0]=0;
1088     }
1089     else
1090     {
1091         memcpy(option, data, len);
1092         option[len] = '\0';
1093     }
1094
1095     return len;
1096 }
1097
1098 CAMessageType_t CAGetMessageTypeFromPduBinaryData(const void *pdu, uint32_t size)
1099 {
1100     VERIFY_NON_NULL_RET(pdu, TAG, "pdu", CA_MSG_NONCONFIRM);
1101
1102     // pdu minimum size is 4 byte.
1103     if (size < CA_PDU_MIN_SIZE)
1104     {
1105         OIC_LOG(ERROR, TAG, "min size");
1106         return CA_MSG_NONCONFIRM;
1107     }
1108
1109     coap_hdr_t *hdr = (coap_hdr_t *) pdu;
1110
1111     return (CAMessageType_t) hdr->coap_hdr_udp_t.type;
1112 }
1113
1114 uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size)
1115 {
1116     VERIFY_NON_NULL_RET(pdu, TAG, "pdu", 0);
1117
1118     // pdu minimum size is 4 byte.
1119     if (size < CA_PDU_MIN_SIZE)
1120     {
1121         OIC_LOG(ERROR, TAG, "min size");
1122         return 0;
1123     }
1124
1125     coap_hdr_t *hdr = (coap_hdr_t *) pdu;
1126
1127     return hdr->coap_hdr_udp_t.id;
1128 }
1129
1130 CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size)
1131 {
1132     VERIFY_NON_NULL_RET(pdu, TAG, "pdu", CA_NOT_FOUND);
1133
1134     // pdu minimum size is 4 byte.
1135     if (size < CA_PDU_MIN_SIZE)
1136     {
1137         OIC_LOG(ERROR, TAG, "min size");
1138         return CA_NOT_FOUND;
1139     }
1140
1141     coap_hdr_t *hdr = (coap_hdr_t *) pdu;
1142
1143     return (CAResponseResult_t) CA_RESPONSE_CODE(hdr->coap_hdr_udp_t.code);
1144 }
1145
1146 CAPayloadFormat_t CAConvertFormat(uint8_t format)
1147 {
1148     switch (format)
1149     {
1150         case COAP_MEDIATYPE_TEXT_PLAIN:
1151             return CA_FORMAT_TEXT_PLAIN;
1152         case COAP_MEDIATYPE_APPLICATION_LINK_FORMAT:
1153             return CA_FORMAT_APPLICATION_LINK_FORMAT;
1154         case COAP_MEDIATYPE_APPLICATION_XML:
1155             return CA_FORMAT_APPLICATION_XML;
1156         case COAP_MEDIATYPE_APPLICATION_OCTET_STREAM:
1157             return CA_FORMAT_APPLICATION_OCTET_STREAM;
1158         case COAP_MEDIATYPE_APPLICATION_RDF_XML:
1159             return CA_FORMAT_APPLICATION_RDF_XML;
1160         case COAP_MEDIATYPE_APPLICATION_EXI:
1161             return CA_FORMAT_APPLICATION_EXI;
1162         case COAP_MEDIATYPE_APPLICATION_JSON:
1163             return CA_FORMAT_APPLICATION_JSON;
1164         case COAP_MEDIATYPE_APPLICATION_CBOR:
1165             return CA_FORMAT_APPLICATION_CBOR;
1166         default:
1167             return CA_FORMAT_UNSUPPORTED;
1168     }
1169 }
1170
1171 #ifdef WITH_BWT
1172 bool CAIsSupportedBlockwiseTransfer(CATransportAdapter_t adapter)
1173 {
1174     if (CA_ADAPTER_IP & adapter || CA_ADAPTER_NFC & adapter
1175             || CA_DEFAULT_ADAPTER == adapter)
1176     {
1177         return true;
1178     }
1179     return false;
1180 }
1181 #endif
1182
1183 #ifdef WITH_TCP
1184 bool CAIsSupportedCoAPOverTCP(CATransportAdapter_t adapter)
1185 {
1186     if (CA_ADAPTER_GATT_BTLE & adapter || CA_ADAPTER_RFCOMM_BTEDR & adapter
1187             || CA_ADAPTER_TCP & adapter || CA_DEFAULT_ADAPTER == adapter)
1188     {
1189         return true;
1190     }
1191     return false;
1192 }
1193 #endif