// For POSIX.1-2001 base specification,
// Refer http://pubs.opengroup.org/onlinepubs/009695399/
#define _POSIX_C_SOURCE 200112L
+#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
+#endif
+#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
+#endif
+#include "iotivity_config.h"
#include <inttypes.h>
#include <string.h>
#include <ctype.h>
#include "logger.h"
#include "ocserverrequest.h"
#include "secureresourcemanager.h"
+#include "psinterface.h"
#include "doxmresource.h"
#include "cacommon.h"
#include "cainterface.h"
#include "ocpayload.h"
#include "ocpayloadcbor.h"
+#include "cautilinterface.h"
+#include "oicgroup.h"
#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
#include "routingutility.h"
#endif
#endif
-#ifdef WITH_ARDUINO
+#ifdef TCP_ADAPTER
+#include "oickeepalive.h"
+#endif
+
+//#ifdef DIRECT_PAIRING
+#include "directpairing.h"
+//#endif
+
+#ifdef HAVE_ARDUINO_TIME_H
#include "Time.h"
-#else
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
-#include "coap_time.h"
-#include "utlist.h"
-#include "pdu.h"
+#include <coap/coap.h>
-#ifndef ARDUINO
+#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
static OCResource *tailResource = NULL;
static OCResourceHandle platformResource = {0};
static OCResourceHandle deviceResource = {0};
+#ifdef MQ_BROKER
+static OCResourceHandle brokerResource = {0};
+#endif
+
#ifdef WITH_PRESENCE
static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
-static PresenceResource presenceResource;
+static PresenceResource presenceResource = {0};
static uint8_t PresenceTimeOutSize = 0;
static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
#endif
#endif
OCDeviceEntityHandler defaultDeviceHandler;
void* defaultDeviceHandlerCallbackParameter = NULL;
-static const char COAP_TCP[] = "coap+tcp:";
+static const char COAP_TCP_SCHEME[] = "coap+tcp:";
+static const char COAPS_TCP_SCHEME[] = "coaps+tcp:";
+static const char CORESPEC[] = "core";
+
+CAAdapterStateChangedCB g_adapterHandler = NULL;
+CAConnectionStateChangedCB g_connectionHandler = NULL;
//-----------------------------------------------------------------------------
// Macros
//-----------------------------------------------------------------------------
-#define TAG "OCStack"
+#define TAG "OIC_RI_STACK"
#define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
- {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
-#define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
+ {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
+#define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
TAG, #arg " is NULL"); return (retVal); } }
-#define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OC_LOG((logLevel), \
+#define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
TAG, #arg " is NULL"); return; } }
-#define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL");\
+#define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
goto exit;} }
//TODO: we should allow the server to define this
*/
static void incrementSequenceNumber(OCResource * resPtr);
-/**
- * Verify the lengths of the URI and the query separately.
- *
- * @param inputUri Input URI and query.
- * @param uriLen The length of the initial URI with query.
- * @return ::OC_STACK_OK on success, some other value upon failure.
- */
-static OCStackResult verifyUriQueryLength(const char * inputUri,
- uint16_t uriLen);
-
/*
* Attempts to initialize every network interface that the CA Layer might have compiled in.
*
static CAResult_t OCSelectNetwork();
/**
- * Get the CoAP ticks after the specified number of milli-seconds.
- *
- * @param afterMilliSeconds Milli-seconds.
- * @return
- * CoAP ticks
- */
-static uint32_t GetTicks(uint32_t afterMilliSeconds);
-
-/**
* Convert CAResponseResult_t to OCStackResult.
*
* @param caCode CAResponseResult_t code.
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-static OCStackResult CAToOCStackResult(CAResponseResult_t caCode);
-
-/**
- * Convert OCStackResult to CAResponseResult_t.
- *
- * @param caCode OCStackResult code.
- * @param method OCMethod method the return code replies to.
- * @return ::CA_CONTENT on OK, some other value upon failure.
- */
-static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
+static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
/**
* Convert OCTransportFlags_t to CATransportModifiers_t.
*/
static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
+/**
+ * default adapter state change callback method
+ *
+ * @param adapter CA network adapter type.
+ * @param enabled current adapter state.
+ */
+static void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled);
+
+/**
+ * default connection state change callback method
+ *
+ * @param info CAEndpoint which has address, port and etc.
+ * @param isConnected current connection state.
+ */
+static void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected);
+
+/**
+ * Register network monitoring callback.
+ * Network status changes are delivered these callback.
+ * @param adapterHandler Adapter state monitoring callback.
+ * @param connectionHandler Connection state monitoring callback.
+ */
+static void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
+ CAConnectionStateChangedCB connectionHandler);
+
//-----------------------------------------------------------------------------
// Internal functions
//-----------------------------------------------------------------------------
-uint32_t GetTicks(uint32_t afterMilliSeconds)
+bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
+{
+ if (!options || 0 == numOptions)
+ {
+ OIC_LOG (INFO, TAG, "No options present");
+ return false;
+ }
+
+ for (uint8_t i = 0; i < numOptions; i++)
+ {
+ if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
+ {
+ OIC_LOG(DEBUG, TAG, "Proxy URI is present");
+ return true;
+ }
+ }
+ return false;
+}
+
+uint32_t GetTicks(uint32_t milliSeconds)
{
coap_tick_t now;
coap_ticks(&now);
// Guard against overflow of uint32_t
- if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
+ if (milliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
COAP_TICKS_PER_SECOND)
{
- return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
+ return now + (milliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
}
else
{
out->flags = CAToOCTransportFlags(in->flags);
OICStrcpy(out->addr, sizeof(out->addr), in->addr);
out->port = in->port;
- out->interface = in->interface;
+ out->ifindex = in->ifindex;
#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
- memcpy(out->routeData, in->routeData, sizeof(out->routeData));
+ /* This assert is to prevent accidental mismatch between address size macros defined in
+ * RI and CA and cause crash here. */
+ OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
+ "Address size mismatch between RI and CA");
+ memcpy(out->routeData, in->routeData, sizeof(in->routeData));
#endif
}
out->flags = OCToCATransportFlags(in->flags);
OICStrcpy(out->addr, sizeof(out->addr), in->addr);
#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
- memcpy(out->routeData, in->routeData, sizeof(out->routeData));
+ /* This assert is to prevent accidental mismatch between address size macros defined in
+ * RI and CA and cause crash here. */
+ OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
+ "Address size mismatch between RI and CA");
+ memcpy(out->routeData, in->routeData, sizeof(in->routeData));
#endif
out->port = in->port;
- out->interface = in->interface;
+ out->ifindex = in->ifindex;
}
void FixUpClientResponse(OCClientResponse *cr)
VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
- OCStackResult rmResult = RMAddInfo(object->routeData, &(requestInfo->info.options),
- &(requestInfo->info.numOptions));
+ OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
if (OC_STACK_OK != rmResult)
{
- OC_LOG(ERROR, TAG, "Add destination option failed");
+ OIC_LOG(ERROR, TAG, "Add destination option failed");
return rmResult;
}
#endif
CAResult_t result = CASendRequest(object, requestInfo);
if(CA_STATUS_OK != result)
{
- OC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
+ OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
return CAResultToOCResult(result);
}
return OC_STACK_OK;
switch(status)
{
case OC_OBSERVER_NOT_INTERESTED:
- OC_LOG(DEBUG, TAG, "observer not interested in our notifications");
- observer = GetObserverUsingToken (token, tokenLength);
- if(observer)
+ OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
+ observer = GetObserverUsingToken(token, tokenLength);
+ if (observer)
{
result = FormOCEntityHandlerRequest(&ehRequest,
- (OCRequestHandle)NULL,
+ 0,
OC_REST_NOMETHOD,
&observer->devAddr,
(OCResourceHandle)NULL,
NULL, PAYLOAD_TYPE_REPRESENTATION,
NULL, 0, 0, NULL,
OC_OBSERVE_DEREGISTER,
- observer->observeId);
- if(result != OC_STACK_OK)
+ observer->observeId,
+ 0);
+ if (result != OC_STACK_OK)
{
return result;
}
- observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
- observer->resource->entityHandlerCallbackParam);
+
+ if (observer->resource && observer->resource->entityHandler)
+ {
+ observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
+ observer->resource->entityHandlerCallbackParam);
+ }
}
- result = DeleteObserverUsingToken (token, tokenLength);
- if(result == OC_STACK_OK)
+ result = DeleteObserverUsingToken(token, tokenLength);
+ if (result == OC_STACK_OK)
{
- OC_LOG(DEBUG, TAG, "Removed observer successfully");
+ OIC_LOG(DEBUG, TAG, "Removed observer successfully");
}
else
{
result = OC_STACK_OK;
- OC_LOG(DEBUG, TAG, "Observer Removal failed");
+ OIC_LOG(DEBUG, TAG, "Observer Removal failed");
}
break;
case OC_OBSERVER_STILL_INTERESTED:
- OC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
- observer = GetObserverUsingToken (token, tokenLength);
- if(observer)
+ OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
+ observer = GetObserverUsingToken(token, tokenLength);
+ if (observer)
{
observer->forceHighQos = 0;
observer->failedCommCount = 0;
break;
case OC_OBSERVER_FAILED_COMM:
- OC_LOG(DEBUG, TAG, "observer is unreachable");
+ OIC_LOG(DEBUG, TAG, "observer is unreachable");
observer = GetObserverUsingToken (token, tokenLength);
- if(observer)
+ if (observer)
{
- if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
+ if (observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
{
result = FormOCEntityHandlerRequest(&ehRequest,
- (OCRequestHandle)NULL,
+ 0,
OC_REST_NOMETHOD,
&observer->devAddr,
(OCResourceHandle)NULL,
NULL, PAYLOAD_TYPE_REPRESENTATION,
NULL, 0, 0, NULL,
OC_OBSERVE_DEREGISTER,
- observer->observeId);
- if(result != OC_STACK_OK)
+ observer->observeId,
+ 0);
+ if (result != OC_STACK_OK)
{
return OC_STACK_ERROR;
}
- observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
- observer->resource->entityHandlerCallbackParam);
- result = DeleteObserverUsingToken (token, tokenLength);
- if(result == OC_STACK_OK)
+ if (observer->resource && observer->resource->entityHandler)
+ {
+ observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
+ observer->resource->entityHandlerCallbackParam);
+ }
+
+ result = DeleteObserverUsingToken(token, tokenLength);
+ if (result == OC_STACK_OK)
{
- OC_LOG(DEBUG, TAG, "Removed observer successfully");
+ OIC_LOG(DEBUG, TAG, "Removed observer successfully");
}
else
{
result = OC_STACK_OK;
- OC_LOG(DEBUG, TAG, "Observer Removal failed");
+ OIC_LOG(DEBUG, TAG, "Observer Removal failed");
}
}
else
{
observer->failedCommCount++;
+ observer->forceHighQos = 1;
+ OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",
+ observer->failedCommCount);
result = OC_STACK_CONTINUE;
}
- observer->forceHighQos = 1;
- OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
}
break;
default:
- OC_LOG(ERROR, TAG, "Unknown status");
+ OIC_LOG(ERROR, TAG, "Unknown status");
result = OC_STACK_ERROR;
break;
}
return result;
}
-OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
+
+OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
{
OCStackResult ret = OC_STACK_ERROR;
-
switch(caCode)
{
case CA_CREATED:
ret = OC_STACK_RESOURCE_DELETED;
break;
case CA_CHANGED:
+ ret = OC_STACK_RESOURCE_CHANGED;
+ break;
case CA_CONTENT:
+ case CA_VALID:
ret = OC_STACK_OK;
break;
case CA_BAD_REQ:
case CA_RETRANSMIT_TIMEOUT:
ret = OC_STACK_COMM_ERROR;
break;
+ case CA_REQUEST_ENTITY_TOO_LARGE:
+ ret = OC_STACK_TOO_LARGE_REQ;
+ break;
+ case CA_FORBIDDEN_REQ:
+ ret = OC_STACK_FORBIDDEN_REQ;
+ break;
+ case CA_INTERNAL_SERVER_ERROR:
+ ret = OC_STACK_INTERNAL_SERVER_ERROR;
+ break;
default:
break;
}
// This should not happen but,
// give it a value just in case but output an error
ret = CA_CONTENT;
- OC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
+ OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
+ method);
}
break;
case OC_STACK_RESOURCE_CREATED:
case OC_STACK_RESOURCE_DELETED:
ret = CA_DELETED;
break;
+ case OC_STACK_RESOURCE_CHANGED:
+ ret = CA_CHANGED;
+ break;
case OC_STACK_INVALID_QUERY:
ret = CA_BAD_REQ;
break;
case OC_STACK_UNAUTHORIZED_REQ:
ret = CA_UNAUTHORIZED_REQ;
break;
+ case OC_STACK_FORBIDDEN_REQ:
+ ret = CA_FORBIDDEN_REQ;
+ break;
+ case OC_STACK_INTERNAL_SERVER_ERROR:
+ ret = CA_INTERNAL_SERVER_ERROR;
+ break;
default:
break;
}
return OC_STACK_INVALID_PARAM;
}
- OC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
+ OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
cbNode->presence->TTL = maxAgeSeconds;
cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
- OC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
- OC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
- OC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
+ OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
+ OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
+ OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
}
cbNode->presence->TTLlevel = 0;
- OC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
+ OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
return OC_STACK_OK;
}
}
}
+OCStackResult OCEncodeAddressForRFC6874(char *outputAddress,
+ size_t outputSize,
+ const char *inputAddress)
+{
+ VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
+ VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
+
+ size_t inputLength = strnlen(inputAddress, outputSize);
+
+ // inputSize includes the null terminator
+ size_t inputSize = inputLength + 1;
+
+ if (inputSize > outputSize)
+ {
+ OIC_LOG_V(ERROR, TAG,
+ "OCEncodeAddressForRFC6874 failed: "
+ "outputSize (%zu) < inputSize (%zu)",
+ outputSize, inputSize);
+
+ return OC_STACK_ERROR;
+ }
+
+ char* percentChar = strchr(inputAddress, '%');
+
+ // If there is no '%' character, then no change is required to the string.
+ if (NULL == percentChar)
+ {
+ OICStrcpy(outputAddress, outputSize, inputAddress);
+ return OC_STACK_OK;
+ }
+
+ const char* addressPart = &inputAddress[0];
+ const char* scopeIdPart = percentChar + 1;
+
+ // Sanity check to make sure this string doesn't have more '%' characters
+ if (NULL != strchr(scopeIdPart, '%'))
+ {
+ return OC_STACK_ERROR;
+ }
+
+ // If no string follows the first '%', then the input was invalid.
+ if (scopeIdPart[0] == '\0')
+ {
+ OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
+ return OC_STACK_ERROR;
+ }
+
+ // Check to see if the string is already encoded
+ if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
+ {
+ OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Input string is already encoded");
+ return OC_STACK_ERROR;
+ }
+
+ // Fail if we don't have room for encoded string's two additional chars
+ if (outputSize < (inputSize + 2))
+ {
+ OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: encoded output will not fit!");
+ return OC_STACK_ERROR;
+ }
+
+ // Restore the null terminator with an escaped '%' character, per RFC 6874
+ OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
+ strcat(outputAddress, "%25");
+ strcat(outputAddress, scopeIdPart);
+
+ return OC_STACK_OK;
+}
+
+OCStackResult OCDecodeAddressForRFC6874(char *outputAddress,
+ size_t outputSize,
+ const char *inputAddress,
+ const char *end)
+{
+ VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
+ VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
+
+ if (NULL == end)
+ {
+ end = inputAddress + strlen(inputAddress);
+ }
+ size_t inputLength = end - inputAddress;
+
+ const char *percent = strchr(inputAddress, '%');
+ if (!percent || (percent > end))
+ {
+ OICStrcpyPartial(outputAddress, outputSize, inputAddress, inputLength);
+ }
+ else
+ {
+ if (percent[1] != '2' || percent[2] != '5')
+ {
+ return OC_STACK_INVALID_URI;
+ }
+
+ int addrlen = percent - inputAddress + 1;
+ OICStrcpyPartial(outputAddress, outputSize, inputAddress, addrlen);
+ OICStrcpyPartial(outputAddress + addrlen, outputSize - addrlen,
+ percent + 3, end - percent - 3);
+ }
+
+ return OC_STACK_OK;
+}
+
/**
* The cononical presence allows constructed URIs to be string compared.
*
* requestUri must be a char array of size CA_MAX_URI_LENGTH
*/
-static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
- char *presenceUri)
+static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
+ char *presenceUri, bool isMulticast)
{
VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
- VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
- CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
+ if (isMulticast)
+ {
+ OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
+ return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
+ }
+ CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
if (ep->adapter == CA_ADAPTER_IP)
{
if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
}
else
{
+ char addressEncoded[CA_MAX_URI_LENGTH] = {0};
+
+ OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
+ sizeof(addressEncoded),
+ ep->addr);
+
+ if (OC_STACK_OK != result)
+ {
+ return -1;
+ }
+
return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
- ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
+ addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
}
}
else
if (responseInfo->result != CA_CONTENT)
{
- OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
+ OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
return OC_STACK_ERROR;
}
- // check for unicast presence
- uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
- if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
- {
- return OC_STACK_INVALID_URI;
- }
-
- cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
- if (cbNode)
- {
- presenceSubscribe = 1;
- }
- else
- {
- // check for multiicast presence
- CAEndpoint_t ep = { .adapter = endpoint->adapter,
- .flags = endpoint->flags };
-
- uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
-
- cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
- if (cbNode)
- {
- multicastPresenceSubscribe = 1;
- }
- }
-
- if (!presenceSubscribe && !multicastPresenceSubscribe)
- {
- OC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
- goto exit;
- }
-
response.payload = NULL;
response.result = OC_STACK_OK;
if(result != OC_STACK_OK)
{
- OC_LOG(ERROR, TAG, "Presence parse failed");
+ OIC_LOG(ERROR, TAG, "Presence parse failed");
goto exit;
}
if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
{
- OC_LOG(ERROR, TAG, "Presence payload was wrong type");
+ OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
result = OC_STACK_ERROR;
goto exit;
}
maxAge = ((OCPresencePayload*)response.payload)->maxAge;
}
+ // check for unicast presence
+ uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
+ responseInfo->isMulticast);
+ if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
+ {
+ return OC_STACK_INVALID_URI;
+ }
+ OIC_LOG(ERROR, TAG, "check for unicast presence");
+ cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
+ if (cbNode)
+ {
+ presenceSubscribe = 1;
+ }
+ else
+ {
+ // check for multicast presence
+ OIC_LOG(ERROR, TAG, "check for multicast presence");
+ cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
+ if (cbNode)
+ {
+ multicastPresenceSubscribe = 1;
+ }
+ }
+
+ if (!presenceSubscribe && !multicastPresenceSubscribe)
+ {
+ OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
+ goto exit;
+ }
+
if (presenceSubscribe)
{
if(cbNode->sequenceNumber == response.sequenceNumber)
{
- OC_LOG(INFO, TAG, "No presence change");
+ OIC_LOG(INFO, TAG, "No presence change");
ResetPresenceTTL(cbNode, maxAge);
- OC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
+ OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
goto exit;
}
if(maxAge == 0)
{
- OC_LOG(INFO, TAG, "Stopping presence");
+ OIC_LOG(INFO, TAG, "Stopping presence");
response.result = OC_STACK_PRESENCE_STOPPED;
if(cbNode->presence)
{
if(!(cbNode->presence))
{
- OC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
+ OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
result = OC_STACK_NO_MEMORY;
goto exit;
}
cbNode->presence->timeOut = (uint32_t *)
OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
if(!(cbNode->presence->timeOut)){
- OC_LOG(ERROR, TAG,
+ OIC_LOG(ERROR, TAG,
"Could not allocate memory for cbNode->presence->timeOut");
OICFree(cbNode->presence);
result = OC_STACK_NO_MEMORY;
ResetPresenceTTL(cbNode, maxAge);
cbNode->sequenceNumber = response.sequenceNumber;
-
- // Ensure that a filter is actually applied.
- if( resourceTypeName && cbNode->filterResourceType)
- {
- if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
- {
- goto exit;
- }
- }
}
}
else
{
// This is the multicast case
- OCMulticastNode* mcNode = NULL;
- mcNode = GetMCPresenceNode(presenceUri);
-
- if(mcNode != NULL)
+ OIC_LOG(INFO, TAG, "this is the multicast presence");
+ if (0 == maxAge)
{
- if(mcNode->nonce == response.sequenceNumber)
- {
- OC_LOG(INFO, TAG, "No presence change (Multicast)");
- goto exit;
- }
- mcNode->nonce = response.sequenceNumber;
-
- if(maxAge == 0)
- {
- OC_LOG(INFO, TAG, "Stopping presence");
- response.result = OC_STACK_PRESENCE_STOPPED;
- }
- }
- else
- {
- char* uri = OICStrdup(presenceUri);
- if (!uri)
- {
- OC_LOG(INFO, TAG,
- "No Memory for URI to store in the presence node");
- result = OC_STACK_NO_MEMORY;
- goto exit;
- }
-
- result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
- if(result == OC_STACK_NO_MEMORY)
- {
- OC_LOG(INFO, TAG,
- "No Memory for Multicast Presence Node");
- OICFree(uri);
- goto exit;
- }
- // presence node now owns uri
+ OIC_LOG(INFO, TAG, "Stopping presence");
+ response.result = OC_STACK_PRESENCE_STOPPED;
}
+ }
- // Ensure that a filter is actually applied.
- if(resourceTypeName && cbNode->filterResourceType)
+ // Ensure that a filter is actually applied.
+ if (resourceTypeName && cbNode->filterResourceType)
+ {
+ OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
+ if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
{
- if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
- {
- goto exit;
- }
+ goto exit;
}
}
+ OIC_LOG(INFO, TAG, "Callback for presence");
+
cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
if (cbResult == OC_STACK_DELETE_TRANSACTION)
return result;
}
-void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
+void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
{
- VERIFY_NON_NULL_NR(endPoint, FATAL);
- VERIFY_NON_NULL_NR(responseInfo, FATAL);
-
- OC_LOG(INFO, TAG, "Enter HandleCAResponses");
-
-#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
-#ifdef ROUTING_GATEWAY
- bool needRIHandling = false;
- /*
- * Routing manager is going to update either of endpoint or response or both.
- * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
- * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
- * destination.
- */
- OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
- &needRIHandling);
- if(ret != OC_STACK_OK || !needRIHandling)
- {
- OC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
- return;
- }
-#endif
-
- /*
- * Put source in sender endpoint so that the next packet from application can be routed to
- * proper destination and remove "RM" coap header option before passing request / response to
- * RI as this option will make no sense to either RI or application.
- */
- RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
- (uint8_t *) &(responseInfo->info.numOptions),
- (CAEndpoint_t *) endPoint);
-#endif
+ OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
if(responseInfo->info.resourceUri &&
strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
if(cbNode)
{
- OC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
+ OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
if(responseInfo->result == CA_EMPTY)
{
- OC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
+ OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
// We do not have a case for the client to receive a RESET
if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
{
//This is the case of receiving an ACK on a request to a slow resource!
- OC_LOG(INFO, TAG, "This is a pure ACK");
+ OIC_LOG(INFO, TAG, "This is a pure ACK");
//TODO: should we inform the client
// app that at least the request was received at the server?
}
}
else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
{
- OC_LOG(INFO, TAG, "Receiving A Timeout for this token");
- OC_LOG(INFO, TAG, "Calling into application address space");
+ OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
+ OIC_LOG(INFO, TAG, "Calling into application address space");
OCClientResponse response =
{.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
sizeof (response.identity.id));
response.identity.id_length = responseInfo->info.identity.id_length;
- response.result = CAToOCStackResult(responseInfo->result);
+ response.result = CAResponseToOCStackResult(responseInfo->result);
cbNode->callBack(cbNode->context,
cbNode->handle, &response);
FindAndDeleteClientCB(cbNode);
}
else
{
- OC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
- OC_LOG(INFO, TAG, "Calling into application address space");
+ OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
+ OIC_LOG(INFO, TAG, "Calling into application address space");
OCClientResponse response =
{.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
- response.sequenceNumber = OC_OBSERVE_NO_OPTION;
+ response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
CopyEndpointToDevAddr(endPoint, &response.devAddr);
FixUpClientResponse(&response);
response.resourceUri = responseInfo->info.resourceUri;
sizeof (response.identity.id));
response.identity.id_length = responseInfo->info.identity.id_length;
- response.result = CAToOCStackResult(responseInfo->result);
+ response.result = CAResponseToOCStackResult(responseInfo->result);
if(responseInfo->info.payload &&
responseInfo->info.payloadSize)
{
type = PAYLOAD_TYPE_DISCOVERY;
}
+#ifdef WITH_MQ
+ else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
+ {
+ type = PAYLOAD_TYPE_DISCOVERY;
+ }
+#endif
else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
{
- type = PAYLOAD_TYPE_DEVICE;
+ type = PAYLOAD_TYPE_REPRESENTATION;
}
else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
{
- type = PAYLOAD_TYPE_PLATFORM;
+ type = PAYLOAD_TYPE_REPRESENTATION;
}
+
#ifdef ROUTING_GATEWAY
else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
{
#endif
else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
{
- type = PAYLOAD_TYPE_RD;
+ type = PAYLOAD_TYPE_REPRESENTATION;
}
+#ifdef TCP_ADAPTER
+ else if (strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
+ {
+ type = PAYLOAD_TYPE_REPRESENTATION;
+ }
+#endif
else
{
- OC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
+ OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
cbNode->method, cbNode->requestUri);
return;
}
cbNode->method == OC_REST_OBSERVE_ALL ||
cbNode->method == OC_REST_DELETE)
{
- char targetUri[MAX_URI_LENGTH];
- snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s",
- OC_RSRVD_RD_URI, OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
- if (strcmp(targetUri, cbNode->requestUri) == 0)
+ if (cbNode->requestUri)
{
- type = PAYLOAD_TYPE_RD;
+ if (0 == strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri))
+ {
+ type = PAYLOAD_TYPE_REPRESENTATION;
+ }
+ else if (0 == strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri))
+ {
+ type = PAYLOAD_TYPE_REPRESENTATION;
+ }
+ if (type == PAYLOAD_TYPE_INVALID)
+ {
+ OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
+ cbNode->method, cbNode->requestUri);
+ type = PAYLOAD_TYPE_REPRESENTATION;
+ }
}
- if (type == PAYLOAD_TYPE_INVALID)
+ else
{
- OC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
- cbNode->method, cbNode->requestUri);
+ OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
type = PAYLOAD_TYPE_REPRESENTATION;
}
}
else
{
- OC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
+ OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
cbNode->method, cbNode->requestUri);
return;
}
responseInfo->info.payload,
responseInfo->info.payloadSize))
{
- OC_LOG(ERROR, TAG, "Error converting payload");
+ OIC_LOG(ERROR, TAG, "Error converting payload");
OCPayloadDestroy(response.payload);
return;
}
{
int start = 0;
//First option always with option ID is COAP_OPTION_OBSERVE if it is available.
- if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
+ if(responseInfo->info.options
+ && responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
{
size_t i;
uint32_t observationOption;
(observationOption << 8) | optionData[i];
}
response.sequenceNumber = observationOption;
-
response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
start = 1;
}
if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
{
- OC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
+ OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
OCPayloadDestroy(response.payload);
return;
}
for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
{
- memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
- &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
+ if(&(responseInfo->info.options[i]))
+ {
+ memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
+ &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
+ }
}
}
if (cbNode->method == OC_REST_OBSERVE &&
response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
+ cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
response.sequenceNumber <= cbNode->sequenceNumber)
{
- OC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
+ OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
response.sequenceNumber);
}
else
{
+#ifdef RD_CLIENT
+ // if request uri is '/oic/rd', update ins value of resource.
+ char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
+ if (targetUri)
+ {
+ OCUpdateResourceInsWithResponse(cbNode->requestUri, &response);
+ }
+#endif
OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
cbNode->handle,
&response);
if(responseInfo->info.type == CA_MSG_CONFIRM)
{
SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
- CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
+ CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
}
OCPayloadDestroy(response.payload);
if(observer)
{
- OC_LOG(INFO, TAG, "There is an observer associated with the response token");
+ OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
if(responseInfo->result == CA_EMPTY)
{
- OC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
+ OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
if(responseInfo->info.type == CA_MSG_RESET)
{
- OC_LOG(INFO, TAG, "This is a RESET");
+ OIC_LOG(INFO, TAG, "This is a RESET");
OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
OC_OBSERVER_NOT_INTERESTED);
}
else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
{
- OC_LOG(INFO, TAG, "This is a pure ACK");
+ OIC_LOG(INFO, TAG, "This is a pure ACK");
OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
OC_OBSERVER_STILL_INTERESTED);
}
}
else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
{
- OC_LOG(INFO, TAG, "Receiving Time Out for an observer");
+ OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
OC_OBSERVER_FAILED_COMM);
}
if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
|| myStackMode == OC_GATEWAY)
{
- OC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
+ OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
if(responseInfo->result == CA_EMPTY)
{
- OC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
+ OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
}
else
{
- OC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
+ OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
- CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
+ CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
}
}
if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
|| myStackMode == OC_GATEWAY)
{
- OC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
+ OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
{
- OC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
+ OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
responseInfo->info.messageId);
}
if (responseInfo->info.type == CA_MSG_RESET)
{
- OC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
+ OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
responseInfo->info.messageId);
}
}
return;
}
+}
+
+void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
+{
+ VERIFY_NON_NULL_NR(endPoint, FATAL);
+ VERIFY_NON_NULL_NR(responseInfo, FATAL);
+
+ OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
+
+#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
+#ifdef ROUTING_GATEWAY
+ bool needRIHandling = false;
+ /*
+ * Routing manager is going to update either of endpoint or response or both.
+ * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
+ * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
+ * destination.
+ */
+ OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
+ &needRIHandling);
+ if(ret != OC_STACK_OK || !needRIHandling)
+ {
+ OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
+ return;
+ }
+#endif
+
+ /*
+ * Put source in sender endpoint so that the next packet from application can be routed to
+ * proper destination and remove "RM" coap header option before passing request / response to
+ * RI as this option will make no sense to either RI or application.
+ */
+ RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
+ (uint8_t *) &(responseInfo->info.numOptions),
+ (CAEndpoint_t *) endPoint);
+#endif
- OC_LOG(INFO, TAG, "Exit HandleCAResponses");
+ OCHandleResponse(endPoint, responseInfo);
+
+ OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
}
/*
* This function handles error response from CA
* code shall be added to handle the errors
*/
-void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
+void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
{
- OC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
+ VERIFY_NON_NULL_NR(endPoint, FATAL);
+ VERIFY_NON_NULL_NR(errorInfo, FATAL);
- if(NULL == endPoint)
+ OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
+
+ ClientCB *cbNode = GetClientCB(errorInfo->info.token,
+ errorInfo->info.tokenLength, NULL, NULL);
+ if (cbNode)
{
- OC_LOG(ERROR, TAG, "endPoint is NULL");
- return;
+ OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
+ CopyEndpointToDevAddr(endPoint, &response.devAddr);
+ FixUpClientResponse(&response);
+ response.resourceUri = errorInfo->info.resourceUri;
+ memcpy(response.identity.id, errorInfo->info.identity.id,
+ sizeof (response.identity.id));
+ response.identity.id_length = errorInfo->info.identity.id_length;
+ response.result = CAResultToOCResult(errorInfo->result);
+
+ cbNode->callBack(cbNode->context, cbNode->handle, &response);
}
- if(NULL == errrorInfo)
+ ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
+ errorInfo->info.tokenLength);
+ if (observer)
{
- OC_LOG(ERROR, TAG, "errrorInfo is NULL");
- return;
+ OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
+ OCStackResult result = CAResultToOCResult(errorInfo->result);
+ if (OC_STACK_COMM_ERROR == result)
+ {
+ OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
+ OC_OBSERVER_FAILED_COMM);
+ }
}
- OC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
+
+ OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
}
/*
OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
const CAResponseResult_t responseResult, const CAMessageType_t type,
const uint8_t numOptions, const CAHeaderOption_t *options,
- CAToken_t token, uint8_t tokenLength, const char *resourceUri)
+ CAToken_t token, uint8_t tokenLength, const char *resourceUri,
+ CADataType_t dataType)
{
+ OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
CAResponseInfo_t respInfo = {
.result = responseResult
};
respInfo.info.type = type;
respInfo.info.resourceUri = OICStrdup (resourceUri);
respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
+ respInfo.info.dataType = dataType;
#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
// Add the destination to route option from the endpoint->routeData.
- OCStackResult result = RMAddInfo(endPoint->routeData,
- &(respInfo.info.options),
- &(respInfo.info.numOptions));
+ bool doPost = false;
+ OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
if(OC_STACK_OK != result)
{
- OC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
+ OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
+ OICFree (respInfo.info.resourceUri);
+ OICFree (respInfo.info.options);
return result;
}
-#endif
-
- CAResult_t caResult = CASendResponse(endPoint, &respInfo);
+ if (doPost)
+ {
+ OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
+ CARequestInfo_t reqInfo = {.method = CA_POST };
+ /* The following initialization is not done in a single initializer block as in
+ * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
+ * does not have designated initalizers. This is a work-around for now.
+ */
+ reqInfo.info.type = CA_MSG_NONCONFIRM;
+ reqInfo.info.messageId = coapID;
+ reqInfo.info.tokenLength = tokenLength;
+ reqInfo.info.token = token;
+ reqInfo.info.numOptions = respInfo.info.numOptions;
+ reqInfo.info.payload = NULL;
+ reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
+ if (reqInfo.info.numOptions)
+ {
+ reqInfo.info.options =
+ (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
+ if (NULL == reqInfo.info.options)
+ {
+ OIC_LOG(ERROR, TAG, "Calloc failed");
+ OICFree (reqInfo.info.resourceUri);
+ OICFree (respInfo.info.resourceUri);
+ OICFree (respInfo.info.options);
+ return OC_STACK_NO_MEMORY;
+ }
+ memcpy (reqInfo.info.options, respInfo.info.options,
+ sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
- // resourceUri in the info field is cloned in the CA layer and
- // thus ownership is still here.
- OICFree (respInfo.info.resourceUri);
- OICFree (respInfo.info.options);
- if(CA_STATUS_OK != caResult)
+ }
+ CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
+ OICFree (reqInfo.info.resourceUri);
+ OICFree (reqInfo.info.options);
+ OICFree (respInfo.info.resourceUri);
+ OICFree (respInfo.info.options);
+ if (CA_STATUS_OK != caResult)
+ {
+ OIC_LOG(ERROR, TAG, "CASendRequest error");
+ return CAResultToOCResult(caResult);
+ }
+ }
+ else
+#endif
{
- OC_LOG(ERROR, TAG, "CASendResponse error");
- return CAResultToOCResult(caResult);
+ CAResult_t caResult = CASendResponse(endPoint, &respInfo);
+
+ // resourceUri in the info field is cloned in the CA layer and
+ // thus ownership is still here.
+ OICFree (respInfo.info.resourceUri);
+ OICFree (respInfo.info.options);
+ if(CA_STATUS_OK != caResult)
+ {
+ OIC_LOG(ERROR, TAG, "CASendResponse error");
+ return CAResultToOCResult(caResult);
+ }
}
+ OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
return OC_STACK_OK;
}
-//This function will be called back by CA layer when a request is received
-void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
+OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
{
- OC_LOG(INFO, TAG, "Enter HandleCARequests");
- if(!endPoint)
+ OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
+ OCStackResult result = OC_STACK_ERROR;
+ if(!protocolRequest)
{
- OC_LOG(ERROR, TAG, "endPoint is NULL");
- return;
+ OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
+ return OC_STACK_INVALID_PARAM;
}
- if(!requestInfo)
+ OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
+ protocolRequest->tokenLength);
+ if(!request)
{
- OC_LOG(ERROR, TAG, "requestInfo is NULL");
- return;
+ OIC_LOG(INFO, TAG, "This is a new Server Request");
+ result = AddServerRequest(&request, protocolRequest->coapID,
+ protocolRequest->delayedResNeeded, 0, protocolRequest->method,
+ protocolRequest->numRcvdVendorSpecificHeaderOptions,
+ protocolRequest->observationOption, protocolRequest->qos,
+ protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
+ protocolRequest->payload, protocolRequest->requestToken,
+ protocolRequest->tokenLength, protocolRequest->resourceUrl,
+ protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
+ &protocolRequest->devAddr);
+ if (OC_STACK_OK != result)
+ {
+ OIC_LOG(ERROR, TAG, "Error adding server request");
+ return result;
+ }
+
+ if(!request)
+ {
+ OIC_LOG(ERROR, TAG, "Out of Memory");
+ return OC_STACK_NO_MEMORY;
+ }
+
+ if(!protocolRequest->reqMorePacket)
+ {
+ request->requestComplete = 1;
+ }
+ }
+ else
+ {
+ OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
}
-#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
-#ifdef ROUTING_GATEWAY
- bool needRIHandling = false;
- /*
- * Routing manager is going to update either of endpoint or request or both.
- * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
- * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
- * destination. It can also remove "RM" coap header option before passing request / response to
- * RI as this option will make no sense to either RI or application.
- */
- OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
- &needRIHandling);
- if(OC_STACK_OK != ret || !needRIHandling)
+ if(request->requestComplete)
{
- OC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
- return;
+ OIC_LOG(INFO, TAG, "This Server Request is complete");
+ ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
+ OCResource *resource = NULL;
+ result = DetermineResourceHandling (request, &resHandling, &resource);
+ if (result == OC_STACK_OK)
+ {
+ result = ProcessRequest(resHandling, resource, request);
+ }
}
-#endif
+ else
+ {
+ OIC_LOG(INFO, TAG, "This Server Request is incomplete");
+ result = OC_STACK_CONTINUE;
+ }
+ return result;
+}
- /*
- * Put source in sender endpoint so that the next packet from application can be routed to
- * proper destination and remove RM header option.
- */
- RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
- (uint8_t *) &(requestInfo->info.numOptions),
- (CAEndpoint_t *) endPoint);
-#endif
+void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
+{
+ OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
OCStackResult requestResult = OC_STACK_ERROR;
OCServerProtocolRequest serverRequest = {0};
- OC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
+ OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
char * uriWithoutQuery = NULL;
char * query = NULL;
if (requestResult != OC_STACK_OK || !uriWithoutQuery)
{
- OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
+ OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
return;
}
- OC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
- OC_LOG_V(INFO, TAG, "Query : %s", query);
+ OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
+ OIC_LOG_V(INFO, TAG, "Query : %s", query);
if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
{
}
else
{
- OC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
+ OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
OICFree(uriWithoutQuery);
OICFree(query);
return;
}
else
{
- OC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
+ OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
OICFree(query);
return;
}
{
serverRequest.reqTotalSize = requestInfo->info.payloadSize;
serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
+ if (!serverRequest.payload)
+ {
+ OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
+ return;
+ }
memcpy (serverRequest.payload, requestInfo->info.payload,
requestInfo->info.payloadSize);
}
serverRequest.method = OC_REST_DELETE;
break;
default:
- OC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
+ OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
requestInfo->info.type, requestInfo->info.numOptions,
requestInfo->info.options, requestInfo->info.token,
- requestInfo->info.tokenLength, requestInfo->info.resourceUri);
+ requestInfo->info.tokenLength, requestInfo->info.resourceUri,
+ CA_RESPONSE_DATA);
OICFree(serverRequest.payload);
return;
}
- OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
+ OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
requestInfo->info.tokenLength);
- serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
+
serverRequest.tokenLength = requestInfo->info.tokenLength;
+ if (serverRequest.tokenLength) {
+ // Non empty token
+ serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
- if (!serverRequest.requestToken)
- {
- OC_LOG(FATAL, TAG, "Allocation for token failed.");
- SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
- requestInfo->info.type, requestInfo->info.numOptions,
- requestInfo->info.options, requestInfo->info.token,
- requestInfo->info.tokenLength, requestInfo->info.resourceUri);
- OICFree(serverRequest.payload);
- return;
+ if (!serverRequest.requestToken)
+ {
+ OIC_LOG(FATAL, TAG, "Allocation for token failed.");
+ SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
+ requestInfo->info.type, requestInfo->info.numOptions,
+ requestInfo->info.options, requestInfo->info.token,
+ requestInfo->info.tokenLength, requestInfo->info.resourceUri,
+ CA_RESPONSE_DATA);
+ OICFree(serverRequest.payload);
+ return;
+ }
+ memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
}
- memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
switch (requestInfo->info.acceptFormat)
{
GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
{
- OC_LOG(ERROR, TAG,
+ OIC_LOG(ERROR, TAG,
"The request info numOptions is greater than MAX_HEADER_OPTIONS");
SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
requestInfo->info.type, requestInfo->info.numOptions,
requestInfo->info.options, requestInfo->info.token,
- requestInfo->info.tokenLength, requestInfo->info.resourceUri);
+ requestInfo->info.tokenLength, requestInfo->info.resourceUri,
+ CA_RESPONSE_DATA);
OICFree(serverRequest.payload);
OICFree(serverRequest.requestToken);
return;
}
serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
- if (serverRequest.numRcvdVendorSpecificHeaderOptions)
+ if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
{
memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
sizeof(CAHeaderOption_t)*tempNum);
requestResult = HandleStackRequests (&serverRequest);
// Send ACK to client as precursor to slow response
- if(requestResult == OC_STACK_SLOW_RESOURCE)
- {
- SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
- CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
- }
- else if(requestResult != OC_STACK_OK)
- {
- OC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
-
- CAResponseResult_t stackResponse =
- OCToCAStackResult(requestResult, serverRequest.method);
-
- SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
- requestInfo->info.type, requestInfo->info.numOptions,
- requestInfo->info.options, requestInfo->info.token,
- requestInfo->info.tokenLength, requestInfo->info.resourceUri);
- }
- // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
- // The token is copied in there, and is thus still owned by this function.
- OICFree(serverRequest.payload);
- OICFree(serverRequest.requestToken);
- OC_LOG(INFO, TAG, "Exit HandleCARequests");
-}
-
-OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
-{
- OC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
- OCStackResult result = OC_STACK_ERROR;
- ResourceHandling resHandling;
- OCResource *resource;
- if(!protocolRequest)
- {
- OC_LOG(ERROR, TAG, "protocolRequest is NULL");
- return OC_STACK_INVALID_PARAM;
- }
-
- OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
- protocolRequest->tokenLength);
- if(!request)
- {
- OC_LOG(INFO, TAG, "This is a new Server Request");
- result = AddServerRequest(&request, protocolRequest->coapID,
- protocolRequest->delayedResNeeded, 0, protocolRequest->method,
- protocolRequest->numRcvdVendorSpecificHeaderOptions,
- protocolRequest->observationOption, protocolRequest->qos,
- protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
- protocolRequest->payload, protocolRequest->requestToken,
- protocolRequest->tokenLength, protocolRequest->resourceUrl,
- protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
- &protocolRequest->devAddr);
- if (OC_STACK_OK != result)
- {
- OC_LOG(ERROR, TAG, "Error adding server request");
- return result;
- }
-
- if(!request)
- {
- OC_LOG(ERROR, TAG, "Out of Memory");
- return OC_STACK_NO_MEMORY;
- }
-
- if(!protocolRequest->reqMorePacket)
- {
- request->requestComplete = 1;
- }
- }
- else
- {
- OC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
- }
-
- if(request->requestComplete)
- {
- OC_LOG(INFO, TAG, "This Server Request is complete");
- result = DetermineResourceHandling (request, &resHandling, &resource);
- if (result == OC_STACK_OK)
+ if (requestResult == OC_STACK_SLOW_RESOURCE)
+ {
+ if (requestInfo->info.type == CA_MSG_CONFIRM)
{
- result = ProcessRequest(resHandling, resource, request);
+ SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
+ CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
+ CA_RESPONSE_DATA);
}
}
- else
+ if (requestResult == OC_STACK_RESOURCE_ERROR
+ && serverRequest.observationOption == OC_OBSERVE_REGISTER)
{
- OC_LOG(INFO, TAG, "This Server Request is incomplete");
- result = OC_STACK_CONTINUE;
+ OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
}
- return result;
+ else if(!OCResultToSuccess(requestResult))
+ {
+ OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
+
+ CAResponseResult_t stackResponse =
+ OCToCAStackResult(requestResult, serverRequest.method);
+
+ SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
+ requestInfo->info.type, requestInfo->info.numOptions,
+ requestInfo->info.options, requestInfo->info.token,
+ requestInfo->info.tokenLength, requestInfo->info.resourceUri,
+ CA_RESPONSE_DATA);
+ }
+ // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
+ // The token is copied in there, and is thus still owned by this function.
+ OICFree(serverRequest.payload);
+ OICFree(serverRequest.requestToken);
+ OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
}
-bool validatePlatformInfo(OCPlatformInfo info)
+//This function will be called back by CA layer when a request is received
+void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
{
-
- if (!info.platformID)
+ OIC_LOG(INFO, TAG, "Enter HandleCARequests");
+ if(!endPoint)
{
- OC_LOG(ERROR, TAG, "No platform ID found.");
- return false;
+ OIC_LOG(ERROR, TAG, "endPoint is NULL");
+ return;
}
- if (info.manufacturerName)
+ if(!requestInfo)
{
- size_t lenManufacturerName = strlen(info.manufacturerName);
-
- if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
- {
- OC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
- return false;
- }
+ OIC_LOG(ERROR, TAG, "requestInfo is NULL");
+ return;
}
- else
+
+#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
+#ifdef ROUTING_GATEWAY
+ bool needRIHandling = false;
+ bool isEmptyMsg = false;
+ /*
+ * Routing manager is going to update either of endpoint or request or both.
+ * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
+ * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
+ * destination. It can also remove "RM" coap header option before passing request / response to
+ * RI as this option will make no sense to either RI or application.
+ */
+ OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
+ &needRIHandling, &isEmptyMsg);
+ if(OC_STACK_OK != ret || !needRIHandling)
{
- OC_LOG(ERROR, TAG, "No manufacturer name present");
- return false;
+ OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
+ return;
}
+#endif
+
+ /*
+ * Put source in sender endpoint so that the next packet from application can be routed to
+ * proper destination and remove RM header option.
+ */
+ RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
+ (uint8_t *) &(requestInfo->info.numOptions),
+ (CAEndpoint_t *) endPoint);
- if (info.manufacturerUrl)
+#ifdef ROUTING_GATEWAY
+ if (isEmptyMsg)
+ {
+ /*
+ * In Gateways, the MSGType in route option is used to check if the actual
+ * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
+ * EMPTY response is sent in the form of POST request which need to be changed
+ * to a EMPTY response by RM. This translation is done in this part of the code.
+ */
+ OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
+ CAResponseInfo_t respInfo = {.result = CA_EMPTY,
+ .info.messageId = requestInfo->info.messageId,
+ .info.type = CA_MSG_ACKNOWLEDGE};
+ OCHandleResponse(endPoint, &respInfo);
+ }
+ else
+#endif
+#endif
{
- if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
- {
- OC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
- return false;
- }
+ // Normal handling of the packet
+ OCHandleRequests(endPoint, requestInfo);
}
- return true;
+ OIC_LOG(INFO, TAG, "Exit HandleCARequests");
}
//-----------------------------------------------------------------------------
{
if(stackState == OC_STACK_INITIALIZED)
{
- OC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
+ OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
OCStop() between them are ignored.");
return OC_STACK_OK;
}
#ifndef ROUTING_GATEWAY
if (OC_GATEWAY == mode)
{
- OC_LOG(ERROR, TAG, "Routing Manager not supported");
+ OIC_LOG(ERROR, TAG, "Routing Manager not supported");
return OC_STACK_INVALID_PARAM;
}
#endif
#ifdef RA_ADAPTER
if(!gRASetInfo)
{
- OC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
+ OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
return OC_STACK_ERROR;
}
#endif
OCStackResult result = OC_STACK_ERROR;
- OC_LOG(INFO, TAG, "Entering OCInit");
+ OIC_LOG(INFO, TAG, "Entering OCInit");
// Validate mode
if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
|| (mode == OC_GATEWAY)))
{
- OC_LOG(ERROR, TAG, "Invalid mode");
+ OIC_LOG(ERROR, TAG, "Invalid mode");
return OC_STACK_ERROR;
}
myStackMode = mode;
defaultDeviceHandler = NULL;
defaultDeviceHandlerCallbackParameter = NULL;
+ result = InitializeScheduleResourceList();
+ VERIFY_SUCCESS(result, OC_STACK_OK);
+
result = CAResultToOCResult(CAInitialize());
VERIFY_SUCCESS(result, OC_STACK_OK);
result = CAResultToOCResult(OCSelectNetwork());
VERIFY_SUCCESS(result, OC_STACK_OK);
+ result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
+ OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
+ VERIFY_SUCCESS(result, OC_STACK_OK);
+
switch (myStackMode)
{
case OC_CLIENT:
CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
result = CAResultToOCResult(CAStartDiscoveryServer());
- OC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
+ OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
break;
case OC_SERVER:
SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
result = CAResultToOCResult(CAStartListeningServer());
- OC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
+ OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
break;
case OC_CLIENT_SERVER:
case OC_GATEWAY:
}
VERIFY_SUCCESS(result, OC_STACK_OK);
+#ifdef TCP_ADAPTER
+ CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
+#endif
+
#ifdef WITH_PRESENCE
PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
#endif // WITH_PRESENCE
result = SRMInitPolicyEngine();
// TODO after BeachHead delivery: consolidate into single SRMInit()
}
-
+#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
+ RMSetStackMode(mode);
#ifdef ROUTING_GATEWAY
if (OC_GATEWAY == myStackMode)
{
result = RMInitialize();
}
#endif
+#endif
+
+#ifdef TCP_ADAPTER
+ if (result == OC_STACK_OK)
+ {
+ result = InitializeKeepAlive(myStackMode);
+ }
+#endif
exit:
if(result != OC_STACK_OK)
{
- OC_LOG(ERROR, TAG, "Stack initialization error");
+ OIC_LOG(ERROR, TAG, "Stack initialization error");
+ TerminateScheduleResourceList();
deleteAllResources();
CATerminate();
stackState = OC_STACK_UNINITIALIZED;
OCStackResult OCStop()
{
- OC_LOG(INFO, TAG, "Entering OCStop");
+ OIC_LOG(INFO, TAG, "Entering OCStop");
if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
{
- OC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
+ OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
return OC_STACK_OK;
}
else if (stackState != OC_STACK_INITIALIZED)
{
- OC_LOG(ERROR, TAG, "Stack not initialized");
+ OIC_LOG(ERROR, TAG, "Stack not initialized");
return OC_STACK_ERROR;
}
stackState = OC_STACK_UNINIT_IN_PROGRESS;
+ CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
+ OCDefaultConnectionStateChangedHandler);
+
#ifdef WITH_PRESENCE
// Ensure that the TTL associated with ANY and ALL presence notifications originating from
// here send with the code "OC_STACK_PRESENCE_STOPPED" result.
}
#endif
- // Free memory dynamically allocated for resources
- deleteAllResources();
- DeleteDeviceInfo();
- DeletePlatformInfo();
- CATerminate();
+#ifdef TCP_ADAPTER
+ TerminateKeepAlive(myStackMode);
+#endif
+
+ TerminateScheduleResourceList();
// Remove all observers
DeleteObserverList();
+ // Free memory dynamically allocated for resources
+ deleteAllResources();
// Remove all the client callbacks
DeleteClientCBList();
+ // Terminate connectivity-abstraction layer.
+ CATerminate();
// De-init the SRM Policy Engine
// TODO after BeachHead delivery: consolidate into single SRMDeInit()
SRMDeInitPolicyEngine();
-
stackState = OC_STACK_UNINITIALIZED;
return OC_STACK_OK;
}
{
if(stackState != OC_STACK_INITIALIZED)
{
- OC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
+ OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
return OC_STACK_ERROR;
}
CAResult_t ret = CAStartListeningServer();
if (CA_STATUS_OK != ret)
{
- OC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
+ OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
return OC_STACK_ERROR;
}
return OC_STACK_OK;
CAResult_t ret = CAStopListeningServer();
if (CA_STATUS_OK != ret)
{
- OC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
+ OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
return OC_STACK_ERROR;
}
return OC_STACK_OK;
}
}
-OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
-{
- char *query;
-
- query = strchr (inputUri, '?');
-
- if (query != NULL)
- {
- if((query - inputUri) > MAX_URI_LENGTH)
- {
- return OC_STACK_INVALID_URI;
- }
-
- if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
- {
- return OC_STACK_INVALID_QUERY;
- }
- }
- else if(uriLen > MAX_URI_LENGTH)
- {
- return OC_STACK_INVALID_URI;
- }
- return OC_STACK_OK;
-}
-
/**
* A request uri consists of the following components in order:
* example
* optionally one of
* CoAP over UDP prefix "coap://"
* CoAP over TCP prefix "coap+tcp://"
+ * CoAP over DTLS prefix "coaps://"
+ * CoAP over TLS prefix "coaps+tcp://"
* optionally one of
* IPv6 address "[1234::5678]"
* IPv4 address "192.168.1.1"
bool istcp = false;
if (prefixLen)
{
- if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
+ if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
+ || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
{
istcp = true;
}
{
colon = close + 1;
}
- adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
+
+ if (istcp)
+ {
+ adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
+ }
+ else
+ {
+ adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
+ }
flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
}
else
end = (colon && colon < slash) ? colon : slash;
if (istcp)
- { // coap over tcp
+ {
+ // coap over tcp
adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
}
else
{
adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
- flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
}
+ flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
}
else
{ // MAC address
{
return OC_STACK_NO_MEMORY;
}
- OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
+
+ // Decode address per RFC 6874.
+ result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
+ if (result != OC_STACK_OK)
+ {
+ OICFree(*devAddr);
+ return result;
+ }
+
da->port = port;
da->adapter = adapter;
da->flags = flags;
- if (!strncmp(fullUri, "coaps:", 6))
+ if (!strncmp(fullUri, "coaps", 5))
{
da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
}
}
static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
- char *resourceUri, char **requestUri)
+ char **requestUri,
+ bool isMulticast)
{
char uri[CA_MAX_URI_LENGTH];
- FormCanonicalPresenceUri(endpoint, resourceUri, uri);
+ FormCanonicalPresenceUri(endpoint, uri, isMulticast);
*requestUri = OICStrdup(uri);
if (!*requestUri)
OCHeaderOption *options,
uint8_t numOptions)
{
- OC_LOG(INFO, TAG, "Entering OCDoResource");
+ OIC_LOG(INFO, TAG, "Entering OCDoResource");
// Validate input parameters
VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
- VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
OCStackResult result = OC_STACK_ERROR;
CAResult_t caResult;
char *resourceUri = NULL;
char *resourceType = NULL;
- // This validation is broken, but doesn't cause harm
- size_t uriLen = strlen(requestUri );
- if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
- {
- goto exit;
- }
-
/*
* Support original behavior with address on resourceUri argument.
*/
adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
- result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
-
- if (result != OC_STACK_OK)
+ if (requestUri)
+ {
+ result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
+ if (result != OC_STACK_OK)
+ {
+ OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
+ goto exit;
+ }
+ }
+ else if (!checkProxyUri(options, numOptions))
{
- OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
+ OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
goto exit;
}
case OC_REST_GET:
case OC_REST_OBSERVE:
case OC_REST_OBSERVE_ALL:
- case OC_REST_CANCEL_OBSERVE:
requestInfo.method = CA_GET;
break;
case OC_REST_PUT:
break;
case OC_REST_DISCOVER:
qos = OC_LOW_QOS;
+#ifdef WITH_PRESENCE
+ case OC_REST_PRESENCE:
+#endif
if (destination || devAddr)
{
requestInfo.isMulticast = false;
destination = &tmpDevAddr;
requestInfo.isMulticast = true;
}
- // CA_DISCOVER will become GET and isMulticast
- requestInfo.method = CA_GET;
- break;
-#ifdef WITH_PRESENCE
- case OC_REST_PRESENCE:
- // Replacing method type with GET because "presence"
- // is a stack layer only implementation.
+ // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
+ // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
+ // replacing method type with GET.
requestInfo.method = CA_GET;
break;
-#endif
default:
result = OC_STACK_INVALID_METHOD;
goto exit;
if (!devAddr && !destination)
{
- OC_LOG(DEBUG, TAG, "no devAddr and no destination");
+ OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
result = OC_STACK_INVALID_PARAM;
goto exit;
}
caResult = CAGenerateToken(&token, tokenLength);
if (caResult != CA_STATUS_OK)
{
- OC_LOG(ERROR, TAG, "CAGenerateToken error");
+ OIC_LOG(ERROR, TAG, "CAGenerateToken error");
result= OC_STACK_ERROR;
goto exit;
}
requestInfo.info.type = qualityOfServiceToMessageType(qos);
requestInfo.info.token = token;
requestInfo.info.tokenLength = tokenLength;
- requestInfo.info.resourceUri = resourceUri;
if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
{
OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
!= OC_STACK_OK)
{
- OC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
+ OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
goto exit;
}
requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
}
- if (result != OC_STACK_OK)
- {
- OC_LOG(ERROR, TAG, "CACreateEndpoint error");
- goto exit;
- }
-
// prepare for response
#ifdef WITH_PRESENCE
if (method == OC_REST_PRESENCE)
{
char *presenceUri = NULL;
- result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
+ result = OCPreparePresence(&endpoint, &presenceUri,
+ requestInfo.isMulticast);
if (OC_STACK_OK != result)
{
goto exit;
// Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
// Presence notification will form a canonical uri to
// look for callbacks into the application.
+ if (resourceUri)
+ {
+ OICFree(resourceUri);
+ }
resourceUri = presenceUri;
}
#endif
+ // update resourceUri onto requestInfo after check presence uri
+ requestInfo.info.resourceUri = resourceUri;
+
ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
method, devAddr, resourceUri, resourceType, ttl);
resourceUri = NULL; // Client CB list entry now owns it
resourceType = NULL; // Client CB list entry now owns it
+#ifdef WITH_PRESENCE
+ if (method == OC_REST_PRESENCE)
+ {
+ OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
+
+ if (handle)
+ {
+ *handle = resHandle;
+ }
+
+ goto exit;
+ }
+#endif
+
// send request
result = OCSendRequest(&endpoint, &requestInfo);
if (OC_STACK_OK != result)
exit:
if (result != OC_STACK_OK)
{
- OC_LOG(ERROR, TAG, "OCDoResource error");
+ OIC_LOG(ERROR, TAG, "OCDoResource error");
FindAndDeleteClientCB(clientCB);
CADestroyToken(token);
if (handle)
ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
if (!clientCB)
{
- OC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
+ OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
return OC_STACK_ERROR;
}
case OC_REST_OBSERVE:
case OC_REST_OBSERVE_ALL:
- OC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
- clientCB->requestUri);
- if (qos != OC_HIGH_QOS)
+ OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
+
+ CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
+
+ if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
{
FindAndDeleteClientCB(clientCB);
break;
}
- OC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
+ OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
requestInfo.info.type = qualityOfServiceToMessageType(qos);
requestInfo.info.token = clientCB->token;
requestInfo.info.numOptions = numOptions + 1;
requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
- CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
ret = OCSendRequest(&endpoint, &requestInfo);
break;
case OC_REST_DISCOVER:
- OC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
+ OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
clientCB->requestUri);
FindAndDeleteClientCB(clientCB);
break;
*/
OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
{
- OC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
+ OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
if(!persistentStorageHandler)
{
- OC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
+ OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
return OC_STACK_INVALID_PARAM;
}
else
!persistentStorageHandler->unlink ||
!persistentStorageHandler->write)
{
- OC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
+ OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
return OC_STACK_INVALID_PARAM;
}
}
// the following line floods the log with messages that are irrelevant
// to most purposes. Uncomment as needed.
- //OC_LOG(INFO, TAG, "Entering RequestPresence");
+ //OIC_LOG(INFO, TAG, "Entering RequestPresence");
ClientCB* cbNode = NULL;
OCClientResponse clientResponse;
OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
}
uint32_t now = GetTicks(0);
- OC_LOG_V(DEBUG, TAG, "this TTL level %d",
+ OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
cbNode->presence->TTLlevel);
- OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
+ OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
{
if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
{
- OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
+ OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
}
if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
{
- OC_LOG(DEBUG, TAG, "No more timeout ticks");
+ OIC_LOG(DEBUG, TAG, "No more timeout ticks");
clientResponse.sequenceNumber = 0;
clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
// Increment the TTLLevel (going to a next state), so we don't keep
// sending presence notification to client.
cbNode->presence->TTLlevel++;
- OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
+ OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
cbNode->presence->TTLlevel);
cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
CARequestInfo_t requestInfo = {.method = CA_GET};
- OC_LOG(DEBUG, TAG, "time to test server presence");
+ OIC_LOG(DEBUG, TAG, "time to test server presence");
CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
}
cbNode->presence->TTLlevel++;
- OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
+ OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
}
exit:
if (result != OC_STACK_OK)
{
- OC_LOG(ERROR, TAG, "OCProcessPresence error");
+ OIC_LOG(ERROR, TAG, "OCProcessPresence error");
}
return result;
#ifdef ROUTING_GATEWAY
RMProcess();
#endif
+
+#ifdef TCP_ADAPTER
+ ProcessKeepAlive();
+#endif
return OC_STACK_OK;
}
#ifdef WITH_PRESENCE
OCStackResult OCStartPresence(const uint32_t ttl)
{
+ OIC_LOG(INFO, TAG, "Entering OCStartPresence");
uint8_t tokenLength = CA_MAX_TOKEN_LEN;
OCChangeResourceProperty(
&(((OCResource *)presenceResource.handle)->resourceProperties),
if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
{
presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
- OC_LOG(INFO, TAG, "Setting Presence TTL to max value");
+ OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
}
else if (0 == ttl)
{
presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
- OC_LOG(INFO, TAG, "Setting Presence TTL to default value");
+ OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
}
else
{
presenceResource.presenceTTL = ttl;
}
- OC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
+ OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
if (OC_PRESENCE_UNINITIALIZED == presenceState)
{
CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
if (caResult != CA_STATUS_OK)
{
- OC_LOG(ERROR, TAG, "CAGenerateToken error");
+ OIC_LOG(ERROR, TAG, "CAGenerateToken error");
CADestroyToken(caToken);
return OC_STACK_ERROR;
}
OCStackResult OCStopPresence()
{
+ OIC_LOG(INFO, TAG, "Entering OCStopPresence");
OCStackResult result = OC_STACK_ERROR;
if(presenceResource.handle)
if(result != OC_STACK_OK)
{
- OC_LOG(ERROR, TAG,
+ OIC_LOG(ERROR, TAG,
"Changing the presence resource properties to ACTIVE not successful");
return result;
}
return OC_STACK_OK;
}
-OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
-{
- OC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
-
- if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
- {
- if (validatePlatformInfo(platformInfo))
- {
- return SavePlatformInfo(platformInfo);
- }
- else
- {
- return OC_STACK_INVALID_PARAM;
- }
- }
- else
- {
- return OC_STACK_ERROR;
- }
-}
-
-OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
-{
- OC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
-
- if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
- {
- OC_LOG(ERROR, TAG, "Null or empty device name.");
- return OC_STACK_INVALID_PARAM;
- }
-
- return SaveDeviceInfo(deviceInfo);
-}
-
OCStackResult OCCreateResource(OCResourceHandle *handle,
const char *resourceTypeName,
const char *resourceInterfaceName,
OCResource *pointer = NULL;
OCStackResult result = OC_STACK_ERROR;
- OC_LOG(INFO, TAG, "Entering OCCreateResource");
+ OIC_LOG(INFO, TAG, "Entering OCCreateResource");
if(myStackMode == OC_CLIENT)
{
// Validate parameters
if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
{
- OC_LOG(ERROR, TAG, "URI is empty or too long");
+ OIC_LOG(ERROR, TAG, "URI is empty or too long");
return OC_STACK_INVALID_URI;
}
// Is it presented during resource discovery?
if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
{
- OC_LOG(ERROR, TAG, "Input parameter is NULL");
+ OIC_LOG(ERROR, TAG, "Input parameter is NULL");
return OC_STACK_INVALID_PARAM;
}
- if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
+ if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
{
resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
}
+#ifdef MQ_PUBLISHER
+ resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
+#endif
// Make sure resourceProperties bitmask has allowed properties specified
if (resourceProperties
> (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
- OC_EXPLICIT_DISCOVERABLE))
+ OC_EXPLICIT_DISCOVERABLE
+#ifdef MQ_PUBLISHER
+ | OC_MQ_PUBLISHER
+#endif
+#ifdef MQ_BROKER
+ | OC_MQ_BROKER
+#endif
+ ))
{
- OC_LOG(ERROR, TAG, "Invalid property");
+ OIC_LOG(ERROR, TAG, "Invalid property");
return OC_STACK_INVALID_PARAM;
}
{
if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
{
- OC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
+ OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
return OC_STACK_INVALID_PARAM;
}
pointer = pointer->next;
result = BindResourceTypeToResource(pointer, resourceTypeName);
if (result != OC_STACK_OK)
{
- OC_LOG(ERROR, TAG, "Error adding resourcetype");
+ OIC_LOG(ERROR, TAG, "Error adding resourcetype");
goto exit;
}
result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
if (result != OC_STACK_OK)
{
- OC_LOG(ERROR, TAG, "Error adding resourceinterface");
+ OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
goto exit;
}
pointer->entityHandlerCallbackParam = NULL;
}
+ // Initialize a pointer indicating child resources in case of collection
+ pointer->rsrcChildResourcesHead = NULL;
+
*handle = pointer;
result = OC_STACK_OK;
return result;
}
-
OCStackResult OCBindResource(
OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
{
OCResource *resource = NULL;
- uint8_t i = 0;
+ OCChildResource *tempChildResource = NULL;
+ OCChildResource *newChildResource = NULL;
- OC_LOG(INFO, TAG, "Entering OCBindResource");
+ OIC_LOG(INFO, TAG, "Entering OCBindResource");
// Validate parameters
VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
// Container cannot contain itself
if (collectionHandle == resourceHandle)
{
- OC_LOG(ERROR, TAG, "Added handle equals collection handle");
+ OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
return OC_STACK_INVALID_PARAM;
}
resource = findResource((OCResource *) collectionHandle);
if (!resource)
{
- OC_LOG(ERROR, TAG, "Collection handle not found");
+ OIC_LOG(ERROR, TAG, "Collection handle not found");
return OC_STACK_INVALID_PARAM;
}
// Look for an open slot to add add the child resource.
// If found, add it and return success
- for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
+
+ tempChildResource = resource->rsrcChildResourcesHead;
+
+ while(resource->rsrcChildResourcesHead && tempChildResource->next)
{
- if (!resource->rsrcResources[i])
- {
- resource->rsrcResources[i] = (OCResource *) resourceHandle;
- OC_LOG(INFO, TAG, "resource bound");
+ // TODO: what if one of child resource was deregistered without unbinding?
+ tempChildResource = tempChildResource->next;
+ }
-#ifdef WITH_PRESENCE
- if (presenceResource.handle)
- {
- ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
- SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
- OC_PRESENCE_TRIGGER_CHANGE);
- }
-#endif
- return OC_STACK_OK;
+ // Do memory allocation for child resource
+ newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
+ if(!newChildResource)
+ {
+ OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
+ return OC_STACK_ERROR;
+ }
- }
+ newChildResource->rsrcResource = (OCResource *) resourceHandle;
+ newChildResource->next = NULL;
+
+ if(!resource->rsrcChildResourcesHead)
+ {
+ resource->rsrcChildResourcesHead = newChildResource;
+ }
+ else {
+ tempChildResource->next = newChildResource;
}
- // Unable to add resourceHandle, so return error
- return OC_STACK_ERROR;
+ OIC_LOG(INFO, TAG, "resource bound");
+
+#ifdef WITH_PRESENCE
+ if (presenceResource.handle)
+ {
+ ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
+ SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
+ OC_PRESENCE_TRIGGER_CHANGE);
+ }
+#endif
+
+ return OC_STACK_OK;
}
OCStackResult OCUnBindResource(
OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
{
OCResource *resource = NULL;
- uint8_t i = 0;
+ OCChildResource *tempChildResource = NULL;
+ OCChildResource *tempLastChildResource = NULL;
- OC_LOG(INFO, TAG, "Entering OCUnBindResource");
+ OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
// Validate parameters
VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
// Container cannot contain itself
if (collectionHandle == resourceHandle)
{
- OC_LOG(ERROR, TAG, "removing handle equals collection handle");
+ OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
return OC_STACK_INVALID_PARAM;
}
resource = findResource((OCResource *) collectionHandle);
if (!resource)
{
- OC_LOG(ERROR, TAG, "Collection handle not found");
+ OIC_LOG(ERROR, TAG, "Collection handle not found");
return OC_STACK_INVALID_PARAM;
}
// Look for an open slot to add add the child resource.
// If found, add it and return success
- for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
+ if(!resource->rsrcChildResourcesHead)
+ {
+ OIC_LOG(INFO, TAG, "resource not found in collection");
+
+ // Unable to add resourceHandle, so return error
+ return OC_STACK_ERROR;
+
+ }
+
+ tempChildResource = resource->rsrcChildResourcesHead;
+
+ while (tempChildResource)
{
- if (resourceHandle == resource->rsrcResources[i])
+ if(tempChildResource->rsrcResource == resourceHandle)
{
- resource->rsrcResources[i] = (OCResource *) NULL;
- OC_LOG(INFO, TAG, "resource unbound");
+ // if resource going to be unbinded is the head one.
+ if( tempChildResource == resource->rsrcChildResourcesHead )
+ {
+ OCChildResource *temp = resource->rsrcChildResourcesHead->next;
+ OICFree(resource->rsrcChildResourcesHead);
+ resource->rsrcChildResourcesHead = temp;
+ temp = NULL;
+ }
+ else
+ {
+ OCChildResource *temp = tempChildResource->next;
+ OICFree(tempChildResource);
+ tempLastChildResource->next = temp;
+ temp = NULL;
+ }
+
+ OIC_LOG(INFO, TAG, "resource unbound");
// Send notification when resource is unbounded successfully.
#ifdef WITH_PRESENCE
OC_PRESENCE_TRIGGER_CHANGE);
}
#endif
+ tempChildResource = NULL;
+ tempLastChildResource = NULL;
+
return OC_STACK_OK;
+
}
+
+ tempLastChildResource = tempChildResource;
+ tempChildResource = tempChildResource->next;
}
- OC_LOG(INFO, TAG, "resource not found in collection");
+ OIC_LOG(INFO, TAG, "resource not found in collection");
+
+ tempChildResource = NULL;
+ tempLastChildResource = NULL;
// Unable to add resourceHandle, so return error
return OC_STACK_ERROR;
}
-// Precondition is that the parameter has been checked to not equal NULL.
static bool ValidateResourceTypeInterface(const char *resourceItemName)
{
- if (resourceItemName[0] < 'a' || resourceItemName[0] > 'z')
+ if (!resourceItemName)
{
return false;
}
-
- size_t index = 1;
- while (resourceItemName[index] != '\0')
+ // Per RFC 6690 only registered values must follow the first rule below.
+ // At this point in time the only values registered begin with "core", and
+ // all other values are specified as opaque strings where multiple values
+ // are separated by a space.
+ if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
{
- if (resourceItemName[index] != '.' &&
- resourceItemName[index] != '-' &&
- (resourceItemName[index] < 'a' || resourceItemName[index] > 'z') &&
- (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
+ for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
{
- return false;
+ if (resourceItemName[index] != '.'
+ && resourceItemName[index] != '-'
+ && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
+ && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
+ {
+ return false;
+ }
+ }
+ }
+ else
+ {
+ for (size_t index = 0; resourceItemName[index]; ++index)
+ {
+ if (resourceItemName[index] == ' '
+ || resourceItemName[index] == '\t'
+ || resourceItemName[index] == '\r'
+ || resourceItemName[index] == '\n')
+ {
+ return false;
+ }
}
- ++index;
}
return true;
}
+
OCStackResult BindResourceTypeToResource(OCResource* resource,
const char *resourceTypeName)
{
if (!ValidateResourceTypeInterface(resourceTypeName))
{
- OC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
+ OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
return OC_STACK_INVALID_PARAM;
}
goto exit;
}
pointer->resourcetypename = str;
+ pointer->next = NULL;
insertResourceType(resource, pointer);
result = OC_STACK_OK;
- exit:
+exit:
if (result != OC_STACK_OK)
{
OICFree(pointer);
if (!ValidateResourceTypeInterface(resourceInterfaceName))
{
- OC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
+ OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
return OC_STACK_INVALID_PARAM;
}
- OC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
+ OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
if (!pointer)
resource = findResource((OCResource *) handle);
if (!resource)
{
- OC_LOG(ERROR, TAG, "Resource not found");
+ OIC_LOG(ERROR, TAG, "Resource not found");
return OC_STACK_ERROR;
}
resource = findResource((OCResource *) handle);
if (!resource)
{
- OC_LOG(ERROR, TAG, "Resource not found");
+ OIC_LOG(ERROR, TAG, "Resource not found");
return OC_STACK_ERROR;
}
{
if (!handle)
{
- OC_LOG(ERROR, TAG, "Invalid handle for deletion");
+ OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
return OC_STACK_INVALID_PARAM;
}
OCResource *resource = findResource((OCResource *) handle);
if (resource == NULL)
{
- OC_LOG(ERROR, TAG, "Resource not found");
+ OIC_LOG(ERROR, TAG, "Resource not found");
return OC_STACK_NO_RESOURCE;
}
if (deleteResource((OCResource *) handle) != OC_STACK_OK)
{
- OC_LOG(ERROR, TAG, "Error deleting resource");
+ OIC_LOG(ERROR, TAG, "Error deleting resource");
return OC_STACK_ERROR;
}
uint8_t index)
{
OCResource *resource = NULL;
+ OCChildResource *tempChildResource = NULL;
+ uint8_t num = 0;
- if (index >= MAX_CONTAINED_RESOURCES)
+ resource = findResource((OCResource *) collectionHandle);
+ if (!resource)
{
return NULL;
}
- resource = findResource((OCResource *) collectionHandle);
- if (!resource)
+ tempChildResource = resource->rsrcChildResourcesHead;
+
+ while(tempChildResource)
{
- return NULL;
+ if( num == index )
+ {
+ return tempChildResource->rsrcResource;
+ }
+ num++;
+ tempChildResource = tempChildResource->next;
}
- return resource->rsrcResources[index];
+ // In this case, the number of resource handles in the collection exceeds the index
+ tempChildResource = NULL;
+ return NULL;
}
OCStackResult OCBindResourceHandler(OCResourceHandle handle,
resource = findResource((OCResource *)handle);
if (!resource)
{
- OC_LOG(ERROR, TAG, "Resource not found");
+ OIC_LOG(ERROR, TAG, "Resource not found");
return OC_STACK_ERROR;
}
resource = findResource((OCResource *)handle);
if (!resource)
{
- OC_LOG(ERROR, TAG, "Resource not found");
+ OIC_LOG(ERROR, TAG, "Resource not found");
return NULL;
}
OCStackResult SendPresenceNotification(OCResourceType *resourceType,
OCPresenceTrigger trigger)
{
+ OIC_LOG(INFO, TAG, "SendPresenceNotification");
OCResource *resPtr = NULL;
OCStackResult result = OC_STACK_ERROR;
OCMethod method = OC_REST_PRESENCE;
OCStackResult SendStopNotification()
{
+ OIC_LOG(INFO, TAG, "SendStopNotification");
OCResource *resPtr = NULL;
OCStackResult result = OC_STACK_ERROR;
OCMethod method = OC_REST_PRESENCE;
OCMethod method = OC_REST_NOMETHOD;
uint32_t maxAge = 0;
- OC_LOG(INFO, TAG, "Notifying all observers");
+ OIC_LOG(INFO, TAG, "Notifying all observers");
#ifdef WITH_PRESENCE
if(handle == presenceResource.handle)
{
const OCRepPayload *payload,
OCQualityOfService qos)
{
- OC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
+ OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
OCResource *resPtr = NULL;
//TODO: we should allow the server to define this
OCStackResult result = OC_STACK_ERROR;
OCServerRequest *serverRequest = NULL;
- OC_LOG(INFO, TAG, "Entering OCDoResponse");
+ OIC_LOG(INFO, TAG, "Entering OCDoResponse");
// Validate input parameters
VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
// Normal response
// Get pointer to request info
- serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
+ serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
if(serverRequest)
{
// response handler in ocserverrequest.c. Usually HandleSingleResponse.
return result;
}
+//#ifdef DIRECT_PAIRING
+const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
+{
+ OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
+ if(OC_STACK_OK != DPDeviceDiscovery(waittime))
+ {
+ OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
+ return NULL;
+ }
+
+ return (const OCDPDev_t*)DPGetDiscoveredDevices();
+}
+
+const OCDPDev_t* OCGetDirectPairedDevices()
+{
+ return (const OCDPDev_t*)DPGetPairedDevices();
+}
+
+OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
+ OCDirectPairingCB resultCallback)
+{
+ OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
+ if(NULL == peer || NULL == pinNumber)
+ {
+ OIC_LOG(ERROR, TAG, "Invalid parameters");
+ return OC_STACK_INVALID_PARAM;
+ }
+ if (NULL == resultCallback)
+ {
+ OIC_LOG(ERROR, TAG, "Invalid callback");
+ return OC_STACK_INVALID_CALLBACK;
+ }
+
+ return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
+ pinNumber, (OCDirectPairingResultCB)resultCallback);
+}
+//#endif // DIRECT_PAIRING
+
//-----------------------------------------------------------------------------
// Private internal function definitions
//-----------------------------------------------------------------------------
if (resourceProperties
> (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
{
- OC_LOG(ERROR, TAG, "Invalid property");
+ OIC_LOG(ERROR, TAG, "Invalid property");
return OC_STACK_INVALID_PARAM;
}
if(!enable)
if(result == OC_STACK_OK)
{
+ CreateResetProfile();
result = OCCreateResource(&deviceResource,
OC_RSRVD_RESOURCE_TYPE_DEVICE,
OC_RSRVD_INTERFACE_DEFAULT,
NULL,
NULL,
OC_DISCOVERABLE);
+ if(result == OC_STACK_OK)
+ {
+ result = BindResourceInterfaceToResource((OCResource *)deviceResource,
+ OC_RSRVD_INTERFACE_READ);
+ }
}
if(result == OC_STACK_OK)
NULL,
NULL,
OC_DISCOVERABLE);
+ if(result == OC_STACK_OK)
+ {
+ result = BindResourceInterfaceToResource((OCResource *)platformResource,
+ OC_RSRVD_INTERFACE_READ);
+ }
}
return result;
#endif // WITH_PRESENCE
pointer = temp;
}
+ memset(&platformResource, 0, sizeof(platformResource));
+ memset(&deviceResource, 0, sizeof(deviceResource));
+#ifdef MQ_BROKER
+ memset(&brokerResource, 0, sizeof(brokerResource));
+#endif
SRMDeInitSecureResources();
// Ensure that the last resource to be deleted is the presence resource. This allows for all
// presence notification attributed to their deletion to be processed.
deleteResource((OCResource *) presenceResource.handle);
+ memset(&presenceResource, 0, sizeof(presenceResource));
#endif // WITH_PRESENCE
}
OCResource *temp = NULL;
if(!resource)
{
- OC_LOG(DEBUG,TAG,"resource is NULL");
+ OIC_LOG(DEBUG,TAG,"resource is NULL");
return OC_STACK_INVALID_PARAM;
}
- OC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
+ OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
temp = headResource;
while (temp)
OICFree(resource->uri);
deleteResourceType(resource->rsrcType);
deleteResourceInterface(resource->rsrcInterface);
+ OCDeleteResourceAttributes(resource->rsrcAttributes);
}
void deleteResourceType(OCResourceType *resourceType)
}
}
+void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
+{
+ OCAttribute *next = NULL;
+ for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
+ {
+ next = pointer->next;
+ if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
+ {
+ OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
+ }
+ else
+ {
+ OICFree(pointer->attrValue);
+ }
+ OICFree(pointer->attrName);
+ OICFree(pointer);
+ }
+}
+
void insertResourceType(OCResource *resource, OCResourceType *resourceType)
{
OCResourceType *pointer = NULL;
{
if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
{
- OC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
+ OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
OICFree(resourceType->resourcetypename);
OICFree(resourceType);
return;
previous = pointer;
pointer = pointer->next;
}
- previous->next = resourceType;
+
+ if (previous)
+ {
+ previous->next = resourceType;
+ }
}
resourceType->next = NULL;
- OC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
+ OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
}
OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
OCResourceType * rtPointer = resourceTypeList;
while(resourceTypeName && rtPointer)
{
+ OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
if(rtPointer->resourcetypename &&
strcmp(resourceTypeName, (const char *)
(rtPointer->resourcetypename)) == 0)
if (!*firstInterface)
{
- *firstInterface = newInterface;
+ // If first interface is not oic.if.baseline, by default add it as first interface type.
+ if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
+ {
+ *firstInterface = newInterface;
+ }
+ else
+ {
+ OCStackResult result = BindResourceInterfaceToResource(resource,
+ OC_RSRVD_INTERFACE_DEFAULT);
+ if (result != OC_STACK_OK)
+ {
+ OICFree(newInterface->name);
+ OICFree(newInterface);
+ return;
+ }
+ if (*firstInterface)
+ {
+ (*firstInterface)->next = newInterface;
+ }
+ }
}
+ // If once add oic.if.baseline, later too below code take care of freeing memory.
else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
{
if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
OICFree(newInterface);
return;
}
+ // This code will not hit anymore, keeping
else
{
newInterface->next = *firstInterface;
previous = pointer;
pointer = pointer->next;
}
- previous->next = newInterface;
+
+ if (previous)
+ {
+ previous->next = newInterface;
+ }
}
}
return OC_STACK_NO_MEMORY;
}
-const OicUuid_t* OCGetServerInstanceID(void)
+static const OicUuid_t* OCGetServerInstanceID(void)
{
static bool generated = false;
static OicUuid_t sid;
return &sid;
}
- if (GetDoxmDeviceID(&sid) != OC_STACK_OK)
+ if (OC_STACK_OK != GetDoxmDeviceID(&sid))
{
- OC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
+ OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
return NULL;
}
generated = true;
static bool generated = false;
static char sidStr[UUID_STRING_SIZE];
- if(generated)
+ if (generated)
{
return sidStr;
}
- const OicUuid_t* sid = OCGetServerInstanceID();
-
- if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
+ const OicUuid_t *sid = OCGetServerInstanceID();
+ if (sid && OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
{
- OC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
+ OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
return NULL;
}
CATransportAdapter_t connTypes[] = {
CA_ADAPTER_IP,
CA_ADAPTER_RFCOMM_BTEDR,
- CA_ADAPTER_GATT_BTLE
-
+ CA_ADAPTER_GATT_BTLE,
+ CA_ADAPTER_NFC
#ifdef RA_ADAPTER
,CA_ADAPTER_REMOTE_ACCESS
#endif
};
int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
- for(int i = 0; i<numConnTypes; i++)
+ for(int i = 0; i < numConnTypes; i++)
{
- // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
- if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
+ // If CA status is not initialized, CASelectNetwork() will not be called.
+ if (caResult != CA_STATUS_NOT_INITIALIZED)
{
caResult = CASelectNetwork(connTypes[i]);
- if(caResult == CA_STATUS_OK)
+ if (caResult == CA_STATUS_OK)
{
retResult = CA_STATUS_OK;
}
}
}
- if(retResult != CA_STATUS_OK)
+ if (retResult != CA_STATUS_OK)
{
return caResult; // Returns error of appropriate transport that failed fatally.
}
return OC_STACK_ERROR;
}
}
+
+bool OCResultToSuccess(OCStackResult ocResult)
+{
+ switch (ocResult)
+ {
+ case OC_STACK_OK:
+ case OC_STACK_RESOURCE_CREATED:
+ case OC_STACK_RESOURCE_DELETED:
+ case OC_STACK_CONTINUE:
+ case OC_STACK_RESOURCE_CHANGED:
+ case OC_STACK_SLOW_RESOURCE:
+ return true;
+ default:
+ return false;
+ }
+}
+
+#ifdef WITH_CHPROXY
+OCStackResult OCSetProxyURI(const char *uri)
+{
+ return CAResultToOCResult(CASetProxyUri(uri));
+}
+#endif
+
+#if defined(RD_CLIENT) || defined(RD_SERVER)
+OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
+{
+ VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
+
+ OCResource *resource = NULL;
+
+ resource = findResource((OCResource *) handle);
+ if (!resource)
+ {
+ OIC_LOG(ERROR, TAG, "Resource not found");
+ return OC_STACK_ERROR;
+ }
+
+ resource->ins = ins;
+
+ return OC_STACK_OK;
+}
+
+
+OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
+ const OCClientResponse *response)
+{
+ // Validate input parameters
+ VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
+ VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
+
+ char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
+ if (!targetUri)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+ strncpy(targetUri, requestUri, strlen(requestUri) + 1);
+
+ if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
+ {
+ OIC_LOG(DEBUG, TAG, "update the ins of published resource");
+
+ char rdPubUri[MAX_URI_LENGTH] = { 0 };
+ snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
+ OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
+
+ if (strcmp(rdPubUri, targetUri) == 0)
+ {
+ // Update resource unique id in stack.
+ if (response)
+ {
+ if (response->payload)
+ {
+ OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
+ OCRepPayload **links = NULL;
+ size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
+ if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
+ &links, dimensions))
+ {
+ size_t i = 0;
+ for (; i < dimensions[0]; i++)
+ {
+ char *uri = NULL;
+ if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
+ {
+ OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
+ int64_t ins = 0;
+ if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
+ {
+ OCBindResourceInsToResource(handle, ins);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
+ {
+ OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
+
+ uint8_t numResources = 0;
+ OCGetNumberOfResources(&numResources);
+
+ char *ins = strstr(targetUri, OC_RSRVD_INS);
+ if (!ins)
+ {
+ for (uint8_t i = 0; i < numResources; i++)
+ {
+ OCResourceHandle resHandle = OCGetResourceHandle(i);
+ if (resHandle)
+ {
+ OCBindResourceInsToResource(resHandle, 0);
+ }
+ }
+ }
+ else
+ {
+ const char *token = "&";
+ char *iterTokenPtr = NULL;
+ char *start = strtok_r(targetUri, token, &iterTokenPtr);
+
+ while (start != NULL)
+ {
+ char *query = start;
+ query = strstr(query, OC_RSRVD_INS);
+ if (query)
+ {
+ uint8_t queryIns = atoi(query + 4);
+ for (uint8_t i = 0; i < numResources; i++)
+ {
+ OCResourceHandle resHandle = OCGetResourceHandle(i);
+ if (resHandle)
+ {
+ uint8_t resIns = 0;
+ OCGetResourceIns(resHandle, &resIns);
+ if (queryIns && queryIns == resIns)
+ {
+ OCBindResourceInsToResource(resHandle, 0);
+ break;
+ }
+ }
+ }
+ }
+ start = strtok_r(NULL, token, &iterTokenPtr);
+ }
+ }
+ }
+
+ OICFree(targetUri);
+ return OC_STACK_OK;
+}
+
+OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
+{
+ if (!uri)
+ {
+ OIC_LOG(ERROR, TAG, "Resource uri is NULL");
+ return NULL;
+ }
+
+ OCResource *pointer = headResource;
+
+ while (pointer)
+ {
+ if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
+ {
+ OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
+ return pointer;
+ }
+ pointer = pointer->next;
+ }
+ return NULL;
+}
+
+OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
+{
+ OCResource *resource = NULL;
+
+ VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
+ VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
+
+ resource = findResource((OCResource *) handle);
+ if (resource)
+ {
+ *ins = resource->ins;
+ return OC_STACK_OK;
+ }
+ return OC_STACK_ERROR;
+}
+#endif
+
+OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
+ void* optionData, size_t optionDataLength)
+{
+ if (!ocHdrOpt)
+ {
+ OIC_LOG (INFO, TAG, "Header options are NULL");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ if (!optionData)
+ {
+ OIC_LOG (INFO, TAG, "optionData are NULL");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ if (!numOptions)
+ {
+ OIC_LOG (INFO, TAG, "numOptions is NULL");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ if (*numOptions >= MAX_HEADER_OPTIONS)
+ {
+ OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
+ return OC_STACK_NO_MEMORY;
+ }
+
+ ocHdrOpt += *numOptions;
+ ocHdrOpt->protocolID = OC_COAP_ID;
+ ocHdrOpt->optionID = optionID;
+ ocHdrOpt->optionLength =
+ optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
+ optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
+ memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
+ *numOptions += 1;
+
+ return OC_STACK_OK;
+}
+
+OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
+ void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
+{
+ if (!ocHdrOpt || !numOptions)
+ {
+ OIC_LOG (INFO, TAG, "No options present");
+ return OC_STACK_OK;
+ }
+
+ if (!optionData)
+ {
+ OIC_LOG (INFO, TAG, "optionData are NULL");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ if (!receivedDataLength)
+ {
+ OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ for (uint8_t i = 0; i < numOptions; i++)
+ {
+ if (ocHdrOpt[i].optionID == optionID)
+ {
+ if (optionDataLength >= ocHdrOpt->optionLength)
+ {
+ memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
+ *receivedDataLength = ocHdrOpt->optionLength;
+ return OC_STACK_OK;
+ }
+ else
+ {
+ OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
+ return OC_STACK_ERROR;
+ }
+ }
+ }
+ return OC_STACK_OK;
+}
+
+void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
+{
+ OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
+ if (g_adapterHandler)
+ {
+ g_adapterHandler(adapter, enabled);
+ }
+}
+
+void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
+{
+ OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
+ if (g_connectionHandler)
+ {
+ g_connectionHandler(info, isConnected);
+ }
+
+ /*
+ * If the client observes one or more resources over a reliable connection,
+ * then the CoAP server (or intermediary in the role of the CoAP server)
+ * MUST remove all entries associated with the client endpoint from the lists
+ * of observers when the connection is either closed or times out.
+ */
+ if (!isConnected)
+ {
+ OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
+ CopyEndpointToDevAddr(info, &devAddr);
+
+ // remove observer list with remote device address.
+ DeleteObserverUsingDevAddr(&devAddr);
+ }
+}
+
+void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
+ CAConnectionStateChangedCB connectionHandler)
+{
+ OIC_LOG(DEBUG, TAG, "OCSetNetworkMonitorHandler");
+ g_adapterHandler = adapterHandler;
+ g_connectionHandler = connectionHandler;
+}
+
+OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
+{
+ OicUuid_t oicUuid;
+ OCStackResult ret = OC_STACK_ERROR;
+
+ ret = GetDoxmDeviceID(&oicUuid);
+ if (OC_STACK_OK == ret)
+ {
+ memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "Device ID Get error");
+ }
+ return ret;
+}
+
+OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
+{
+ OicUuid_t oicUuid;
+ OCStackResult ret = OC_STACK_ERROR;
+
+ memcpy(&oicUuid, deviceId, UUID_LENGTH);
+ for (int i = 0; i < UUID_LENGTH; i++)
+ {
+ OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
+ }
+ ret = SetDoxmDeviceID(&oicUuid);
+ return ret;
+}