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