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