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