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