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