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