-/******************************************************************\r
- *\r
- * Copyright 2014 Samsung Electronics All Rights Reserved.\r
- *\r
- *\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- *\r
- ******************************************************************/\r
-\r
-#include <stdio.h>\r
-#include <stdlib.h>\r
-#include <string.h>\r
-\r
-\r
-#include "caprotocolmessage.h"\r
-#include "logger.h"\r
-#include "oic_malloc.h"\r
-\r
-#define TAG "CA"\r
-\r
-#define CA_MAX_TOKEN_LEN (8)\r
-#define CA_FLAGS_BLOCK 0x01\r
-#define CA_BUFSIZE 128\r
-#define CA_COAP_MESSAGE_CON 0\r
-\r
-#include <time.h>\r
-\r
-\r
-uint32_t CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo,\r
- char *outUri)\r
-{\r
- OIC_LOG(DEBUG, TAG, "CAGetRequestInfoFromPdu IN");\r
-\r
- if (NULL == pdu)\r
- return 0;\r
-\r
- uint32_t code = CA_NOT_FOUND;\r
- CAGetRequestPDUInfo(pdu, &code, &(outReqInfo->info), outUri);\r
- outReqInfo->method = code;\r
- OIC_LOG(DEBUG, TAG, "CAGetRequestInfoFromPdu OUT");\r
- return 1;\r
-}\r
-\r
-uint32_t CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,\r
- char *outUri)\r
-{\r
- OIC_LOG(DEBUG, TAG, "CAGetResponseInfoFromPdu IN");\r
- if (NULL == pdu)\r
- return 0;\r
-\r
- uint32_t code = CA_NOT_FOUND;\r
- CAGetRequestPDUInfo(pdu, &code, &(outResInfo->info), outUri);\r
- outResInfo->result = code;\r
- OIC_LOG(DEBUG, TAG, "CAGetResponseInfoFromPdu OUT");\r
- return 1;\r
-}\r
-\r
-coap_pdu_t *CAGeneratePdu(const char *uri, const uint32_t code, const CAInfo_t info)\r
-{\r
- OIC_LOG(DEBUG, TAG, "CAGeneratePdu IN");\r
-\r
- coap_pdu_t *pdu;\r
- char *coapUri = NULL;\r
- uint32_t coapHeaderLength = 12;\r
- uint32_t length;\r
- coap_list_t *optlist = NULL;\r
-\r
- if (NULL == uri)\r
- return NULL;\r
-\r
- length = strlen(uri);\r
- if (CA_MAX_URI_LENGTH < length)\r
- {\r
- OIC_LOG(DEBUG, TAG, "check URI length..");\r
- return NULL;\r
- }\r
-\r
- coapUri = (char *) OICMalloc(length + coapHeaderLength + 1);\r
- if (coapUri == NULL)\r
- {\r
- OIC_LOG(DEBUG, TAG, "CAGeneratePdu, Memory allocation failed !");\r
- return NULL;\r
- }\r
- memset(coapUri, 0, length + coapHeaderLength + 1);\r
-\r
- if (NULL != coapUri)\r
- {\r
- memcpy(coapUri, "coap://[::]/", coapHeaderLength);\r
- memcpy(coapUri + coapHeaderLength, uri, length);\r
-\r
- // parsing options in URI\r
- CAParseURI(coapUri, &optlist);\r
-\r
- // parsing options in HeadOption\r
- CAParseHeadOption(code, info, &optlist);\r
-\r
- OICFree(coapUri);\r
- }\r
-\r
- if (NULL != info.payload) // payload is include in request / response\r
- {\r
- if (!(pdu = CACreatePDUforRequestWithPayload((code_t) code, optlist, info.payload, info)))\r
- return NULL;\r
- }\r
- else // payload is not include in request / response\r
- {\r
- if (!(pdu = CACreatePDUforRequest((code_t) code, optlist, info)))\r
- return NULL;\r
- }\r
-\r
- // pdu print method : coap_show_pdu(pdu);\r
- OIC_LOG(DEBUG, TAG, "CAGeneratePdu OUT");\r
- return pdu;\r
-}\r
-\r
-coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode)\r
-{\r
- OIC_LOG(DEBUG, TAG, "CAParsePDU IN");\r
- coap_pdu_t *outpdu = coap_new_pdu();\r
-\r
- coap_pdu_parse((unsigned char *) data, length, outpdu);\r
- (*outCode) = (uint32_t) outpdu->hdr->code;\r
- OIC_LOG(DEBUG, TAG, "CAParsePDU OUT");\r
- return outpdu;\r
-}\r
-\r
-coap_pdu_t *CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *options,\r
- const char *payload, const CAInfo_t info)\r
-{\r
- OIC_LOG(DEBUG, TAG, "CACreatePDUforRequestWithPayload IN");\r
-\r
- coap_pdu_t *pdu;\r
- coap_list_t *opt;\r
-\r
- uint32_t CAFlags = 0;\r
- coap_block_t CABlock =\r
- { .num = 0, .m = 0, .szx = 6 };\r
-\r
- if (!(pdu = coap_new_pdu()))\r
- return NULL;\r
-\r
- unsigned short message_id;\r
-\r
- if (info.messageId == 0)\r
- {\r
- /* initialize message id */\r
- prng((unsigned char * )&message_id, sizeof(unsigned short));\r
- ++message_id;\r
-\r
- OIC_LOG_V(DEBUG, TAG, "generate the message id(%d)", message_id);\r
- }\r
- else\r
- {\r
- /* use saved message id */\r
- message_id = info.messageId;\r
- }\r
-\r
- pdu->hdr->type = info.type;\r
- pdu->hdr->id = htons(message_id);\r
- pdu->hdr->code = code;\r
-\r
- if (info.token)\r
- {\r
- pdu->hdr->token_length = CA_MAX_TOKEN_LEN;\r
- if (!coap_add_token(pdu, CA_MAX_TOKEN_LEN, (unsigned char *) info.token))\r
- {\r
- OIC_LOG(DEBUG, TAG, "cannot add token to request");\r
- }\r
- }\r
- for (opt = options; opt; opt = opt->next)\r
- {\r
- OIC_LOG_V(DEBUG, TAG, "[%s] opt will be added.", COAP_OPTION_DATA(*(coap_option * )opt->data));\r
- coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option * )opt->data),\r
- COAP_OPTION_LENGTH(*(coap_option * )opt->data),\r
- COAP_OPTION_DATA(*(coap_option * )opt->data));\r
- }\r
-\r
- if (NULL != payload)\r
- {\r
- uint32_t len = strlen(payload);\r
- if ((CAFlags & CA_FLAGS_BLOCK) == 0)\r
- {\r
- OIC_LOG_V(DEBUG, TAG, "coap_add_data, payload: %s", payload);\r
- coap_add_data(pdu, len, (const unsigned char *) payload);\r
- }\r
- else\r
- {\r
- OIC_LOG_V(DEBUG, TAG, "coap_add_block, payload: %s", payload);\r
- coap_add_block(pdu, len, (const unsigned char *) payload, CABlock.num, CABlock.szx);\r
- }\r
- }\r
- OIC_LOG(DEBUG, TAG, "CACreatePDUforRequestWithPayload OUT");\r
- return pdu;\r
-}\r
-\r
-coap_pdu_t *CACreatePDUforRequest(const code_t code, coap_list_t *options,\r
- const CAInfo_t info)\r
-{\r
- OIC_LOG(DEBUG, TAG, "CACreatePDUforRequest IN");\r
-\r
- coap_pdu_t *pdu;\r
- coap_list_t *opt;\r
-\r
- if (!(pdu = coap_new_pdu()))\r
- {\r
- OIC_LOG(DEBUG, TAG, "Out of memory");\r
- return NULL;\r
- }\r
-\r
- unsigned short message_id;\r
-\r
- if (info.messageId == 0)\r
- {\r
- /* initialize message id */\r
- prng((unsigned char * )&message_id, sizeof(unsigned short));\r
- ++message_id;\r
-\r
- OIC_LOG_V(DEBUG, TAG, "generate the message id(%d)", message_id);\r
- }\r
- else\r
- {\r
- /* use saved message id */\r
- message_id = info.messageId;\r
- }\r
-\r
- pdu->hdr->type = info.type;\r
- pdu->hdr->id = htons(message_id);\r
- pdu->hdr->code = code;\r
-\r
- OIC_LOG_V(DEBUG, TAG, "token info : %s, %d", info.token, strlen(info.token));\r
- pdu->hdr->token_length = CA_MAX_TOKEN_LEN;\r
-\r
- if (!coap_add_token(pdu, CA_MAX_TOKEN_LEN, (unsigned char *) info.token))\r
- {\r
- OIC_LOG(DEBUG, TAG, "cannot add token to request");\r
- }\r
-\r
- for (opt = options; opt; opt = opt->next)\r
- {\r
- coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option * )opt->data),\r
- COAP_OPTION_LENGTH(*(coap_option * )opt->data),\r
- COAP_OPTION_DATA(*(coap_option * )opt->data));\r
- }\r
- OIC_LOG(DEBUG, TAG, "CACreatePDUforRequest OUT");\r
- return pdu;\r
-}\r
-\r
-void CAParseURI(const char *uriInfo, coap_list_t **optlist)\r
-{\r
- OIC_LOG(DEBUG, TAG, "CAParseURI IN");\r
-\r
- unsigned char portbuf[2];\r
- unsigned char _buf[CA_BUFSIZE];\r
- unsigned char *buf = _buf;\r
- coap_uri_t uri;\r
- size_t buflen;\r
- uint32_t res;\r
-\r
- OIC_LOG_V(DEBUG, TAG, "url : %s", uriInfo);\r
-\r
- /* split arg into Uri-* options */\r
- coap_split_uri((unsigned char *) uriInfo, strlen(uriInfo), &uri);\r
-\r
- if (uri.port != COAP_DEFAULT_PORT)\r
- {\r
- coap_insert(optlist,\r
- CACreateNewOptionNode(COAP_OPTION_URI_PORT,\r
- coap_encode_var_bytes(portbuf, uri.port), portbuf),\r
- CAOrderOpts);\r
- }\r
-\r
- if (uri.path.length)\r
- {\r
- buflen = CA_BUFSIZE;\r
- res = coap_split_path(uri.path.s, uri.path.length, buf, &buflen);\r
-\r
- while (res--)\r
- {\r
- coap_insert(optlist,\r
- CACreateNewOptionNode(COAP_OPTION_URI_PATH, COAP_OPT_LENGTH(buf),\r
- COAP_OPT_VALUE(buf)), CAOrderOpts);\r
- buf += COAP_OPT_SIZE(buf);\r
- }\r
- }\r
-\r
- if (uri.query.length)\r
- {\r
- buflen = CA_BUFSIZE;\r
- buf = _buf;\r
- res = coap_split_query(uri.query.s, uri.query.length, buf, &buflen);\r
-\r
- while (res--)\r
- {\r
- coap_insert(optlist,\r
- CACreateNewOptionNode(COAP_OPTION_URI_QUERY, COAP_OPT_LENGTH(buf),\r
- COAP_OPT_VALUE(buf)), CAOrderOpts);\r
-\r
- buf += COAP_OPT_SIZE(buf);\r
- }\r
- }\r
- OIC_LOG(DEBUG, TAG, "CAParseURI OUT");\r
-}\r
-\r
-void CAParseHeadOption(const uint32_t code, const CAInfo_t info, coap_list_t **optlist)\r
-{\r
- OIC_LOG(DEBUG, TAG, "CAParseHeadOption IN");\r
- OIC_LOG_V(DEBUG, TAG, "start parse Head Option : %d", info.numOptions);\r
-\r
- uint32_t i;\r
- for (i = 0; i < info.numOptions; i++)\r
- {\r
- uint32_t id = info.options[i].optionID;\r
- if (COAP_OPTION_URI_PATH == id || COAP_OPTION_URI_QUERY == id)\r
- {\r
- OIC_LOG_V(DEBUG, TAG, "it is not Header Option : %d", id);\r
- }\r
- else\r
- {\r
- OIC_LOG_V(DEBUG, TAG, "Head Option ID: %d", info.options[i].optionID);\r
- OIC_LOG_V(DEBUG, TAG, "Head Option data: %s", info.options[i].optionData);\r
- OIC_LOG_V(DEBUG, TAG, "Head Option length: %d", info.options[i].optionLength);\r
-\r
- coap_insert(optlist,\r
- CACreateNewOptionNode(info.options[i].optionID,\r
- info.options[i].optionLength,\r
- info.options[i].optionData), CAOrderOpts);\r
- }\r
- }\r
- OIC_LOG(DEBUG, TAG, "CAParseHeadOption OUT");\r
-}\r
-\r
-coap_list_t *CACreateNewOptionNode(const uint16_t key, const uint32_t length,\r
- const uint8_t *data)\r
-{\r
- OIC_LOG(DEBUG, TAG, "CACreateNewOptionNode IN");\r
- coap_option *option;\r
- coap_list_t *node;\r
-\r
- option = coap_malloc(sizeof(coap_option) + length);\r
- if (!option)\r
- {\r
- OIC_LOG(DEBUG, TAG, "Out of memory");\r
- return NULL;\r
- }\r
- memset(option, 0, sizeof(coap_option) + length);\r
-\r
- COAP_OPTION_KEY(*option) = key;\r
- COAP_OPTION_LENGTH(*option) = length;\r
- memcpy(COAP_OPTION_DATA(*option), data, length);\r
-\r
- /* we can pass NULL here as delete function since option is released automatically */\r
- node = coap_new_listnode(option, NULL);\r
-\r
- if (!node)\r
- {\r
- OIC_LOG(DEBUG, TAG, "coap_new_listnode returns NULL");\r
- coap_free(option);\r
- return NULL;\r
- }\r
- //coap_free(option);\r
- OIC_LOG(DEBUG, TAG, "CACreateNewOptionNode OUT");\r
- return node;\r
-}\r
-\r
-int CAOrderOpts(void *a, void *b)\r
-{\r
- OIC_LOG(DEBUG, TAG, "CAOrderOpts IN");\r
- if (!a || !b)\r
- {\r
- return a < b ? -1 : 1;\r
- }\r
-\r
- if (COAP_OPTION_KEY(*(coap_option *)a) < COAP_OPTION_KEY(*(coap_option * )b))\r
- {\r
- return -1;\r
- }\r
- OIC_LOG(DEBUG, TAG, "CAOrderOpts OUT");\r
- return COAP_OPTION_KEY(*(coap_option *)a) == COAP_OPTION_KEY(*(coap_option * )b);\r
-}\r
-\r
-uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter)\r
-{\r
- OIC_LOG(DEBUG, TAG, "CAGetOptionCount IN");\r
- uint32_t count = 0;\r
- coap_opt_t *option;\r
-\r
- while ((option = coap_option_next(&opt_iter)))\r
- {\r
- if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type)\r
- {\r
-\r
- }\r
- else\r
- {\r
- count++;\r
- }\r
- }\r
- OIC_LOG(DEBUG, TAG, "CAGetOptionCount OUT");\r
- return count;\r
-}\r
-\r
-void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo,\r
- char *outUri)\r
-{\r
- OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo IN");\r
- char buf[COAP_MAX_PDU_SIZE]; /* need some space for output creation */\r
- uint32_t encode = 0;\r
- coap_opt_iterator_t opt_iter;\r
- coap_opt_t *option;\r
- char optionResult[CA_MAX_URI_LENGTH] =\r
- { 0, };\r
- uint32_t count = 0, idx = 0;\r
- uint32_t optionLength = 0;\r
- uint32_t isfirstsetflag = 0;\r
-\r
- coap_option_iterator_init((coap_pdu_t *) pdu, &opt_iter, COAP_OPT_ALL);\r
-\r
- memset(optionResult, 0, sizeof(optionResult));\r
-\r
- // set code\r
- (*outCode) = (uint32_t) pdu->hdr->code;\r
-\r
- // init HeaderOption list\r
- count = CAGetOptionCount(opt_iter);\r
-\r
- memset(outInfo, 0, sizeof(CAInfo_t));\r
- outInfo->numOptions = count;\r
- // set type\r
- outInfo->type = pdu->hdr->type;\r
-\r
- // set message id\r
- outInfo->messageId = ntohs(pdu->hdr->id);\r
-\r
- if (count > 0)\r
- {\r
- outInfo->options = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * count);\r
- if (outInfo->options == NULL)\r
- {\r
- OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo, Memory allocation failed !");\r
- return;\r
- }\r
- memset(outInfo->options, 0, sizeof(CAHeaderOption_t) * count);\r
- }\r
-\r
- while ((option = coap_option_next(&opt_iter)))\r
- {\r
-\r
- if (CAGetOptionData((uint8_t *)(COAP_OPT_VALUE(option)),\r
- COAP_OPT_LENGTH(option), (uint8_t *)buf, sizeof(buf),\r
- encode))\r
- {\r
- OIC_LOG_V(DEBUG, TAG, "COAP URI element : %s", buf);\r
- if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type)\r
- {\r
- if (0 == isfirstsetflag)\r
- {\r
- isfirstsetflag = 1;\r
- memcpy(optionResult + optionLength, "/", 1);\r
- optionLength++;\r
- memcpy(optionResult + optionLength, buf, strlen((const char *) buf));\r
- optionLength += strlen((const char *) buf);\r
- }\r
- else\r
- {\r
- if (COAP_OPTION_URI_PATH == opt_iter.type)\r
- {\r
- memcpy(optionResult + optionLength, "/", 1);\r
- optionLength++;\r
- }\r
- else if (COAP_OPTION_URI_QUERY == opt_iter.type)\r
- {\r
- memcpy(optionResult + optionLength, "?", 1);\r
- optionLength++;\r
- }\r
- memcpy(optionResult + optionLength, buf, strlen((const char *) buf));\r
- optionLength += strlen((const char *) buf);\r
- }\r
- }\r
- else\r
- {\r
- if (idx < count)\r
- {\r
- uint32_t length = (uint32_t) strlen((const char *) buf);\r
-\r
- if (length <= CA_MAX_HEADER_OPTION_DATA_LENGTH)\r
- {\r
- outInfo->options[idx].optionID = opt_iter.type;\r
- outInfo->options[idx].optionLength = length;\r
- outInfo->options[idx].protocolID = CA_COAP_ID;\r
- memcpy(outInfo->options[idx].optionData, buf, length);\r
- idx++;\r
- }\r
- }\r
- }\r
- }\r
- }\r
-\r
- // set token data\r
- if (pdu->hdr->token_length > 0)\r
- {\r
- OIC_LOG(DEBUG, TAG, "inside pdu->hdr->token_length");\r
- outInfo->token = (char *) OICMalloc(CA_MAX_TOKEN_LEN);\r
- if (outInfo->token == NULL)\r
- {\r
- OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo, Memory allocation failed !");\r
- OICFree(outInfo->options);\r
- return;\r
- }\r
- memcpy(outInfo->token, pdu->hdr->token, CA_MAX_TOKEN_LEN);\r
- }\r
-\r
- // set payload data\r
- if (NULL != pdu->data)\r
- {\r
- OIC_LOG(DEBUG, TAG, "inside pdu->data");\r
- outInfo->payload = (char *) OICMalloc(strlen((const char *) pdu->data) + 1);\r
- if (outInfo->payload == NULL)\r
- {\r
- OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo, Memory allocation failed !");\r
- OICFree(outInfo->options);\r
- OICFree(outInfo->token);\r
- return;\r
- }\r
- memcpy(outInfo->payload, pdu->data, strlen((const char *) pdu->data) + 1);\r
- }\r
-\r
-\r
- memcpy(outUri, optionResult, strlen(optionResult));\r
- OIC_LOG_V(DEBUG, TAG, "made URL : %s\n", optionResult);\r
- OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo OUT");\r
-\r
-}\r
-\r
-CAResult_t CAGenerateTokenInternal(CAToken_t *token)\r
-{\r
- OIC_LOG(DEBUG, TAG, "CAGenerateTokenInternal IN");\r
- if (token == NULL)\r
- {\r
- return CA_STATUS_FAILED;\r
- }\r
-\r
- // memory allocation\r
- char *temp = (char *) OICMalloc(sizeof(char) * (CA_MAX_TOKEN_LEN + 1));\r
- if (temp == NULL)\r
- {\r
- OIC_LOG(DEBUG, TAG, "CAGenerateTokenInternal, Memory allocation failed !");\r
- return CA_MEMORY_ALLOC_FAILED;\r
- }\r
- memset(temp, 0, sizeof(char) * (CA_MAX_TOKEN_LEN + 1));\r
-\r
- // set random byte\r
- uint32_t index;\r
-\r
- srand(time(NULL));\r
- for (index = 0; index < CA_MAX_TOKEN_LEN; index++)\r
- {\r
- // use valid characters\r
- temp[index] = (rand() % 94 + 33) & 0xFF;\r
- }\r
-\r
- temp[index] = '\0';\r
- // save token\r
- *token = temp;\r
-\r
- OIC_LOG_V(DEBUG, TAG, "generate the token(%s)!!", *token);\r
- OIC_LOG(DEBUG, TAG, "CAGenerateTokenInternal OUT");\r
- return CA_STATUS_OK;\r
-}\r
-\r
-void CADestroyTokenInternal(CAToken_t token)\r
-{\r
- OIC_LOG(DEBUG, TAG, "CADestroyTokenInternal IN");\r
- if (token != NULL)\r
- {\r
- OIC_LOG_V(DEBUG, TAG, "destroy the token(%s)!!", token);\r
-\r
- OICFree(token);\r
- }\r
- OIC_LOG(DEBUG, TAG, "CADestroyTokenInternal OUT");\r
-}\r
-\r
-void CADeinitialize(CAInfo_t *info)\r
-{\r
- OIC_LOG(DEBUG, TAG, "CADeinitialize IN");\r
-\r
- if (NULL != info)\r
- {\r
- if (NULL != info->options)\r
- {\r
- OIC_LOG(DEBUG, TAG, "free options in CAInfo");\r
- OICFree(info->options);\r
- }\r
-\r
- if (NULL != info->token)\r
- {\r
- OIC_LOG(DEBUG, TAG, "free token in CAInfo");\r
- OICFree(info->token);\r
- }\r
-\r
- if (NULL != info->payload)\r
- {\r
- OIC_LOG(DEBUG, TAG, "free payload in CAInfo");\r
- OICFree(info->payload);\r
- }\r
- }\r
- OIC_LOG(DEBUG, TAG, "CADeinitialize OUT");\r
-}\r
-\r
-uint32_t CAGetOptionData(const uint8_t *data, uint32_t len, uint8_t *result,\r
- uint32_t buflen, uint32_t encode_always)\r
-{\r
- const unsigned char hex[] = "0123456789ABCDEF";\r
- uint32_t cnt = 0;\r
- assert(data || len == 0);\r
-\r
- if (buflen == 0 || len == 0)\r
- return 0;\r
-\r
- if (data == NULL)\r
- {\r
- return 0;\r
- }\r
-\r
- while (len)\r
- {\r
- if (!encode_always)\r
- {\r
- if (cnt == buflen)\r
- break;\r
- *result++ = *data;\r
- ++cnt;\r
- }\r
- else\r
- {\r
- if (cnt + 4 < buflen)\r
- {\r
- *result++ = '\\';\r
- *result++ = 'x';\r
- *result++ = hex[(*data & 0xf0) >> 4];\r
- *result++ = hex[*data & 0x0f];\r
- cnt += 4;\r
- }\r
- else\r
- break;\r
- }\r
-\r
- ++data;\r
- --len;\r
- }\r
-\r
- *result = '\0';\r
- return cnt;\r
-}\r
-\r
-CAMessageType_t CAGetMessageTypeFromPduBinaryData(const void *pdu, uint32_t size)\r
-{\r
- // pdu minimum size is 4 byte.\r
- if (size < 4)\r
- return CA_MSG_NONCONFIRM;\r
-\r
- coap_hdr_t *hdr = (coap_hdr_t *) pdu;\r
-\r
- return (CAMessageType_t) hdr->type;\r
-}\r
-\r
-uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size)\r
-{\r
- // pdu minimum size is 4 byte.\r
- if (size < 4)\r
- return 0;\r
-\r
- coap_hdr_t *hdr = (coap_hdr_t *) pdu;\r
-\r
- return ntohs(hdr->id);\r
-}\r
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+// Defining _BSD_SOURCE or _DEFAULT_SOURCE causes header files to expose
+// definitions that may otherwise be skipped. Skipping can cause implicit
+// declaration warnings and/or bugs and subtle problems in code execution.
+// For glibc information on feature test macros,
+// Refer http://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html
+//
+// This file requires #define use due to random() and srandom()
+// For details on compatibility and glibc support,
+// Refer http://www.gnu.org/software/libc/manual/html_node/BSD-Random.html
+#define _DEFAULT_SOURCE
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdbool.h>
+#ifdef HAVE_TIME_H
+#include <time.h>
+#endif
+
+#include "caprotocolmessage.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+
+// ARM GCC compiler doesnt define srandom function.
+#if defined(ARDUINO) && !defined(ARDUINO_ARCH_SAM)
+#define HAVE_SRANDOM 1
+#endif
+
+#define TAG "CA_PRTCL_MSG"
+
+/**
+ * @def VERIFY_NON_NULL_RET
+ * @brief Macro to verify the validity of input argument
+ */
+#define VERIFY_NON_NULL_RET(arg, log_tag, log_message,ret) \
+ if (NULL == arg ){ \
+ OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
+ return ret; \
+ }
+
+#define CA_BUFSIZE (128)
+#define CA_PDU_MIN_SIZE (4)
+#define CA_PORT_BUFFER_SIZE (4)
+
+static const char COAP_URI_HEADER[] = "coap://[::]/";
+
+static unsigned int SEED = 0;
+
+CAResult_t CAGetRequestInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
+ CARequestInfo_t *outReqInfo)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+
+ if (NULL == pdu || NULL == outReqInfo)
+ {
+ OIC_LOG(ERROR, TAG, "parameter is null");
+ return CA_STATUS_INVALID_PARAM;
+ }
+
+ uint32_t code = CA_NOT_FOUND;
+ CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &(outReqInfo->info));
+ outReqInfo->method = code;
+
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return ret;
+}
+
+CAResult_t CAGetResponseInfoFromPDU(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,
+ const CAEndpoint_t *endpoint)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+
+ if (NULL == pdu || NULL == outResInfo)
+ {
+ OIC_LOG(ERROR, TAG, "parameter is null");
+ return CA_STATUS_INVALID_PARAM;
+ }
+
+ uint32_t code = CA_NOT_FOUND;
+ CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &(outResInfo->info));
+ outResInfo->result = code;
+
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return ret;
+}
+
+CAResult_t CAGetErrorInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
+ CAErrorInfo_t *errorInfo)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+
+ if (!pdu)
+ {
+ OIC_LOG(ERROR, TAG, "parameter is null");
+ return CA_STATUS_INVALID_PARAM;
+ }
+
+ uint32_t code = 0;
+ CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &errorInfo->info);
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return ret;
+}
+
+coap_pdu_t *CAGeneratePDU(uint32_t code, const CAInfo_t *info, const CAEndpoint_t *endpoint)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+
+ VERIFY_NON_NULL_RET(info, TAG, "info", NULL);
+ VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", NULL);
+
+ coap_pdu_t *pdu = NULL;
+
+ // RESET have to use only 4byte (empty message)
+ // and ACKNOWLEDGE can use empty message when code is empty.
+ if (CA_MSG_RESET == info->type || (CA_EMPTY == code && CA_MSG_ACKNOWLEDGE == info->type))
+ {
+ OIC_LOG(DEBUG, TAG, "code is empty");
+ if (!(pdu = CAGeneratePDUImpl((code_t) code, info, endpoint, NULL)))
+ {
+ OIC_LOG(ERROR, TAG, "pdu NULL");
+ return NULL;
+ }
+ }
+ else
+ {
+ coap_list_t *optlist = NULL;
+
+ if (CA_MSG_ACKNOWLEDGE != info->type)
+ {
+ const char *uri = info->resourceUri;
+ if (NULL == uri)
+ {
+ OIC_LOG(ERROR, TAG, "uri NULL");
+ return NULL;
+ }
+
+ uint32_t length = strlen(uri);
+ if (CA_MAX_URI_LENGTH < length)
+ {
+ OIC_LOG(ERROR, TAG, "URI len err");
+ return NULL;
+ }
+
+ uint32_t uriLength = length + sizeof(COAP_URI_HEADER);
+ char *coapUri = (char *) OICCalloc(1, uriLength);
+ if (NULL == coapUri)
+ {
+ OIC_LOG(ERROR, TAG, "out of memory");
+ return NULL;
+ }
+ OICStrcat(coapUri, uriLength, COAP_URI_HEADER);
+ OICStrcat(coapUri, uriLength, uri);
+
+ // parsing options in URI
+ CAResult_t res = CAParseURI(coapUri, &optlist);
+ if (CA_STATUS_OK != res)
+ {
+ if (optlist)
+ {
+ coap_delete_list(optlist);
+ }
+ OICFree(coapUri);
+ return NULL;
+ }
+
+ OICFree(coapUri);
+ }
+ // parsing options in HeadOption
+ CAResult_t ret = CAParseHeadOption(code, info, &optlist);
+ if (CA_STATUS_OK != ret)
+ {
+ coap_delete_list(optlist);
+ return NULL;
+ }
+
+ pdu = CAGeneratePDUImpl((code_t) code, info, endpoint, optlist);
+ if (NULL == pdu)
+ {
+ OIC_LOG(ERROR, TAG, "pdu NULL");
+ coap_delete_list(optlist);
+ return NULL;
+ }
+
+ // free option list
+ coap_delete_list(optlist);
+ }
+
+ // pdu print method : coap_show_pdu(pdu);
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return pdu;
+}
+
+coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode,
+ const CAEndpoint_t *endpoint)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+
+ if (NULL == data)
+ {
+ OIC_LOG(ERROR, TAG, "data is null");
+ return NULL;
+ }
+
+ coap_transport_type transport;
+#ifdef TCP_ADAPTER
+ if (CA_ADAPTER_TCP == endpoint->adapter)
+ {
+ transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)data)[0] >> 4);
+ }
+ else
+#endif
+ {
+ transport = coap_udp;
+ }
+
+ coap_pdu_t *outpdu = coap_new_pdu(transport, length);
+ if (NULL == outpdu)
+ {
+ OIC_LOG(ERROR, TAG, "outpdu is null");
+ return NULL;
+ }
+
+ OIC_LOG_V(DEBUG, TAG, "pdu parse-transport type : %d", transport);
+
+ int ret = coap_pdu_parse((unsigned char *) data, length, outpdu, transport);
+ OIC_LOG_V(DEBUG, TAG, "pdu parse ret: %d", ret);
+ if (0 >= ret)
+ {
+ OIC_LOG(ERROR, TAG, "pdu parse failed");
+ coap_delete_pdu(outpdu);
+ return NULL;
+ }
+
+#ifdef TCP_ADAPTER
+ if (CA_ADAPTER_TCP == endpoint->adapter)
+ {
+ OIC_LOG(INFO, TAG, "there is no version info in coap header");
+ }
+ else
+#endif
+ {
+ if (outpdu->hdr->coap_hdr_udp_t.version != COAP_DEFAULT_VERSION)
+ {
+ OIC_LOG_V(ERROR, TAG, "coap version is not available : %d",
+ outpdu->hdr->coap_hdr_udp_t.version);
+ coap_delete_pdu(outpdu);
+ return NULL;
+ }
+ if (outpdu->hdr->coap_hdr_udp_t.token_length > CA_MAX_TOKEN_LEN)
+ {
+ OIC_LOG_V(ERROR, TAG, "token length has been exceed : %d",
+ outpdu->hdr->coap_hdr_udp_t.token_length);
+ coap_delete_pdu(outpdu);
+ return NULL;
+ }
+ }
+
+ if (outCode)
+ {
+ (*outCode) = (uint32_t) CA_RESPONSE_CODE(coap_get_code(outpdu, transport));
+ }
+
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return outpdu;
+}
+
+coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
+ const CAEndpoint_t *endpoint, coap_list_t *options)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ VERIFY_NON_NULL_RET(info, TAG, "info", NULL);
+ VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", NULL);
+
+ coap_transport_type transport;
+ unsigned int length = COAP_MAX_PDU_SIZE;
+#ifdef TCP_ADAPTER
+ unsigned int headerLength = 0;
+ if (CA_ADAPTER_TCP == endpoint->adapter)
+ {
+ if (options)
+ {
+ for (coap_list_t *opt = options; opt; opt = opt->next)
+ {
+ headerLength += COAP_OPTION_LENGTH(*(coap_option *) opt->data) + 1;
+ }
+ }
+
+ if (info->payloadSize > 0)
+ {
+ headerLength = headerLength + info->payloadSize + 1;
+ }
+ transport = coap_get_tcp_header_type_from_size(headerLength);
+ length = headerLength + coap_get_tcp_header_length_for_transport(transport)
+ + info->tokenLength;
+ }
+ else
+#endif
+ {
+ transport = coap_udp;
+ }
+
+ coap_pdu_t *pdu = coap_new_pdu(transport, length);
+
+ if (NULL == pdu)
+ {
+ OIC_LOG(ERROR, TAG, "malloc failed");
+ return NULL;
+ }
+
+ OIC_LOG_V(DEBUG, TAG, "transport type: %d, payload size: %d",
+ transport, info->payloadSize);
+
+#ifdef TCP_ADAPTER
+ if (CA_ADAPTER_TCP == endpoint->adapter)
+ {
+ coap_add_length(pdu, transport, headerLength);
+ }
+ else
+#endif
+ {
+ OIC_LOG_V(DEBUG, TAG, "msgID is %d", info->messageId);
+ uint16_t message_id;
+ if (0 == info->messageId)
+ {
+ /* initialize message id */
+ prng((uint8_t * ) &message_id, sizeof(message_id));
+
+ OIC_LOG_V(DEBUG, TAG, "gen msg id=%d", message_id);
+ }
+ else
+ {
+ /* use saved message id */
+ message_id = info->messageId;
+ }
+ pdu->hdr->coap_hdr_udp_t.id = message_id;
+ OIC_LOG_V(DEBUG, TAG, "messageId in pdu is %d, %d", message_id, pdu->hdr->coap_hdr_udp_t.id);
+
+ pdu->hdr->coap_hdr_udp_t.type = info->type;
+ }
+
+ coap_add_code(pdu, transport, code);
+
+ if (info->token && CA_EMPTY != code)
+ {
+ uint32_t tokenLength = info->tokenLength;
+ OIC_LOG_V(DEBUG, TAG, "token info token length: %d, token :", tokenLength);
+ OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *)info->token, tokenLength);
+
+ int32_t ret = coap_add_token(pdu, tokenLength, (unsigned char *)info->token, transport);
+ if (0 == ret)
+ {
+ OIC_LOG(ERROR, TAG, "can't add token");
+ }
+ }
+
+ if (options)
+ {
+ for (coap_list_t *opt = options; opt; opt = opt->next)
+ {
+ OIC_LOG_V(DEBUG, TAG, "[%s] opt will be added.",
+ COAP_OPTION_DATA(*(coap_option *) opt->data));
+
+ OIC_LOG_V(DEBUG, TAG, "[%d] pdu length", pdu->length);
+ coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
+ COAP_OPTION_LENGTH(*(coap_option *) opt->data),
+ COAP_OPTION_DATA(*(coap_option *) opt->data), transport);
+ }
+ }
+
+ OIC_LOG_V(DEBUG, TAG, "[%d] pdu length after option", pdu->length);
+
+ bool enabledPayload = false;
+#ifndef WITH_BWT
+ enabledPayload = true;
+#endif
+
+ if (enabledPayload || CA_ADAPTER_GATT_BTLE == endpoint->adapter
+#ifdef TCP_ADAPTER
+ || CA_ADAPTER_TCP == endpoint->adapter
+#endif
+ )
+ {
+ if (NULL != info->payload && 0 < info->payloadSize)
+ {
+ OIC_LOG(DEBUG, TAG, "payload is added");
+ coap_add_data(pdu, info->payloadSize, (const unsigned char *) info->payload);
+ }
+ }
+
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return pdu;
+}
+
+CAResult_t CAParseURI(const char *uriInfo, coap_list_t **optlist)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+
+ if (NULL == uriInfo)
+ {
+ OIC_LOG(ERROR, TAG, "uriInfo is null");
+ return CA_STATUS_INVALID_PARAM;
+ }
+
+ OIC_LOG_V(DEBUG, TAG, "url : %s", uriInfo);
+
+ if (NULL == optlist)
+ {
+ OIC_LOG(ERROR, TAG, "optlist is null");
+ return CA_STATUS_INVALID_PARAM;
+ }
+
+ /* split arg into Uri-* options */
+ coap_uri_t uri;
+ coap_split_uri((unsigned char *) uriInfo, strlen(uriInfo), &uri);
+
+ if (uri.port != COAP_DEFAULT_PORT)
+ {
+ unsigned char portbuf[CA_PORT_BUFFER_SIZE] = { 0 };
+ int ret = coap_insert(optlist,
+ CACreateNewOptionNode(COAP_OPTION_URI_PORT,
+ coap_encode_var_bytes(portbuf, uri.port),
+ (char *)portbuf),
+ CAOrderOpts);
+ if (ret <= 0)
+ {
+ return CA_STATUS_INVALID_PARAM;
+ }
+ }
+
+ if (uri.path.s && uri.path.length)
+ {
+ CAResult_t ret = CAParseUriPartial(uri.path.s, uri.path.length,
+ COAP_OPTION_URI_PATH, optlist);
+ if (CA_STATUS_OK != ret)
+ {
+ OIC_LOG(ERROR, TAG, "CAParseUriPartial failed(uri path)");
+ return ret;
+ }
+ }
+
+ if (uri.query.s && uri.query.length)
+ {
+ CAResult_t ret = CAParseUriPartial(uri.query.s, uri.query.length, COAP_OPTION_URI_QUERY,
+ optlist);
+ if (CA_STATUS_OK != ret)
+ {
+ OIC_LOG(ERROR, TAG, "CAParseUriPartial failed(uri query)");
+ return ret;
+ }
+ }
+
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return CA_STATUS_OK;
+}
+
+CAResult_t CAParseUriPartial(const unsigned char *str, size_t length, int target,
+ coap_list_t **optlist)
+{
+ if (!optlist)
+ {
+ OIC_LOG(ERROR, TAG, "optlist is null");
+ return CA_STATUS_INVALID_PARAM;
+ }
+
+ if ((target != COAP_OPTION_URI_PATH) && (target != COAP_OPTION_URI_QUERY))
+ {
+ // should never occur. Log just in case.
+ OIC_LOG(DEBUG, TAG, "Unexpected URI component.");
+ return CA_NOT_SUPPORTED;
+ }
+ else if (str && length)
+ {
+ unsigned char uriBuffer[CA_BUFSIZE] = { 0 };
+ unsigned char *pBuf = uriBuffer;
+ size_t buflen = sizeof(uriBuffer);
+ int res = (target == COAP_OPTION_URI_PATH) ? coap_split_path(str, length, pBuf, &buflen) :
+ coap_split_query(str, length, pBuf, &buflen);
+
+ if (res > 0)
+ {
+ size_t prevIdx = 0;
+ while (res--)
+ {
+ int ret = coap_insert(optlist,
+ CACreateNewOptionNode(target, COAP_OPT_LENGTH(pBuf),
+ (char *)COAP_OPT_VALUE(pBuf)),
+ CAOrderOpts);
+ if (ret <= 0)
+ {
+ return CA_STATUS_INVALID_PARAM;
+ }
+
+ size_t optSize = COAP_OPT_SIZE(pBuf);
+ if ((prevIdx + optSize) < buflen)
+ {
+ pBuf += optSize;
+ prevIdx += optSize;
+ }
+ }
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, TAG, "Problem parsing URI : %d for %d", res, target);
+ return CA_STATUS_FAILED;
+ }
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "str or length is not available");
+ return CA_STATUS_FAILED;
+ }
+
+ return CA_STATUS_OK;
+}
+
+CAResult_t CAParseHeadOption(uint32_t code, const CAInfo_t *info, coap_list_t **optlist)
+{
+ (void)code;
+ OIC_LOG(DEBUG, TAG, "IN");
+ VERIFY_NON_NULL_RET(info, TAG, "info is NULL", CA_STATUS_INVALID_PARAM);
+
+ OIC_LOG_V(DEBUG, TAG, "parse Head Opt: %d", info->numOptions);
+
+ if (!optlist)
+ {
+ OIC_LOG(ERROR, TAG, "optlist is null");
+ return CA_STATUS_INVALID_PARAM;
+ }
+
+ for (uint32_t i = 0; i < info->numOptions; i++)
+ {
+ if(!(info->options + i))
+ {
+ OIC_LOG(ERROR, TAG, "options is not available");
+ return CA_STATUS_FAILED;
+ }
+
+ uint32_t id = (info->options + i)->optionID;
+ if (COAP_OPTION_URI_PATH == id || COAP_OPTION_URI_QUERY == id)
+ {
+ OIC_LOG_V(DEBUG, TAG, "not Header Opt: %d", id);
+ }
+ else
+ {
+ OIC_LOG_V(DEBUG, TAG, "Head opt ID: %d", id);
+ OIC_LOG_V(DEBUG, TAG, "Head opt data: %s", (info->options + i)->optionData);
+ OIC_LOG_V(DEBUG, TAG, "Head opt length: %d", (info->options + i)->optionLength);
+ int ret = coap_insert(optlist,
+ CACreateNewOptionNode(id, (info->options + i)->optionLength,
+ (info->options + i)->optionData),
+ CAOrderOpts);
+ if (ret <= 0)
+ {
+ return CA_STATUS_INVALID_PARAM;
+ }
+ }
+ }
+
+ // insert one extra header with the payload format if applicable.
+ if (CA_FORMAT_UNDEFINED != info->payloadFormat)
+ {
+ coap_list_t* node = NULL;
+ uint8_t buf[3] = {0};
+ switch (info->payloadFormat) {
+ case CA_FORMAT_APPLICATION_CBOR:
+ node = CACreateNewOptionNode(
+ COAP_OPTION_CONTENT_FORMAT,
+ coap_encode_var_bytes(buf, (uint16_t)COAP_MEDIATYPE_APPLICATION_CBOR),
+ (char *)buf);
+ break;
+ default:
+ OIC_LOG_V(ERROR, TAG, "format option:[%d] not supported", info->payloadFormat);
+ }
+ if (!node)
+ {
+ OIC_LOG(ERROR, TAG, "format option not created");
+ return CA_STATUS_INVALID_PARAM;
+ }
+ int ret = coap_insert(optlist, node, CAOrderOpts);
+ if (ret <= 0)
+ {
+ coap_delete(node);
+ OIC_LOG(ERROR, TAG, "format option not inserted in header");
+ return CA_STATUS_INVALID_PARAM;
+ }
+ }
+ if (CA_FORMAT_UNDEFINED != info->acceptFormat)
+ {
+ coap_list_t* node = NULL;
+ uint8_t buf[3] = {0};
+ switch (info->acceptFormat) {
+ case CA_FORMAT_APPLICATION_CBOR:
+ node = CACreateNewOptionNode(
+ COAP_OPTION_ACCEPT,
+ coap_encode_var_bytes(buf, (uint16_t)COAP_MEDIATYPE_APPLICATION_CBOR),
+ (char *)buf);
+ break;
+ default:
+ OIC_LOG_V(ERROR, TAG, "format option:[%d] not supported", info->acceptFormat);
+ }
+ if (!node)
+ {
+ OIC_LOG(ERROR, TAG, "format option not created");
+ return CA_STATUS_INVALID_PARAM;
+ }
+ int ret = coap_insert(optlist, node, CAOrderOpts);
+ if (ret <= 0)
+ {
+ coap_delete(node);
+ OIC_LOG(ERROR, TAG, "format option not inserted in header");
+ return CA_STATUS_INVALID_PARAM;
+ }
+ }
+
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return CA_STATUS_OK;
+}
+
+coap_list_t *CACreateNewOptionNode(uint16_t key, uint32_t length, const char *data)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+
+ if (!data)
+ {
+ OIC_LOG(ERROR, TAG, "invalid pointer parameter");
+ return NULL;
+ }
+
+ coap_option *option = coap_malloc(sizeof(coap_option) + length + 1);
+ if (!option)
+ {
+ OIC_LOG(ERROR, TAG, "Out of memory");
+ return NULL;
+ }
+ memset(option, 0, sizeof(coap_option) + length + 1);
+
+ COAP_OPTION_KEY(*option) = key;
+
+ coap_option_def_t* def = coap_opt_def(key);
+ if (NULL != def && coap_is_var_bytes(def))
+ {
+ if (length > def->max)
+ {
+ // make sure we shrink the value so it fits the coap option definition
+ // by truncating the value, disregard the leading bytes.
+ OIC_LOG_V(DEBUG, TAG, "Option [%d] data size [%d] shrunk to [%d]",
+ def->key, length, def->max);
+ data = &(data[length-def->max]);
+ length = def->max;
+ }
+ // Shrink the encoding length to a minimum size for coap
+ // options that support variable length encoding.
+ COAP_OPTION_LENGTH(*option) = coap_encode_var_bytes(
+ COAP_OPTION_DATA(*option),
+ coap_decode_var_bytes((unsigned char *)data, length));
+ }
+ else
+ {
+ COAP_OPTION_LENGTH(*option) = length;
+ memcpy(COAP_OPTION_DATA(*option), data, length);
+ }
+
+ /* we can pass NULL here as delete function since option is released automatically */
+ coap_list_t *node = coap_new_listnode(option, NULL);
+
+ if (!node)
+ {
+ OIC_LOG(ERROR, TAG, "node is NULL");
+ coap_free(option);
+ return NULL;
+ }
+
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return node;
+}
+
+int CAOrderOpts(void *a, void *b)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ if (!a || !b)
+ {
+ return a < b ? -1 : 1;
+ }
+
+ if (COAP_OPTION_KEY(*(coap_option *) a) < COAP_OPTION_KEY(*(coap_option * ) b))
+ {
+ return -1;
+ }
+
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return COAP_OPTION_KEY(*(coap_option *) a) == COAP_OPTION_KEY(*(coap_option * ) b);
+}
+
+uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ uint32_t count = 0;
+ coap_opt_t *option;
+
+ while ((option = coap_option_next(&opt_iter)))
+ {
+ if (COAP_OPTION_URI_PATH != opt_iter.type && COAP_OPTION_URI_QUERY != opt_iter.type
+ && COAP_OPTION_BLOCK1 != opt_iter.type && COAP_OPTION_BLOCK2 != opt_iter.type
+ && COAP_OPTION_SIZE1 != opt_iter.type && COAP_OPTION_SIZE2 != opt_iter.type
+ && COAP_OPTION_CONTENT_FORMAT != opt_iter.type
+ && COAP_OPTION_ACCEPT != opt_iter.type)
+ {
+ count++;
+ }
+ }
+
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return count;
+}
+
+CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
+ uint32_t *outCode, CAInfo_t *outInfo)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+
+ if (!pdu || !outCode || !outInfo)
+ {
+ OIC_LOG(ERROR, TAG, "NULL pointer param");
+ return CA_STATUS_INVALID_PARAM;
+ }
+
+ coap_transport_type transport;
+#ifdef TCP_ADAPTER
+ if (CA_ADAPTER_TCP == endpoint->adapter)
+ {
+ transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)pdu->hdr)[0] >> 4);
+ }
+ else
+#endif
+ {
+ transport = coap_udp;
+ }
+
+ coap_opt_iterator_t opt_iter;
+ coap_option_iterator_init((coap_pdu_t *) pdu, &opt_iter, COAP_OPT_ALL, transport);
+
+ if (outCode)
+ {
+ (*outCode) = (uint32_t) CA_RESPONSE_CODE(coap_get_code(pdu, transport));
+ }
+
+ // init HeaderOption list
+ uint32_t count = CAGetOptionCount(opt_iter);
+ memset(outInfo, 0, sizeof(*outInfo));
+
+ outInfo->numOptions = count;
+
+#ifdef TCP_ADAPTER
+ if (CA_ADAPTER_TCP == endpoint->adapter)
+ {
+ // set type
+ outInfo->type = CA_MSG_NONCONFIRM;
+ outInfo->payloadFormat = CA_FORMAT_UNDEFINED;
+ }
+ else
+#endif
+ {
+ // set type
+ outInfo->type = pdu->hdr->coap_hdr_udp_t.type;
+
+ // set message id
+ outInfo->messageId = pdu->hdr->coap_hdr_udp_t.id;
+ outInfo->payloadFormat = CA_FORMAT_UNDEFINED;
+ outInfo->acceptFormat = CA_FORMAT_UNDEFINED;
+ }
+
+ if (count > 0)
+ {
+ outInfo->options = (CAHeaderOption_t *) OICCalloc(count, sizeof(CAHeaderOption_t));
+ if (NULL == outInfo->options)
+ {
+ OIC_LOG(ERROR, TAG, "Out of memory");
+ return CA_MEMORY_ALLOC_FAILED;
+ }
+ }
+
+ coap_opt_t *option;
+ char optionResult[CA_MAX_URI_LENGTH] = {0};
+ uint32_t idx = 0;
+ uint32_t optionLength = 0;
+ bool isfirstsetflag = false;
+ bool isQueryBeingProcessed = false;
+
+ while ((option = coap_option_next(&opt_iter)))
+ {
+ char buf[COAP_MAX_PDU_SIZE] = {0};
+ uint32_t bufLength =
+ CAGetOptionData(opt_iter.type, (uint8_t *)(COAP_OPT_VALUE(option)),
+ COAP_OPT_LENGTH(option), (uint8_t *)buf, sizeof(buf));
+ if (bufLength)
+ {
+ OIC_LOG_V(DEBUG, TAG, "COAP URI element : %s", buf);
+ if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type)
+ {
+ if (false == isfirstsetflag)
+ {
+ isfirstsetflag = true;
+ optionResult[optionLength] = '/';
+ optionLength++;
+ // Make sure there is enough room in the optionResult buffer
+ if ((optionLength + bufLength) < sizeof(optionResult))
+ {
+ memcpy(&optionResult[optionLength], buf, bufLength);
+ optionLength += bufLength;
+ }
+ else
+ {
+ goto exit;
+ }
+ }
+ else
+ {
+ if (COAP_OPTION_URI_PATH == opt_iter.type)
+ {
+ // Make sure there is enough room in the optionResult buffer
+ if (optionLength < sizeof(optionResult))
+ {
+ optionResult[optionLength] = '/';
+ optionLength++;
+ }
+ else
+ {
+ goto exit;
+ }
+ }
+ else if (COAP_OPTION_URI_QUERY == opt_iter.type)
+ {
+ if (false == isQueryBeingProcessed)
+ {
+ // Make sure there is enough room in the optionResult buffer
+ if (optionLength < sizeof(optionResult))
+ {
+ optionResult[optionLength] = '?';
+ optionLength++;
+ isQueryBeingProcessed = true;
+ }
+ else
+ {
+ goto exit;
+ }
+ }
+ else
+ {
+ // Make sure there is enough room in the optionResult buffer
+ if (optionLength < sizeof(optionResult))
+ {
+ optionResult[optionLength] = ';';
+ optionLength++;
+ }
+ else
+ {
+ goto exit;
+ }
+ }
+ }
+ // Make sure there is enough room in the optionResult buffer
+ if ((optionLength + bufLength) < sizeof(optionResult))
+ {
+ memcpy(&optionResult[optionLength], buf, bufLength);
+ optionLength += bufLength;
+ }
+ else
+ {
+ goto exit;
+ }
+ }
+ }
+ else if (COAP_OPTION_BLOCK1 == opt_iter.type || COAP_OPTION_BLOCK2 == opt_iter.type
+ || COAP_OPTION_SIZE1 == opt_iter.type || COAP_OPTION_SIZE2 == opt_iter.type)
+ {
+ OIC_LOG_V(DEBUG, TAG, "option[%d] will be filtering", opt_iter.type);
+ }
+ else if (COAP_OPTION_CONTENT_FORMAT == opt_iter.type)
+ {
+ if (1 == COAP_OPT_LENGTH(option))
+ {
+ outInfo->payloadFormat = CAConvertFormat((uint8_t)buf[0]);
+ }
+ else
+ {
+ outInfo->payloadFormat = CA_FORMAT_UNSUPPORTED;
+ OIC_LOG_V(DEBUG, TAG, "option[%d] has an unsupported format [%d]",
+ opt_iter.type, (uint8_t)buf[0]);
+ }
+ }
+ else if (COAP_OPTION_ACCEPT == opt_iter.type)
+ {
+ if (1 == COAP_OPT_LENGTH(option))
+ {
+ outInfo->acceptFormat = CAConvertFormat((uint8_t)buf[0]);
+ }
+ else
+ {
+ outInfo->acceptFormat = CA_FORMAT_UNSUPPORTED;
+ }
+ OIC_LOG_V(DEBUG, TAG, "option[%d] has an unsupported format [%d]",
+ opt_iter.type, (uint8_t)buf[0]);
+ }
+ else
+ {
+ if (idx < count)
+ {
+ if (bufLength <= sizeof(outInfo->options[0].optionData))
+ {
+ outInfo->options[idx].optionID = opt_iter.type;
+ outInfo->options[idx].optionLength = bufLength;
+ outInfo->options[idx].protocolID = CA_COAP_ID;
+ memcpy(outInfo->options[idx].optionData, buf, bufLength);
+ idx++;
+ }
+ }
+ }
+ }
+ }
+
+ unsigned char* token = NULL;
+ unsigned int token_length = 0;
+ coap_get_token(pdu->hdr, transport, &token, &token_length);
+
+ // set token data
+ if (token_length > 0)
+ {
+ OIC_LOG_V(DEBUG, TAG, "inside token length : %d", token_length);
+ outInfo->token = (char *) OICMalloc(token_length);
+ if (NULL == outInfo->token)
+ {
+ OIC_LOG(ERROR, TAG, "Out of memory");
+ OICFree(outInfo->options);
+ return CA_MEMORY_ALLOC_FAILED;
+ }
+ memcpy(outInfo->token, token, token_length);
+ }
+
+ outInfo->tokenLength = token_length;
+
+ // set payload data
+ size_t dataSize;
+ uint8_t *data;
+ if (coap_get_data(pdu, &dataSize, &data))
+ {
+ OIC_LOG(DEBUG, TAG, "inside pdu->data");
+ outInfo->payload = (uint8_t *) OICMalloc(dataSize);
+ if (NULL == outInfo->payload)
+ {
+ OIC_LOG(ERROR, TAG, "Out of memory");
+ OICFree(outInfo->options);
+ OICFree(outInfo->token);
+ return CA_MEMORY_ALLOC_FAILED;
+ }
+ memcpy(outInfo->payload, pdu->data, dataSize);
+ outInfo->payloadSize = dataSize;
+ }
+
+ if (optionResult[0] != '\0')
+ {
+ OIC_LOG_V(DEBUG, TAG, "URL length:%d", strlen(optionResult));
+ outInfo->resourceUri = OICStrdup(optionResult);
+ if (!outInfo->resourceUri)
+ {
+ OIC_LOG(ERROR, TAG, "Out of memory");
+ OICFree(outInfo->options);
+ OICFree(outInfo->token);
+ return CA_MEMORY_ALLOC_FAILED;
+ }
+ }
+
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return CA_STATUS_OK;
+
+exit:
+ OIC_LOG(ERROR, TAG, "buffer too small");
+ OICFree(outInfo->options);
+ return CA_STATUS_FAILED;
+}
+
+CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo,
+ const CAEndpoint_t *endpoint)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ if (NULL == pdu_hdr)
+ {
+ OIC_LOG(ERROR, TAG, "pdu_hdr is null");
+ return CA_STATUS_INVALID_PARAM;
+ }
+
+ if (NULL == outInfo)
+ {
+ OIC_LOG(ERROR, TAG, "outInfo is null");
+ return CA_STATUS_INVALID_PARAM;
+ }
+
+ coap_transport_type transport;
+#ifdef TCP_ADAPTER
+ if (CA_ADAPTER_TCP == endpoint->adapter)
+ {
+ transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)pdu_hdr)[0] >> 4);
+ }
+ else
+#endif
+ {
+ transport = coap_udp;
+ }
+
+ unsigned char* token = NULL;
+ unsigned int token_length = 0;
+ coap_get_token(pdu_hdr, transport, &token, &token_length);
+
+ // set token data
+ if (token_length > 0)
+ {
+ OIC_LOG_V(DEBUG, TAG, "token len:%d", token_length);
+ outInfo->token = (char *) OICMalloc(token_length);
+ if (NULL == outInfo->token)
+ {
+ OIC_LOG(ERROR, TAG, "Out of memory");
+ return CA_MEMORY_ALLOC_FAILED;
+ }
+ memcpy(outInfo->token, token, token_length);
+ }
+
+ outInfo->tokenLength = token_length;
+
+ OIC_LOG(DEBUG, TAG, "OUT");
+
+ return CA_STATUS_OK;
+}
+
+CAResult_t CAGenerateTokenInternal(CAToken_t *token, uint8_t tokenLength)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+
+ if (!token)
+ {
+ OIC_LOG(ERROR, TAG, "invalid token pointer");
+ return CA_STATUS_INVALID_PARAM;
+ }
+
+ if ((tokenLength > CA_MAX_TOKEN_LEN) || (0 == tokenLength))
+ {
+ OIC_LOG(ERROR, TAG, "invalid token length");
+ return CA_STATUS_INVALID_PARAM;
+ }
+
+ if (SEED == 0)
+ {
+#ifdef ARDUINO
+ SEED = now();
+#else
+ SEED = time(NULL);
+#endif
+ if (SEED == (unsigned int)((time_t)-1))
+ {
+ OIC_LOG(ERROR, TAG, "seed is not made");
+ SEED = 0;
+ return CA_STATUS_FAILED;
+ }
+#if HAVE_SRANDOM
+ srandom(SEED);
+#else
+ srand(SEED);
+#endif
+ }
+
+ // memory allocation
+ char *temp = (char *) OICCalloc(tokenLength, sizeof(char));
+ if (NULL == temp)
+ {
+ OIC_LOG(ERROR, TAG, "Out of memory");
+ return CA_MEMORY_ALLOC_FAILED;
+ }
+
+ // set random byte
+ for (uint8_t index = 0; index < tokenLength; index++)
+ {
+ // use valid characters
+#ifdef ARDUINO
+ temp[index] = rand() & 0x00FF;
+#else
+ temp[index] = random() & 0x00FF;
+#endif
+ }
+
+ // save token
+ *token = temp;
+
+ OIC_LOG_V(DEBUG, TAG, "token len:%d, token:", tokenLength);
+ OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *)(*token), tokenLength);
+
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return CA_STATUS_OK;
+}
+
+void CADestroyTokenInternal(CAToken_t token)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ OICFree(token);
+ OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CADestroyInfo(CAInfo_t *info)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+
+ if (NULL != info)
+ {
+ OIC_LOG(DEBUG, TAG, "free options");
+ OICFree(info->options);
+
+ OIC_LOG(DEBUG, TAG, "free token");
+ OICFree(info->token);
+
+ OIC_LOG(DEBUG, TAG, "free payload");
+ OICFree(info->payload);
+ }
+
+ OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+uint32_t CAGetOptionData(uint16_t key, const uint8_t *data, uint32_t len,
+ uint8_t *option, uint32_t buflen)
+{
+ if (0 == buflen)
+ {
+ OIC_LOG(ERROR, TAG, "buflen 0");
+ return 0;
+ }
+
+ if (buflen <= len)
+ {
+ OIC_LOG(ERROR, TAG, "option buffer too small");
+ return 0;
+ }
+
+ coap_option_def_t* def = coap_opt_def(key);
+ if(NULL != def && coap_is_var_bytes(def) && 0 == len) {
+ // A 0 length option is permitted in CoAP but the
+ // rest or the stack is unaware of variable byte encoding
+ // should remain that way so a 0 byte of length 1 is inserted.
+ len = 1;
+ option[0]=0;
+ } else {
+ memcpy(option, data, len);
+ option[len] = '\0';
+ }
+
+ return len;
+}
+
+CAMessageType_t CAGetMessageTypeFromPduBinaryData(const void *pdu, uint32_t size)
+{
+ if (NULL == pdu)
+ {
+ OIC_LOG(ERROR, TAG, "pdu is null");
+ return CA_MSG_NONCONFIRM;
+ }
+
+ // pdu minimum size is 4 byte.
+ if (size < CA_PDU_MIN_SIZE)
+ {
+ OIC_LOG(ERROR, TAG, "min size");
+ return CA_MSG_NONCONFIRM;
+ }
+
+ coap_hdr_t *hdr = (coap_hdr_t *) pdu;
+
+ return (CAMessageType_t) hdr->coap_hdr_udp_t.type;
+}
+
+uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size)
+{
+ if (NULL == pdu)
+ {
+ OIC_LOG(ERROR, TAG, "pdu is null");
+ return 0;
+ }
+
+ // pdu minimum size is 4 byte.
+ if (size < CA_PDU_MIN_SIZE)
+ {
+ OIC_LOG(ERROR, TAG, "min size");
+ return 0;
+ }
+
+ coap_hdr_t *hdr = (coap_hdr_t *) pdu;
+
+ return hdr->coap_hdr_udp_t.id;
+}
+
+CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size)
+{
+ if (NULL == pdu)
+ {
+ OIC_LOG(ERROR, TAG, "pdu is null");
+ return CA_NOT_FOUND;
+ }
+
+ // pdu minimum size is 4 byte.
+ if (size < CA_PDU_MIN_SIZE)
+ {
+ OIC_LOG(ERROR, TAG, "min size");
+ return CA_NOT_FOUND;
+ }
+
+ coap_hdr_t *hdr = (coap_hdr_t *) pdu;
+
+ return (CAResponseResult_t) CA_RESPONSE_CODE(hdr->coap_hdr_udp_t.code);
+}
+
+CAPayloadFormat_t CAConvertFormat(uint8_t format)
+{
+ switch (format)
+ {
+ case COAP_MEDIATYPE_TEXT_PLAIN:
+ return CA_FORMAT_TEXT_PLAIN;
+ case COAP_MEDIATYPE_APPLICATION_LINK_FORMAT:
+ return CA_FORMAT_APPLICATION_LINK_FORMAT;
+ case COAP_MEDIATYPE_APPLICATION_XML:
+ return CA_FORMAT_APPLICATION_XML;
+ case COAP_MEDIATYPE_APPLICATION_OCTET_STREAM:
+ return CA_FORMAT_APPLICATION_OCTET_STREAM;
+ case COAP_MEDIATYPE_APPLICATION_RDF_XML:
+ return CA_FORMAT_APPLICATION_RDF_XML;
+ case COAP_MEDIATYPE_APPLICATION_EXI:
+ return CA_FORMAT_APPLICATION_EXI;
+ case COAP_MEDIATYPE_APPLICATION_JSON:
+ return CA_FORMAT_APPLICATION_JSON;
+ case COAP_MEDIATYPE_APPLICATION_CBOR:
+ return CA_FORMAT_APPLICATION_CBOR;
+ default:
+ return CA_FORMAT_UNSUPPORTED;
+ }
+}