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