1 /******************************************************************
3 * Copyright 2014 Samsung Electronics All Rights Reserved.
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 ******************************************************************/
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
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
31 #include "iotivity_config.h"
40 #include "caprotocolmessage.h"
42 #include "oic_malloc.h"
43 #include "oic_string.h"
45 #include "cacommonutil.h"
47 #define TAG "OIC_CA_PRTCL_MSG"
49 #define CA_PDU_MIN_SIZE (4)
50 #define CA_ENCODE_BUFFER_SIZE (4)
52 static const char COAP_URI_HEADER[] = "coap://[::]/";
54 static char g_chproxyUri[CA_MAX_URI_LENGTH];
56 CAResult_t CASetProxyUri(const char *uri)
58 VERIFY_NON_NULL(uri, TAG, "uri");
59 OICStrcpy(g_chproxyUri, sizeof (g_chproxyUri), uri);
63 CAResult_t CAGetRequestInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
64 CARequestInfo_t *outReqInfo)
66 VERIFY_NON_NULL(pdu, TAG, "pdu");
67 VERIFY_NON_NULL(outReqInfo, TAG, "outReqInfo");
69 uint32_t code = CA_NOT_FOUND;
70 CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &(outReqInfo->info));
71 outReqInfo->method = code;
76 CAResult_t CAGetResponseInfoFromPDU(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,
77 const CAEndpoint_t *endpoint)
79 VERIFY_NON_NULL(pdu, TAG, "pdu");
80 VERIFY_NON_NULL(outResInfo, TAG, "outResInfo");
82 uint32_t code = CA_NOT_FOUND;
83 CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &(outResInfo->info));
84 outResInfo->result = code;
89 CAResult_t CAGetErrorInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
90 CAErrorInfo_t *errorInfo)
92 VERIFY_NON_NULL(pdu, TAG, "pdu");
95 CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &errorInfo->info);
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)
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);
107 OIC_LOG_V(DEBUG, TAG, "generate pdu for [%d]adapter, [%d]flags",
108 endpoint->adapter, endpoint->flags);
110 coap_pdu_t *pdu = NULL;
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))
116 if (CA_EMPTY != code)
118 OIC_LOG(ERROR, TAG, "reset is not empty message");
122 if (info->payloadSize > 0 || info->payload || info->token || info->tokenLength > 0)
124 OIC_LOG(ERROR, TAG, "Empty message has unnecessary data after messageID");
128 OIC_LOG(DEBUG, TAG, "code is empty");
129 if (!(pdu = CAGeneratePDUImpl((code_t) code, info, endpoint, NULL, transport)))
131 OIC_LOG(ERROR, TAG, "pdu NULL");
137 if (info->resourceUri)
139 OIC_LOG_V(DEBUG, TAG, "uri : %s", info->resourceUri);
141 uint32_t length = strlen(info->resourceUri);
142 if (CA_MAX_URI_LENGTH < length)
144 OIC_LOG(ERROR, TAG, "URI len err");
148 uint32_t uriLength = length + sizeof(COAP_URI_HEADER);
149 char *coapUri = (char *) OICCalloc(1, uriLength);
152 OIC_LOG(ERROR, TAG, "out of memory");
155 OICStrcat(coapUri, uriLength, COAP_URI_HEADER);
156 OICStrcat(coapUri, uriLength, info->resourceUri);
158 // parsing options in URI
159 CAResult_t res = CAParseURI(coapUri, optlist);
160 if (CA_STATUS_OK != res)
168 // parsing options in HeadOption
169 CAResult_t ret = CAParseHeadOption(code, info, optlist);
170 if (CA_STATUS_OK != ret)
175 pdu = CAGeneratePDUImpl((code_t) code, info, endpoint, *optlist, transport);
178 OIC_LOG(ERROR, TAG, "pdu NULL");
183 // pdu print method : coap_show_pdu(pdu);
187 coap_pdu_t *CAParsePDU(const char *data, size_t length, uint32_t *outCode,
188 const CAEndpoint_t *endpoint)
190 VERIFY_NON_NULL_RET(data, TAG, "data", NULL);
191 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", NULL);
193 coap_transport_t transport = COAP_UDP;
195 if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
197 transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)data)[0] >> 4);
202 coap_pdu_init2(0, 0, ntohs(COAP_INVALID_TID), length, transport);
205 OIC_LOG(ERROR, TAG, "outpdu is null");
209 OIC_LOG_V(DEBUG, TAG, "pdu parse-transport type : %d", transport);
211 int ret = coap_pdu_parse2((unsigned char *) data, length, outpdu, transport);
212 OIC_LOG_V(DEBUG, TAG, "pdu parse ret: %d", ret);
215 OIC_LOG(ERROR, TAG, "pdu parse failed");
220 if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
222 OIC_LOG(INFO, TAG, "there is no version info in coap header");
227 if (outpdu->transport_hdr->udp.version != COAP_DEFAULT_VERSION)
229 OIC_LOG_V(ERROR, TAG, "coap version is not available : %d",
230 outpdu->transport_hdr->udp.version);
233 if (outpdu->transport_hdr->udp.token_length > CA_MAX_TOKEN_LEN)
235 OIC_LOG_V(ERROR, TAG, "token length has been exceed : %d",
236 outpdu->transport_hdr->udp.token_length);
243 (*outCode) = (uint32_t) CA_RESPONSE_CODE(coap_get_code(outpdu, transport));
249 OIC_LOG(DEBUG, TAG, "data :");
250 OIC_LOG_BUFFER(DEBUG, TAG, data, length);
251 coap_delete_pdu(outpdu);
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)
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);
263 unsigned int length = COAP_MAX_PDU_SIZE;
265 unsigned int msgLength = 0;
266 if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
270 unsigned short prevOptNumber = 0;
271 for (coap_list_t *opt = options; opt; opt = opt->next)
273 unsigned short curOptNumber = COAP_OPTION_KEY(*(coap_option *) opt->data);
274 if (prevOptNumber > curOptNumber)
276 OIC_LOG(ERROR, TAG, "option list is wrong");
280 size_t optValueLen = COAP_OPTION_LENGTH(*(coap_option *) opt->data);
281 size_t optLength = coap_get_opt_header_length(curOptNumber - prevOptNumber, optValueLen);
284 OIC_LOG(ERROR, TAG, "Reserved for the Payload marker for the option");
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);
295 if (info->payloadSize > 0)
297 msgLength = msgLength + info->payloadSize + PAYLOAD_MARKER;
299 *transport = coap_get_tcp_header_type_from_size(msgLength);
300 length = msgLength + coap_get_tcp_header_length_for_transport(*transport)
306 *transport = COAP_UDP;
309 coap_pdu_t *pdu = coap_new_pdu2(*transport, length);
313 OIC_LOG(ERROR, TAG, "malloc failed");
317 OIC_LOG_V(DEBUG, TAG, "transport type: %d, payload size: %zu",
318 *transport, info->payloadSize);
321 if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
323 coap_add_length(pdu, *transport, msgLength);
328 OIC_LOG_V(DEBUG, TAG, "msgID is %d", info->messageId);
329 uint16_t message_id = 0;
330 if (0 == info->messageId)
332 /* initialize message id */
333 prng((uint8_t * ) &message_id, sizeof(message_id));
335 OIC_LOG_V(DEBUG, TAG, "gen msg id=%d", message_id);
339 /* use saved message id */
340 message_id = info->messageId;
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);
345 pdu->transport_hdr->udp.type = info->type;
348 coap_add_code(pdu, *transport, code);
350 if (info->token && CA_EMPTY != code)
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);
356 int32_t ret = coap_add_token2(pdu, tokenLength, (unsigned char *)info->token, *transport);
359 OIC_LOG(ERROR, TAG, "can't add token");
364 if (CA_ADAPTER_GATT_BTLE != endpoint->adapter
366 && !CAIsSupportedCoAPOverTCP(endpoint->adapter)
370 // option list will be added in blockwise-transfer
377 for (coap_list_t *opt = options; opt; opt = opt->next)
379 OIC_LOG_V(DEBUG, TAG, "[%s] opt will be added.",
380 COAP_OPTION_DATA(*(coap_option *) opt->data));
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))
387 OIC_LOG(ERROR, TAG, "coap_add_option2 has failed");
388 coap_delete_pdu(pdu);
394 OIC_LOG_V(DEBUG, TAG, "[%d] pdu length after option", pdu->length);
396 if (NULL != info->payload && 0 < info->payloadSize)
398 OIC_LOG(DEBUG, TAG, "payload is added");
399 coap_add_data(pdu, info->payloadSize, (const unsigned char *) info->payload);
405 CAResult_t CAParseURI(const char *uriInfo, coap_list_t **optlist)
407 VERIFY_NON_NULL(uriInfo, TAG, "uriInfo");
408 VERIFY_NON_NULL(optlist, TAG, "optlist");
410 /* split arg into Uri-* options */
412 coap_split_uri((unsigned char *) uriInfo, strlen(uriInfo), &uri);
414 if (uri.port != COAP_DEFAULT_PORT)
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),
424 return CA_STATUS_INVALID_PARAM;
428 if (uri.path.s && uri.path.length)
430 CAResult_t ret = CAParseUriPartial(uri.path.s, uri.path.length,
431 COAP_OPTION_URI_PATH, optlist);
432 if (CA_STATUS_OK != ret)
434 OIC_LOG(ERROR, TAG, "CAParseUriPartial failed(uri path)");
439 if (uri.query.s && uri.query.length)
441 CAResult_t ret = CAParseUriPartial(uri.query.s, uri.query.length, COAP_OPTION_URI_QUERY,
443 if (CA_STATUS_OK != ret)
445 OIC_LOG(ERROR, TAG, "CAParseUriPartial failed(uri query)");
453 CAResult_t CAParseUriPartial(const unsigned char *str, size_t length, int target,
454 coap_list_t **optlist)
456 VERIFY_NON_NULL(optlist, TAG, "optlist");
458 if ((target != COAP_OPTION_URI_PATH) && (target != COAP_OPTION_URI_QUERY))
460 // should never occur. Log just in case.
461 OIC_LOG(DEBUG, TAG, "Unexpected URI component.");
462 return CA_NOT_SUPPORTED;
464 else if (str && length)
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);
477 int ret = coap_insert(optlist,
478 CACreateNewOptionNode(target, COAP_OPT_LENGTH(pBuf),
479 (char *)COAP_OPT_VALUE(pBuf)),
483 return CA_STATUS_INVALID_PARAM;
486 size_t optSize = COAP_OPT_SIZE(pBuf);
487 if ((prevIdx + optSize) < buflen)
496 OIC_LOG_V(ERROR, TAG, "Problem parsing URI : %d for %d", res, target);
497 return CA_STATUS_FAILED;
502 OIC_LOG(ERROR, TAG, "str or length is not available");
503 return CA_STATUS_FAILED;
509 CAResult_t CAParseHeadOption(uint32_t code, const CAInfo_t *info, coap_list_t **optlist)
512 VERIFY_NON_NULL_RET(info, TAG, "info", CA_STATUS_INVALID_PARAM);
514 OIC_LOG_V(DEBUG, TAG, "parse Head Opt: %d", info->numOptions);
518 OIC_LOG(ERROR, TAG, "optlist is null");
519 return CA_STATUS_INVALID_PARAM;
522 for (uint32_t i = 0; i < info->numOptions; i++)
524 if(!(info->options + i))
526 OIC_LOG(ERROR, TAG, "options is not available");
527 return CA_STATUS_FAILED;
530 uint32_t id = (info->options + i)->optionID;
531 if (COAP_OPTION_URI_PATH == id || COAP_OPTION_URI_QUERY == id)
533 OIC_LOG_V(DEBUG, TAG, "not Header Opt: %d", id);
537 OIC_LOG_V(DEBUG, TAG, "Head opt ID: %d", id);
538 OIC_LOG_V(DEBUG, TAG, "Head opt data: %s", (info->options + i)->optionData);
539 OIC_LOG_V(DEBUG, TAG, "Head opt length: %d", (info->options + i)->optionLength);
540 int ret = coap_insert(optlist,
541 CACreateNewOptionNode(id, (info->options + i)->optionLength,
542 (info->options + i)->optionData),
546 return CA_STATUS_INVALID_PARAM;
551 // insert one extra header with the payload format if applicable.
552 if (CA_FORMAT_UNDEFINED != info->payloadFormat)
554 CAParsePayloadFormatHeadOption(info->payloadFormat, COAP_OPTION_CONTENT_FORMAT, COAP_OPTION_CONTENT_VERSION, info->payloadVersion, optlist);
557 if (CA_FORMAT_UNDEFINED != info->acceptFormat)
559 CAParsePayloadFormatHeadOption(info->acceptFormat, COAP_OPTION_ACCEPT, info->acceptVersion, COAP_OPTION_ACCEPT_VERSION, optlist);
565 CAResult_t CAParsePayloadFormatHeadOption(CAPayloadFormat_t format, uint16_t formatOption,
566 uint16_t versionOption, uint16_t version, coap_list_t **optlist)
568 coap_list_t* encodeNode = NULL;
569 coap_list_t* versionNode = NULL;
570 uint8_t encodeBuf[CA_ENCODE_BUFFER_SIZE] = { 0 };
571 uint8_t versionBuf[CA_ENCODE_BUFFER_SIZE] = { 0 };
575 case CA_FORMAT_APPLICATION_CBOR:
576 encodeNode = CACreateNewOptionNode(formatOption,
577 coap_encode_var_bytes(encodeBuf,
578 (unsigned short) COAP_MEDIATYPE_APPLICATION_CBOR), (char *) encodeBuf);
580 case CA_FORMAT_APPLICATION_VND_OCF_CBOR:
581 encodeNode = CACreateNewOptionNode(formatOption,
582 coap_encode_var_bytes(encodeBuf,
583 (unsigned short) COAP_MEDIATYPE_APPLICATION_VND_OCF_CBOR),
585 // Include payload version information for this format.
586 versionNode = CACreateNewOptionNode(versionOption,
587 coap_encode_var_bytes(versionBuf, version), (char *) versionBuf);
590 OIC_LOG_V(ERROR, TAG, "Format option:[%d] not supported", format);
594 OIC_LOG(ERROR, TAG, "Format option not created");
595 return CA_STATUS_INVALID_PARAM;
597 int ret = coap_insert(optlist, encodeNode, CAOrderOpts);
600 coap_delete(encodeNode);
601 OIC_LOG(ERROR, TAG, "Format option not inserted in header");
602 if (CA_FORMAT_APPLICATION_VND_OCF_CBOR == format && versionNode)
604 coap_delete(versionNode);
606 return CA_STATUS_INVALID_PARAM;
609 if (CA_FORMAT_APPLICATION_VND_OCF_CBOR == format)
613 OIC_LOG(ERROR, TAG, "Version option not created");
614 coap_delete(encodeNode);
615 return CA_STATUS_INVALID_PARAM;
619 ret = coap_insert(optlist, versionNode, CAOrderOpts);
622 coap_delete(versionNode);
623 coap_delete(encodeNode);
624 OIC_LOG(ERROR, TAG, "Content version option not inserted in header");
625 return CA_STATUS_INVALID_PARAM;
632 coap_list_t *CACreateNewOptionNode(uint16_t key, uint32_t length, const char *data)
634 VERIFY_NON_NULL_RET(data, TAG, "data", NULL);
636 coap_option *option = coap_malloc(sizeof(coap_option) + length + 1);
639 OIC_LOG(ERROR, TAG, "Out of memory");
642 memset(option, 0, sizeof(coap_option) + length + 1);
644 COAP_OPTION_KEY(*option) = key;
646 coap_option_def_t* def = coap_opt_def(key);
647 if (NULL != def && coap_is_var_bytes(def))
649 if (length > def->max)
651 // make sure we shrink the value so it fits the coap option definition
652 // by truncating the value, disregard the leading bytes.
653 OIC_LOG_V(DEBUG, TAG, "Option [%d] data size [%d] shrunk to [%d]",
654 def->key, length, def->max);
655 data = &(data[length-def->max]);
658 // Shrink the encoding length to a minimum size for coap
659 // options that support variable length encoding.
660 COAP_OPTION_LENGTH(*option) = coap_encode_var_bytes(
661 COAP_OPTION_DATA(*option),
662 coap_decode_var_bytes((unsigned char *)data, length));
666 COAP_OPTION_LENGTH(*option) = length;
667 memcpy(COAP_OPTION_DATA(*option), data, length);
670 /* we can pass NULL here as delete function since option is released automatically */
671 coap_list_t *node = coap_new_listnode(option, NULL);
675 OIC_LOG(ERROR, TAG, "node is NULL");
683 int CAOrderOpts(void *a, void *b)
687 return a < b ? -1 : 1;
690 if (COAP_OPTION_KEY(*(coap_option *) a) < COAP_OPTION_KEY(*(coap_option * ) b))
695 return COAP_OPTION_KEY(*(coap_option *) a) == COAP_OPTION_KEY(*(coap_option * ) b);
698 uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter)
701 coap_opt_t *option = NULL;
703 while ((option = coap_option_next(&opt_iter)))
705 if (COAP_OPTION_URI_PATH != opt_iter.type && COAP_OPTION_URI_QUERY != opt_iter.type
706 && COAP_OPTION_BLOCK1 != opt_iter.type && COAP_OPTION_BLOCK2 != opt_iter.type
707 && COAP_OPTION_SIZE1 != opt_iter.type && COAP_OPTION_SIZE2 != opt_iter.type
708 && COAP_OPTION_CONTENT_FORMAT != opt_iter.type
709 && COAP_OPTION_ACCEPT != opt_iter.type
710 && COAP_OPTION_CONTENT_VERSION != opt_iter.type
711 && COAP_OPTION_ACCEPT_VERSION != opt_iter.type
712 && COAP_OPTION_URI_HOST != opt_iter.type && COAP_OPTION_URI_PORT != opt_iter.type
713 && COAP_OPTION_ETAG != opt_iter.type && COAP_OPTION_MAXAGE != opt_iter.type
714 && COAP_OPTION_PROXY_SCHEME != opt_iter.type)
723 CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
724 uint32_t *outCode, CAInfo_t *outInfo)
726 VERIFY_NON_NULL(pdu, TAG, "pdu");
727 VERIFY_NON_NULL(endpoint, TAG, "endpoint");
728 VERIFY_NON_NULL(outCode, TAG, "outCode");
729 VERIFY_NON_NULL(outInfo, TAG, "outInfo");
731 coap_transport_t transport;
733 if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
735 transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)pdu->transport_hdr)[0] >> 4);
740 transport = COAP_UDP;
743 coap_opt_iterator_t opt_iter;
744 coap_option_iterator_init2((coap_pdu_t *) pdu, &opt_iter, COAP_OPT_ALL, transport);
748 (*outCode) = (uint32_t) CA_RESPONSE_CODE(coap_get_code(pdu, transport));
751 // init HeaderOption list
752 uint32_t count = CAGetOptionCount(opt_iter);
753 memset(outInfo, 0, sizeof(*outInfo));
755 outInfo->numOptions = count;
758 if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
761 outInfo->type = CA_MSG_NONCONFIRM;
762 outInfo->payloadFormat = CA_FORMAT_UNDEFINED;
770 outInfo->type = pdu->transport_hdr->udp.type;
773 outInfo->messageId = pdu->transport_hdr->udp.id;
774 outInfo->payloadFormat = CA_FORMAT_UNDEFINED;
775 outInfo->acceptFormat = CA_FORMAT_UNDEFINED;
780 outInfo->options = (CAHeaderOption_t *) OICCalloc(count, sizeof(CAHeaderOption_t));
781 if (NULL == outInfo->options)
783 OIC_LOG(ERROR, TAG, "Out of memory");
784 return CA_MEMORY_ALLOC_FAILED;
788 coap_opt_t *option = NULL;
789 char optionResult[CA_MAX_URI_LENGTH] = {0};
791 uint32_t optionLength = 0;
792 bool isfirstsetflag = false;
793 bool isQueryBeingProcessed = false;
794 bool isProxyRequest = false;
796 while ((option = coap_option_next(&opt_iter)))
798 char buf[COAP_MAX_PDU_SIZE] = {0};
800 CAGetOptionData(opt_iter.type, (uint8_t *)(COAP_OPT_VALUE(option)),
801 COAP_OPT_LENGTH(option), (uint8_t *)buf, sizeof(buf));
804 OIC_LOG_V(DEBUG, TAG, "COAP URI element : %s", buf);
805 if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type)
807 if (false == isfirstsetflag)
809 isfirstsetflag = true;
810 optionResult[optionLength] = '/';
812 // Make sure there is enough room in the optionResult buffer
813 if ((optionLength + bufLength) < sizeof(optionResult))
815 memcpy(&optionResult[optionLength], buf, bufLength);
816 optionLength += bufLength;
825 if (COAP_OPTION_URI_PATH == opt_iter.type)
827 // Make sure there is enough room in the optionResult buffer
828 if (optionLength < sizeof(optionResult))
830 optionResult[optionLength] = '/';
838 else if (COAP_OPTION_URI_QUERY == opt_iter.type)
840 if (false == isQueryBeingProcessed)
842 // Make sure there is enough room in the optionResult buffer
843 if (optionLength < sizeof(optionResult))
845 optionResult[optionLength] = '?';
847 isQueryBeingProcessed = true;
856 // Make sure there is enough room in the optionResult buffer
857 if (optionLength < sizeof(optionResult))
859 optionResult[optionLength] = ';';
868 // Make sure there is enough room in the optionResult buffer
869 if ((optionLength + bufLength) < sizeof(optionResult))
871 memcpy(&optionResult[optionLength], buf, bufLength);
872 optionLength += bufLength;
880 else if (COAP_OPTION_BLOCK1 == opt_iter.type || COAP_OPTION_BLOCK2 == opt_iter.type
881 || COAP_OPTION_SIZE1 == opt_iter.type || COAP_OPTION_SIZE2 == opt_iter.type)
883 OIC_LOG_V(DEBUG, TAG, "option[%d] will be filtering", opt_iter.type);
885 else if (COAP_OPTION_CONTENT_FORMAT == opt_iter.type)
887 if (1 == COAP_OPT_LENGTH(option))
889 outInfo->payloadFormat = CAConvertFormat((uint8_t)buf[0]);
891 else if (2 == COAP_OPT_LENGTH(option))
893 outInfo->payloadFormat = CAConvertFormat(
894 coap_decode_var_bytes(COAP_OPT_VALUE(option), COAP_OPT_LENGTH(option)));
898 outInfo->payloadFormat = CA_FORMAT_UNSUPPORTED;
899 OIC_LOG_V(DEBUG, TAG, "option has an unsupported format");
902 else if (COAP_OPTION_CONTENT_VERSION == opt_iter.type)
904 if (2 == COAP_OPT_LENGTH(option))
906 outInfo->payloadVersion = coap_decode_var_bytes(COAP_OPT_VALUE(option), COAP_OPT_LENGTH(option));
910 OIC_LOG_V(DEBUG, TAG, "unsupported content version");
911 outInfo->payloadVersion = DEFAULT_CONTENT_VERSION_VALUE;
915 else if (COAP_OPTION_ACCEPT_VERSION == opt_iter.type)
917 if (2 == COAP_OPT_LENGTH(option))
919 outInfo->acceptVersion = coap_decode_var_bytes(COAP_OPT_VALUE(option), COAP_OPT_LENGTH(option));
923 OIC_LOG_V(DEBUG, TAG, "unsupported accept version");
924 outInfo->acceptVersion = DEFAULT_ACCEPT_VERSION_VALUE;
927 else if (COAP_OPTION_ACCEPT == opt_iter.type)
929 if (1 == COAP_OPT_LENGTH(option))
931 outInfo->acceptFormat = CAConvertFormat((uint8_t)buf[0]);
933 else if (2 == COAP_OPT_LENGTH(option))
935 outInfo->acceptFormat = CAConvertFormat(
936 coap_decode_var_bytes(COAP_OPT_VALUE(option), COAP_OPT_LENGTH(option)));
940 outInfo->acceptFormat = CA_FORMAT_UNSUPPORTED;
941 OIC_LOG_V(DEBUG, TAG, "option has an unsupported accept format");
944 else if (COAP_OPTION_URI_PORT == opt_iter.type ||
945 COAP_OPTION_URI_HOST == opt_iter.type ||
946 COAP_OPTION_ETAG == opt_iter.type ||
947 COAP_OPTION_MAXAGE == opt_iter.type ||
948 COAP_OPTION_PROXY_SCHEME== opt_iter.type)
950 OIC_LOG_V(INFO, TAG, "option[%d] has an unsupported format [%d]",
951 opt_iter.type, (uint8_t)buf[0]);
955 if (COAP_OPTION_PROXY_URI == opt_iter.type)
957 isProxyRequest = true;
961 if (bufLength <= sizeof(outInfo->options[0].optionData))
963 outInfo->options[idx].optionID = opt_iter.type;
964 outInfo->options[idx].optionLength = bufLength;
965 outInfo->options[idx].protocolID = CA_COAP_ID;
966 memcpy(outInfo->options[idx].optionData, buf, bufLength);
974 unsigned char* token = NULL;
975 unsigned int token_length = 0;
976 coap_get_token2(pdu->transport_hdr, transport, &token, &token_length);
979 if (token_length > 0)
981 OIC_LOG_V(DEBUG, TAG, "inside token length : %d", token_length);
982 outInfo->token = (char *) OICMalloc(token_length);
983 if (NULL == outInfo->token)
985 OIC_LOG(ERROR, TAG, "Out of memory");
986 OICFree(outInfo->options);
987 return CA_MEMORY_ALLOC_FAILED;
989 memcpy(outInfo->token, token, token_length);
992 outInfo->tokenLength = token_length;
997 if (coap_get_data(pdu, &dataSize, &data))
999 OIC_LOG(DEBUG, TAG, "inside pdu->data");
1000 outInfo->payload = (uint8_t *) OICMalloc(dataSize);
1001 if (NULL == outInfo->payload)
1003 OIC_LOG(ERROR, TAG, "Out of memory");
1004 OICFree(outInfo->options);
1005 OICFree(outInfo->token);
1006 return CA_MEMORY_ALLOC_FAILED;
1008 memcpy(outInfo->payload, pdu->data, dataSize);
1009 outInfo->payloadSize = dataSize;
1012 if (optionResult[0] != '\0')
1014 OIC_LOG_V(DEBUG, TAG, "URL length:%zu", strlen(optionResult));
1015 outInfo->resourceUri = OICStrdup(optionResult);
1016 if (!outInfo->resourceUri)
1018 OIC_LOG(ERROR, TAG, "Out of memory");
1019 OICFree(outInfo->options);
1020 OICFree(outInfo->token);
1021 return CA_MEMORY_ALLOC_FAILED;
1024 else if(isProxyRequest && g_chproxyUri[0] != '\0')
1027 * A request for Proxy will not have any uri element as per CoAP specs
1028 * and only COAP_OPTION_PROXY_URI will be present. Use preset proxy uri
1029 * for such requests.
1031 outInfo->resourceUri = OICStrdup(g_chproxyUri);
1032 if (!outInfo->resourceUri)
1034 OIC_LOG(ERROR, TAG, "Out of memory");
1035 OICFree(outInfo->options);
1036 OICFree(outInfo->token);
1037 return CA_MEMORY_ALLOC_FAILED;
1040 return CA_STATUS_OK;
1043 OIC_LOG(ERROR, TAG, "buffer too small");
1044 OICFree(outInfo->options);
1045 return CA_STATUS_FAILED;
1048 CAResult_t CAGetTokenFromPDU(const coap_hdr_transport_t *pdu_hdr,
1050 const CAEndpoint_t *endpoint)
1052 VERIFY_NON_NULL(pdu_hdr, TAG, "pdu_hdr");
1053 VERIFY_NON_NULL(outInfo, TAG, "outInfo");
1054 VERIFY_NON_NULL(endpoint, TAG, "endpoint");
1056 coap_transport_t transport = COAP_UDP;
1058 if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
1060 transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)pdu_hdr)[0] >> 4);
1064 unsigned char* token = NULL;
1065 unsigned int token_length = 0;
1066 coap_get_token2(pdu_hdr, transport, &token, &token_length);
1069 if (token_length > 0)
1071 OIC_LOG_V(DEBUG, TAG, "token len:%d", token_length);
1072 outInfo->token = (char *) OICMalloc(token_length);
1073 if (NULL == outInfo->token)
1075 OIC_LOG(ERROR, TAG, "Out of memory");
1076 return CA_MEMORY_ALLOC_FAILED;
1078 memcpy(outInfo->token, token, token_length);
1081 outInfo->tokenLength = token_length;
1083 return CA_STATUS_OK;
1086 CAResult_t CAGenerateTokenInternal(CAToken_t *token, uint8_t tokenLength)
1088 VERIFY_NON_NULL(token, TAG, "token");
1090 if ((tokenLength > CA_MAX_TOKEN_LEN) || (0 == tokenLength))
1092 OIC_LOG(ERROR, TAG, "invalid token length");
1093 return CA_STATUS_INVALID_PARAM;
1096 // memory allocation
1097 char *temp = (char *) OICCalloc(tokenLength, sizeof(char));
1100 OIC_LOG(ERROR, TAG, "Out of memory");
1101 return CA_MEMORY_ALLOC_FAILED;
1104 if (!OCGetRandomBytes((uint8_t *)temp, tokenLength))
1106 OIC_LOG(ERROR, TAG, "Failed to generate random token");
1107 return CA_STATUS_FAILED;
1113 OIC_LOG_V(DEBUG, TAG, "token len:%d, token:", tokenLength);
1114 OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *)(*token), tokenLength);
1116 return CA_STATUS_OK;
1119 void CADestroyTokenInternal(CAToken_t token)
1124 uint32_t CAGetOptionData(uint16_t key, const uint8_t *data, uint32_t len,
1125 uint8_t *option, uint32_t buflen)
1129 OIC_LOG(ERROR, TAG, "buflen 0");
1135 OIC_LOG(ERROR, TAG, "option buffer too small");
1139 coap_option_def_t* def = coap_opt_def(key);
1140 if (NULL != def && coap_is_var_bytes(def) && 0 == len)
1142 // A 0 length option is permitted in CoAP but the
1143 // rest or the stack is unaware of variable byte encoding
1144 // should remain that way so a 0 byte of length 1 is inserted.
1150 memcpy(option, data, len);
1157 CAMessageType_t CAGetMessageTypeFromPduBinaryData(const void *pdu, uint32_t size)
1159 VERIFY_NON_NULL_RET(pdu, TAG, "pdu", CA_MSG_NONCONFIRM);
1161 // pdu minimum size is 4 byte.
1162 if (size < CA_PDU_MIN_SIZE)
1164 OIC_LOG(ERROR, TAG, "min size");
1165 return CA_MSG_NONCONFIRM;
1168 coap_hdr_t *hdr = (coap_hdr_t *) pdu;
1170 return (CAMessageType_t) hdr->type;
1173 uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size)
1175 VERIFY_NON_NULL_RET(pdu, TAG, "pdu", 0);
1177 // pdu minimum size is 4 byte.
1178 if (size < CA_PDU_MIN_SIZE)
1180 OIC_LOG(ERROR, TAG, "min size");
1184 coap_hdr_t *hdr = (coap_hdr_t *) pdu;
1189 CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size)
1191 VERIFY_NON_NULL_RET(pdu, TAG, "pdu", CA_NOT_FOUND);
1193 // pdu minimum size is 4 byte.
1194 if (size < CA_PDU_MIN_SIZE)
1196 OIC_LOG(ERROR, TAG, "min size");
1197 return CA_NOT_FOUND;
1200 coap_hdr_t *hdr = (coap_hdr_t *) pdu;
1202 return (CAResponseResult_t) CA_RESPONSE_CODE(hdr->code);
1205 CAPayloadFormat_t CAConvertFormat(uint16_t format)
1209 case COAP_MEDIATYPE_TEXT_PLAIN:
1210 return CA_FORMAT_TEXT_PLAIN;
1211 case COAP_MEDIATYPE_APPLICATION_LINK_FORMAT:
1212 return CA_FORMAT_APPLICATION_LINK_FORMAT;
1213 case COAP_MEDIATYPE_APPLICATION_XML:
1214 return CA_FORMAT_APPLICATION_XML;
1215 case COAP_MEDIATYPE_APPLICATION_OCTET_STREAM:
1216 return CA_FORMAT_APPLICATION_OCTET_STREAM;
1217 case COAP_MEDIATYPE_APPLICATION_RDF_XML:
1218 return CA_FORMAT_APPLICATION_RDF_XML;
1219 case COAP_MEDIATYPE_APPLICATION_EXI:
1220 return CA_FORMAT_APPLICATION_EXI;
1221 case COAP_MEDIATYPE_APPLICATION_JSON:
1222 return CA_FORMAT_APPLICATION_JSON;
1223 case COAP_MEDIATYPE_APPLICATION_CBOR:
1224 return CA_FORMAT_APPLICATION_CBOR;
1225 case COAP_MEDIATYPE_APPLICATION_VND_OCF_CBOR:
1226 return CA_FORMAT_APPLICATION_VND_OCF_CBOR;
1228 return CA_FORMAT_UNSUPPORTED;
1233 bool CAIsSupportedBlockwiseTransfer(CATransportAdapter_t adapter)
1235 OIC_LOG_V(INFO, TAG, "adapter value is %d", adapter);
1236 if (CA_ADAPTER_IP & adapter || CA_ADAPTER_NFC & adapter
1237 || CA_DEFAULT_ADAPTER == adapter)
1246 bool CAIsSupportedCoAPOverTCP(CATransportAdapter_t adapter)
1248 OIC_LOG_V(INFO, TAG, "adapter value is %d", adapter);
1249 if (CA_ADAPTER_GATT_BTLE & adapter || CA_ADAPTER_RFCOMM_BTEDR & adapter
1250 || CA_ADAPTER_TCP & adapter || CA_DEFAULT_ADAPTER == adapter)