CoAP over TCP transmission over BLE
[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_PORT_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 #else
187     (void) endpoint;
188 #endif
189     {
190         transport = coap_udp;
191     }
192
193     coap_pdu_t *outpdu = coap_new_pdu(transport, length);
194     if (NULL == outpdu)
195     {
196         OIC_LOG(ERROR, TAG, "outpdu is null");
197         return NULL;
198     }
199
200     OIC_LOG_V(DEBUG, TAG, "pdu parse-transport type : %d", transport);
201
202     int ret = coap_pdu_parse((unsigned char *) data, length, outpdu, transport);
203     OIC_LOG_V(DEBUG, TAG, "pdu parse ret: %d", ret);
204     if (0 >= ret)
205     {
206         OIC_LOG(ERROR, TAG, "pdu parse failed");
207         coap_delete_pdu(outpdu);
208         return NULL;
209     }
210
211 #ifdef WITH_TCP
212     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
213     {
214         OIC_LOG(INFO, TAG, "there is no version info in coap header");
215     }
216     else
217 #endif
218     {
219         if (outpdu->hdr->coap_hdr_udp_t.version != COAP_DEFAULT_VERSION)
220         {
221             OIC_LOG_V(ERROR, TAG, "coap version is not available : %d",
222                       outpdu->hdr->coap_hdr_udp_t.version);
223             coap_delete_pdu(outpdu);
224             return NULL;
225         }
226         if (outpdu->hdr->coap_hdr_udp_t.token_length > CA_MAX_TOKEN_LEN)
227         {
228             OIC_LOG_V(ERROR, TAG, "token length has been exceed : %d",
229                       outpdu->hdr->coap_hdr_udp_t.token_length);
230             coap_delete_pdu(outpdu);
231             return NULL;
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
243 coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
244                               const CAEndpoint_t *endpoint, coap_list_t *options,
245                               coap_transport_type *transport)
246 {
247     VERIFY_NON_NULL_RET(info, TAG, "info", NULL);
248     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", NULL);
249     VERIFY_NON_NULL_RET(transport, TAG, "transport", NULL);
250
251     unsigned int length = COAP_MAX_PDU_SIZE;
252 #ifdef WITH_TCP
253     unsigned int msgLength = 0;
254     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
255     {
256         if (options)
257         {
258             unsigned short prevOptNumber = 0;
259             for (coap_list_t *opt = options; opt; opt = opt->next)
260             {
261                 unsigned short curOptNumber = COAP_OPTION_KEY(*(coap_option *) opt->data);
262                 if (prevOptNumber > curOptNumber)
263                 {
264                     OIC_LOG(ERROR, TAG, "option list is wrong");
265                     return NULL;
266                 }
267
268                 size_t optValueLen = COAP_OPTION_LENGTH(*(coap_option *) opt->data);
269                 size_t optLength = coap_get_opt_header_length(curOptNumber - prevOptNumber, optValueLen);
270                 if (0 == optLength)
271                 {
272                     OIC_LOG(ERROR, TAG, "Reserved for the Payload marker for the option");
273                     return NULL;
274                 }
275                 msgLength += optLength;
276                 prevOptNumber = curOptNumber;
277                 OIC_LOG_V(DEBUG, TAG, "curOptNumber[%d], prevOptNumber[%d], optValueLen[%zu], "
278                         "optLength[%zu], msgLength[%d]",
279                           curOptNumber, prevOptNumber, optValueLen, optLength, msgLength);
280             }
281         }
282
283         if (info->payloadSize > 0)
284         {
285             msgLength = msgLength + info->payloadSize + PAYLOAD_MARKER;
286         }
287         *transport = coap_get_tcp_header_type_from_size(msgLength);
288         length = msgLength + coap_get_tcp_header_length_for_transport(*transport)
289                 + info->tokenLength;
290     }
291     else
292 #endif
293     {
294         *transport = coap_udp;
295     }
296
297     coap_pdu_t *pdu = coap_new_pdu(*transport, length);
298
299     if (NULL == pdu)
300     {
301         OIC_LOG(ERROR, TAG, "malloc failed");
302         return NULL;
303     }
304
305     OIC_LOG_V(DEBUG, TAG, "transport type: %d, payload size: %zu",
306               *transport, info->payloadSize);
307
308 #ifdef WITH_TCP
309     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
310     {
311         coap_add_length(pdu, *transport, msgLength);
312     }
313     else
314 #endif
315     {
316         OIC_LOG_V(DEBUG, TAG, "msgID is %d", info->messageId);
317         uint16_t message_id;
318         if (0 == info->messageId)
319         {
320             /* initialize message id */
321             prng((uint8_t * ) &message_id, sizeof(message_id));
322
323             OIC_LOG_V(DEBUG, TAG, "gen msg id=%d", message_id);
324         }
325         else
326         {
327             /* use saved message id */
328             message_id = info->messageId;
329         }
330         pdu->hdr->coap_hdr_udp_t.id = message_id;
331         OIC_LOG_V(DEBUG, TAG, "messageId in pdu is %d, %d", message_id, pdu->hdr->coap_hdr_udp_t.id);
332
333         pdu->hdr->coap_hdr_udp_t.type = info->type;
334     }
335
336     coap_add_code(pdu, *transport, code);
337
338     if (info->token && CA_EMPTY != code)
339     {
340         uint32_t tokenLength = info->tokenLength;
341         OIC_LOG_V(DEBUG, TAG, "token info token length: %d, token :", tokenLength);
342         OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *)info->token, tokenLength);
343
344         int32_t ret = coap_add_token(pdu, tokenLength, (unsigned char *)info->token, *transport);
345         if (0 == ret)
346         {
347             OIC_LOG(ERROR, TAG, "can't add token");
348         }
349     }
350
351 #ifdef WITH_BWT
352     if (CA_ADAPTER_GATT_BTLE != endpoint->adapter
353 #ifdef WITH_TCP
354             && !CAIsSupportedCoAPOverTCP(endpoint->adapter)
355 #endif
356             )
357     {
358         // option list will be added in blockwise-transfer
359         return pdu;
360     }
361 #endif
362
363     if (options)
364     {
365         for (coap_list_t *opt = options; opt; opt = opt->next)
366         {
367             OIC_LOG_V(DEBUG, TAG, "[%s] opt will be added.",
368                       COAP_OPTION_DATA(*(coap_option *) opt->data));
369
370             OIC_LOG_V(DEBUG, TAG, "[%d] pdu length", pdu->length);
371             coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
372                             COAP_OPTION_LENGTH(*(coap_option *) opt->data),
373                             COAP_OPTION_DATA(*(coap_option *) opt->data), *transport);
374         }
375     }
376
377     OIC_LOG_V(DEBUG, TAG, "[%d] pdu length after option", pdu->length);
378
379     if (NULL != info->payload && 0 < info->payloadSize)
380     {
381         OIC_LOG(DEBUG, TAG, "payload is added");
382         coap_add_data(pdu, info->payloadSize, (const unsigned char *) info->payload);
383     }
384
385     return pdu;
386 }
387
388 CAResult_t CAParseURI(const char *uriInfo, coap_list_t **optlist)
389 {
390     VERIFY_NON_NULL(uriInfo, TAG, "uriInfo");
391     VERIFY_NON_NULL(optlist, TAG, "optlist");
392
393     OIC_LOG_V(DEBUG, TAG, "url : %s", uriInfo);
394
395     /* split arg into Uri-* options */
396     coap_uri_t uri;
397     coap_split_uri((unsigned char *) uriInfo, strlen(uriInfo), &uri);
398
399     if (uri.port != COAP_DEFAULT_PORT)
400     {
401         unsigned char portbuf[CA_PORT_BUFFER_SIZE] = { 0 };
402         int ret = coap_insert(optlist,
403                               CACreateNewOptionNode(COAP_OPTION_URI_PORT,
404                                                     coap_encode_var_bytes(portbuf, uri.port),
405                                                     (char *)portbuf),
406                               CAOrderOpts);
407         if (ret <= 0)
408         {
409             return CA_STATUS_INVALID_PARAM;
410         }
411     }
412
413     if (uri.path.s && uri.path.length)
414     {
415         CAResult_t ret = CAParseUriPartial(uri.path.s, uri.path.length,
416                                            COAP_OPTION_URI_PATH, optlist);
417         if (CA_STATUS_OK != ret)
418         {
419             OIC_LOG(ERROR, TAG, "CAParseUriPartial failed(uri path)");
420             return ret;
421         }
422     }
423
424     if (uri.query.s && uri.query.length)
425     {
426         CAResult_t ret = CAParseUriPartial(uri.query.s, uri.query.length, COAP_OPTION_URI_QUERY,
427                                            optlist);
428         if (CA_STATUS_OK != ret)
429         {
430             OIC_LOG(ERROR, TAG, "CAParseUriPartial failed(uri query)");
431             return ret;
432         }
433     }
434
435     return CA_STATUS_OK;
436 }
437
438 CAResult_t CAParseUriPartial(const unsigned char *str, size_t length, int target,
439                              coap_list_t **optlist)
440 {
441     VERIFY_NON_NULL(optlist, TAG, "optlist");
442
443     if ((target != COAP_OPTION_URI_PATH) && (target != COAP_OPTION_URI_QUERY))
444     {
445         // should never occur. Log just in case.
446         OIC_LOG(DEBUG, TAG, "Unexpected URI component.");
447         return CA_NOT_SUPPORTED;
448     }
449     else if (str && length)
450     {
451         unsigned char uriBuffer[CA_BUFSIZE] = { 0 };
452         unsigned char *pBuf = uriBuffer;
453         size_t buflen = sizeof(uriBuffer);
454         int res = (target == COAP_OPTION_URI_PATH) ? coap_split_path(str, length, pBuf, &buflen) :
455                                                      coap_split_query(str, length, pBuf, &buflen);
456
457         if (res > 0)
458         {
459             size_t prevIdx = 0;
460             while (res--)
461             {
462                 int ret = coap_insert(optlist,
463                                       CACreateNewOptionNode(target, COAP_OPT_LENGTH(pBuf),
464                                                             (char *)COAP_OPT_VALUE(pBuf)),
465                                       CAOrderOpts);
466                 if (ret <= 0)
467                 {
468                     return CA_STATUS_INVALID_PARAM;
469                 }
470
471                 size_t optSize = COAP_OPT_SIZE(pBuf);
472                 if ((prevIdx + optSize) < buflen)
473                 {
474                     pBuf += optSize;
475                     prevIdx += optSize;
476                 }
477             }
478         }
479         else
480         {
481             OIC_LOG_V(ERROR, TAG, "Problem parsing URI : %d for %d", res, target);
482             return CA_STATUS_FAILED;
483         }
484     }
485     else
486     {
487         OIC_LOG(ERROR, TAG, "str or length is not available");
488         return CA_STATUS_FAILED;
489     }
490
491     return CA_STATUS_OK;
492 }
493
494 CAResult_t CAParseHeadOption(uint32_t code, const CAInfo_t *info, coap_list_t **optlist)
495 {
496     (void)code;
497     VERIFY_NON_NULL_RET(info, TAG, "info", CA_STATUS_INVALID_PARAM);
498
499     OIC_LOG_V(DEBUG, TAG, "parse Head Opt: %d", info->numOptions);
500
501     if (!optlist)
502     {
503         OIC_LOG(ERROR, TAG, "optlist is null");
504         return CA_STATUS_INVALID_PARAM;
505     }
506
507     for (uint32_t i = 0; i < info->numOptions; i++)
508     {
509         if(!(info->options + i))
510         {
511             OIC_LOG(ERROR, TAG, "options is not available");
512             return CA_STATUS_FAILED;
513         }
514
515         uint32_t id = (info->options + i)->optionID;
516         if (COAP_OPTION_URI_PATH == id || COAP_OPTION_URI_QUERY == id)
517         {
518             OIC_LOG_V(DEBUG, TAG, "not Header Opt: %d", id);
519         }
520         else
521         {
522             OIC_LOG_V(DEBUG, TAG, "Head opt ID: %d", id);
523             OIC_LOG_V(DEBUG, TAG, "Head opt data: %s", (info->options + i)->optionData);
524             OIC_LOG_V(DEBUG, TAG, "Head opt length: %d", (info->options + i)->optionLength);
525             int ret = coap_insert(optlist,
526                                   CACreateNewOptionNode(id, (info->options + i)->optionLength,
527                                                         (info->options + i)->optionData),
528                                   CAOrderOpts);
529             if (ret <= 0)
530             {
531                 return CA_STATUS_INVALID_PARAM;
532             }
533         }
534     }
535
536     // insert one extra header with the payload format if applicable.
537     if (CA_FORMAT_UNDEFINED != info->payloadFormat)
538     {
539         coap_list_t* node = NULL;
540         uint8_t buf[3] = {0};
541         switch (info->payloadFormat)
542         {
543             case CA_FORMAT_APPLICATION_CBOR:
544                 node = CACreateNewOptionNode(
545                         COAP_OPTION_CONTENT_FORMAT,
546                         coap_encode_var_bytes(buf, (uint16_t)COAP_MEDIATYPE_APPLICATION_CBOR),
547                         (char *)buf);
548                 break;
549             default:
550                 OIC_LOG_V(ERROR, TAG, "format option:[%d] not supported", info->payloadFormat);
551         }
552         if (!node)
553         {
554             OIC_LOG(ERROR, TAG, "format option not created");
555             return CA_STATUS_INVALID_PARAM;
556         }
557         int ret = coap_insert(optlist, node, CAOrderOpts);
558         if (ret <= 0)
559         {
560             coap_delete(node);
561             OIC_LOG(ERROR, TAG, "format option not inserted in header");
562             return CA_STATUS_INVALID_PARAM;
563         }
564     }
565     if (CA_FORMAT_UNDEFINED != info->acceptFormat)
566     {
567         coap_list_t* node = NULL;
568         uint8_t buf[3] = {0};
569         switch (info->acceptFormat)
570         {
571             case CA_FORMAT_APPLICATION_CBOR:
572                 node = CACreateNewOptionNode(
573                         COAP_OPTION_ACCEPT,
574                         coap_encode_var_bytes(buf, (uint16_t)COAP_MEDIATYPE_APPLICATION_CBOR),
575                         (char *)buf);
576                 break;
577             default:
578                 OIC_LOG_V(ERROR, TAG, "format option:[%d] not supported", info->acceptFormat);
579         }
580         if (!node)
581         {
582             OIC_LOG(ERROR, TAG, "format option not created");
583             return CA_STATUS_INVALID_PARAM;
584         }
585         int ret = coap_insert(optlist, node, CAOrderOpts);
586         if (ret <= 0)
587         {
588             coap_delete(node);
589             OIC_LOG(ERROR, TAG, "format option not inserted in header");
590             return CA_STATUS_INVALID_PARAM;
591         }
592     }
593
594     return CA_STATUS_OK;
595 }
596
597 coap_list_t *CACreateNewOptionNode(uint16_t key, uint32_t length, const char *data)
598 {
599     VERIFY_NON_NULL_RET(data, TAG, "data", NULL);
600
601     coap_option *option = coap_malloc(sizeof(coap_option) + length + 1);
602     if (!option)
603     {
604         OIC_LOG(ERROR, TAG, "Out of memory");
605         return NULL;
606     }
607     memset(option, 0, sizeof(coap_option) + length + 1);
608
609     COAP_OPTION_KEY(*option) = key;
610
611     coap_option_def_t* def = coap_opt_def(key);
612     if (NULL != def && coap_is_var_bytes(def))
613     {
614        if (length > def->max)
615         {
616             // make sure we shrink the value so it fits the coap option definition
617             // by truncating the value, disregard the leading bytes.
618             OIC_LOG_V(DEBUG, TAG, "Option [%d] data size [%d] shrunk to [%d]",
619                     def->key, length, def->max);
620             data = &(data[length-def->max]);
621             length = def->max;
622         }
623         // Shrink the encoding length to a minimum size for coap
624         // options that support variable length encoding.
625          COAP_OPTION_LENGTH(*option) = coap_encode_var_bytes(
626                 COAP_OPTION_DATA(*option),
627                 coap_decode_var_bytes((unsigned char *)data, length));
628     }
629     else
630     {
631         COAP_OPTION_LENGTH(*option) = length;
632         memcpy(COAP_OPTION_DATA(*option), data, length);
633     }
634
635     /* we can pass NULL here as delete function since option is released automatically  */
636     coap_list_t *node = coap_new_listnode(option, NULL);
637
638     if (!node)
639     {
640         OIC_LOG(ERROR, TAG, "node is NULL");
641         coap_free(option);
642         return NULL;
643     }
644
645     return node;
646 }
647
648 int CAOrderOpts(void *a, void *b)
649 {
650     if (!a || !b)
651     {
652         return a < b ? -1 : 1;
653     }
654
655     if (COAP_OPTION_KEY(*(coap_option *) a) < COAP_OPTION_KEY(*(coap_option * ) b))
656     {
657         return -1;
658     }
659
660     return COAP_OPTION_KEY(*(coap_option *) a) == COAP_OPTION_KEY(*(coap_option * ) b);
661 }
662
663 uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter)
664 {
665     uint32_t count = 0;
666     coap_opt_t *option;
667
668     while ((option = coap_option_next(&opt_iter)))
669     {
670         if (COAP_OPTION_URI_PATH != opt_iter.type && COAP_OPTION_URI_QUERY != opt_iter.type
671             && COAP_OPTION_BLOCK1 != opt_iter.type && COAP_OPTION_BLOCK2 != opt_iter.type
672             && COAP_OPTION_SIZE1 != opt_iter.type && COAP_OPTION_SIZE2 != opt_iter.type
673             && COAP_OPTION_CONTENT_FORMAT != opt_iter.type
674             && COAP_OPTION_ACCEPT != opt_iter.type)
675         {
676             count++;
677         }
678     }
679
680     return count;
681 }
682
683 CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
684                             uint32_t *outCode, CAInfo_t *outInfo)
685 {
686     VERIFY_NON_NULL(pdu, TAG, "pdu");
687     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
688     VERIFY_NON_NULL(outCode, TAG, "outCode");
689     VERIFY_NON_NULL(outInfo, TAG, "outInfo");
690
691     coap_transport_type transport;
692 #ifdef WITH_TCP
693     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
694     {
695         transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)pdu->hdr)[0] >> 4);
696     }
697     else
698 #else
699     (void) endpoint;
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
873             {
874                 if (idx < count)
875                 {
876                     if (bufLength <= sizeof(outInfo->options[0].optionData))
877                     {
878                         outInfo->options[idx].optionID = opt_iter.type;
879                         outInfo->options[idx].optionLength = bufLength;
880                         outInfo->options[idx].protocolID = CA_COAP_ID;
881                         memcpy(outInfo->options[idx].optionData, buf, bufLength);
882                         idx++;
883                     }
884                 }
885             }
886         }
887     }
888
889     unsigned char* token = NULL;
890     unsigned int token_length = 0;
891     coap_get_token(pdu->hdr, transport, &token, &token_length);
892
893     // set token data
894     if (token_length > 0)
895     {
896         OIC_LOG_V(DEBUG, TAG, "inside token length : %d", token_length);
897         outInfo->token = (char *) OICMalloc(token_length);
898         if (NULL == outInfo->token)
899         {
900             OIC_LOG(ERROR, TAG, "Out of memory");
901             OICFree(outInfo->options);
902             return CA_MEMORY_ALLOC_FAILED;
903         }
904         memcpy(outInfo->token, token, token_length);
905     }
906
907     outInfo->tokenLength = token_length;
908
909     // set payload data
910     size_t dataSize;
911     uint8_t *data;
912     if (coap_get_data(pdu, &dataSize, &data))
913     {
914         OIC_LOG(DEBUG, TAG, "inside pdu->data");
915         outInfo->payload = (uint8_t *) OICMalloc(dataSize);
916         if (NULL == outInfo->payload)
917         {
918             OIC_LOG(ERROR, TAG, "Out of memory");
919             OICFree(outInfo->options);
920             OICFree(outInfo->token);
921             return CA_MEMORY_ALLOC_FAILED;
922         }
923         memcpy(outInfo->payload, pdu->data, dataSize);
924         outInfo->payloadSize = dataSize;
925     }
926
927     if (optionResult[0] != '\0')
928     {
929         OIC_LOG_V(DEBUG, TAG, "URL length:%zu", strlen(optionResult));
930         outInfo->resourceUri = OICStrdup(optionResult);
931         if (!outInfo->resourceUri)
932         {
933             OIC_LOG(ERROR, TAG, "Out of memory");
934             OICFree(outInfo->options);
935             OICFree(outInfo->token);
936             return CA_MEMORY_ALLOC_FAILED;
937         }
938     }
939
940     return CA_STATUS_OK;
941
942 exit:
943     OIC_LOG(ERROR, TAG, "buffer too small");
944     OICFree(outInfo->options);
945     return CA_STATUS_FAILED;
946 }
947
948 CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo,
949                              const CAEndpoint_t *endpoint)
950 {
951     VERIFY_NON_NULL(pdu_hdr, TAG, "pdu_hdr");
952     VERIFY_NON_NULL(outInfo, TAG, "outInfo");
953     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
954
955     coap_transport_type transport;
956 #ifdef WITH_TCP
957     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
958     {
959         transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)pdu_hdr)[0] >> 4);
960     }
961     else
962 #endif
963     {
964         transport = coap_udp;
965     }
966
967     unsigned char* token = NULL;
968     unsigned int token_length = 0;
969     coap_get_token(pdu_hdr, transport, &token, &token_length);
970
971     // set token data
972     if (token_length > 0)
973     {
974         OIC_LOG_V(DEBUG, TAG, "token len:%d", token_length);
975         outInfo->token = (char *) OICMalloc(token_length);
976         if (NULL == outInfo->token)
977         {
978             OIC_LOG(ERROR, TAG, "Out of memory");
979             return CA_MEMORY_ALLOC_FAILED;
980         }
981         memcpy(outInfo->token, token, token_length);
982     }
983
984     outInfo->tokenLength = token_length;
985
986     return CA_STATUS_OK;
987 }
988
989 CAResult_t CAGenerateTokenInternal(CAToken_t *token, uint8_t tokenLength)
990 {
991     VERIFY_NON_NULL(token, TAG, "token");
992
993     if ((tokenLength > CA_MAX_TOKEN_LEN) || (0 == tokenLength))
994     {
995         OIC_LOG(ERROR, TAG, "invalid token length");
996         return CA_STATUS_INVALID_PARAM;
997     }
998
999     // memory allocation
1000     char *temp = (char *) OICCalloc(tokenLength, sizeof(char));
1001     if (NULL == temp)
1002     {
1003         OIC_LOG(ERROR, TAG, "Out of memory");
1004         return CA_MEMORY_ALLOC_FAILED;
1005     }
1006
1007     OCFillRandomMem((uint8_t *)temp, tokenLength);
1008
1009     // save token
1010     *token = temp;
1011
1012     OIC_LOG_V(DEBUG, TAG, "token len:%d, token:", tokenLength);
1013     OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *)(*token), tokenLength);
1014
1015     return CA_STATUS_OK;
1016 }
1017
1018 void CADestroyTokenInternal(CAToken_t token)
1019 {
1020     OICFree(token);
1021 }
1022
1023 void CADestroyInfo(CAInfo_t *info)
1024 {
1025     if (NULL != info)
1026     {
1027         OIC_LOG(DEBUG, TAG, "free options");
1028         OICFree(info->options);
1029
1030         OIC_LOG(DEBUG, TAG, "free token");
1031         OICFree(info->token);
1032
1033         OIC_LOG(DEBUG, TAG, "free payload");
1034         OICFree(info->payload);
1035     }
1036 }
1037
1038 uint32_t CAGetOptionData(uint16_t key, const uint8_t *data, uint32_t len,
1039         uint8_t *option, uint32_t buflen)
1040 {
1041     if (0 == buflen)
1042     {
1043         OIC_LOG(ERROR, TAG, "buflen 0");
1044         return 0;
1045     }
1046
1047     if (buflen <= len)
1048     {
1049         OIC_LOG(ERROR, TAG, "option buffer too small");
1050         return 0;
1051     }
1052
1053     coap_option_def_t* def = coap_opt_def(key);
1054     if (NULL != def && coap_is_var_bytes(def) && 0 == len)
1055     {
1056         // A 0 length option is permitted in CoAP but the
1057         // rest or the stack is unaware of variable byte encoding
1058         // should remain that way so a 0 byte of length 1 is inserted.
1059         len = 1;
1060         option[0]=0;
1061     } else {
1062         memcpy(option, data, len);
1063         option[len] = '\0';
1064     }
1065
1066     return len;
1067 }
1068
1069 CAMessageType_t CAGetMessageTypeFromPduBinaryData(const void *pdu, uint32_t size)
1070 {
1071     VERIFY_NON_NULL_RET(pdu, TAG, "pdu", CA_MSG_NONCONFIRM);
1072
1073     // pdu minimum size is 4 byte.
1074     if (size < CA_PDU_MIN_SIZE)
1075     {
1076         OIC_LOG(ERROR, TAG, "min size");
1077         return CA_MSG_NONCONFIRM;
1078     }
1079
1080     coap_hdr_t *hdr = (coap_hdr_t *) pdu;
1081
1082     return (CAMessageType_t) hdr->coap_hdr_udp_t.type;
1083 }
1084
1085 uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size)
1086 {
1087     VERIFY_NON_NULL_RET(pdu, TAG, "pdu", 0);
1088
1089     // pdu minimum size is 4 byte.
1090     if (size < CA_PDU_MIN_SIZE)
1091     {
1092         OIC_LOG(ERROR, TAG, "min size");
1093         return 0;
1094     }
1095
1096     coap_hdr_t *hdr = (coap_hdr_t *) pdu;
1097
1098     return hdr->coap_hdr_udp_t.id;
1099 }
1100
1101 CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size)
1102 {
1103     VERIFY_NON_NULL_RET(pdu, TAG, "pdu", CA_NOT_FOUND);
1104
1105     // pdu minimum size is 4 byte.
1106     if (size < CA_PDU_MIN_SIZE)
1107     {
1108         OIC_LOG(ERROR, TAG, "min size");
1109         return CA_NOT_FOUND;
1110     }
1111
1112     coap_hdr_t *hdr = (coap_hdr_t *) pdu;
1113
1114     return (CAResponseResult_t) CA_RESPONSE_CODE(hdr->coap_hdr_udp_t.code);
1115 }
1116
1117 CAPayloadFormat_t CAConvertFormat(uint8_t format)
1118 {
1119     switch (format)
1120     {
1121         case COAP_MEDIATYPE_TEXT_PLAIN:
1122             return CA_FORMAT_TEXT_PLAIN;
1123         case COAP_MEDIATYPE_APPLICATION_LINK_FORMAT:
1124             return CA_FORMAT_APPLICATION_LINK_FORMAT;
1125         case COAP_MEDIATYPE_APPLICATION_XML:
1126             return CA_FORMAT_APPLICATION_XML;
1127         case COAP_MEDIATYPE_APPLICATION_OCTET_STREAM:
1128             return CA_FORMAT_APPLICATION_OCTET_STREAM;
1129         case COAP_MEDIATYPE_APPLICATION_RDF_XML:
1130             return CA_FORMAT_APPLICATION_RDF_XML;
1131         case COAP_MEDIATYPE_APPLICATION_EXI:
1132             return CA_FORMAT_APPLICATION_EXI;
1133         case COAP_MEDIATYPE_APPLICATION_JSON:
1134             return CA_FORMAT_APPLICATION_JSON;
1135         case COAP_MEDIATYPE_APPLICATION_CBOR:
1136             return CA_FORMAT_APPLICATION_CBOR;
1137         default:
1138             return CA_FORMAT_UNSUPPORTED;
1139     }
1140 }
1141
1142 #ifdef WITH_TCP
1143 bool CAIsSupportedCoAPOverTCP(CATransportAdapter_t adapter)
1144 {
1145     if (CA_ADAPTER_GATT_BTLE == adapter || CA_ADAPTER_RFCOMM_BTEDR == adapter
1146             || CA_ADAPTER_TCP == adapter)
1147     {
1148         return true;
1149     }
1150     return false;
1151 }
1152 #endif