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