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