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