1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //-----------------------------------------------------------------------------
24 //-----------------------------------------------------------------------------
26 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
27 // causes header files to expose definitions
28 // corresponding to the POSIX.1-2001 base
29 // specification (excluding the XSI extension).
30 // For POSIX.1-2001 base specification,
31 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
32 #define _POSIX_C_SOURCE 200112L
33 #ifndef __STDC_FORMAT_MACROS
34 #define __STDC_FORMAT_MACROS
36 #ifndef __STDC_LIMIT_MACROS
37 #define __STDC_LIMIT_MACROS
39 #include "iotivity_config.h"
45 #include "ocstackinternal.h"
46 #include "ocresourcehandler.h"
47 #include "occlientcb.h"
48 #include "ocobserve.h"
50 #include "oic_malloc.h"
51 #include "oic_string.h"
53 #include "ocserverrequest.h"
54 #include "secureresourcemanager.h"
55 #include "psinterface.h"
56 #include "doxmresource.h"
58 #include "cainterface.h"
59 #include "ocpayload.h"
60 #include "ocpayloadcbor.h"
61 #include "cautilinterface.h"
64 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
65 #include "routingutility.h"
66 #ifdef ROUTING_GATEWAY
67 #include "routingmanager.h"
72 #include "oickeepalive.h"
75 //#ifdef DIRECT_PAIRING
76 #include "directpairing.h"
79 #ifdef HAVE_ARDUINO_TIME_H
82 #ifdef HAVE_SYS_TIME_H
85 #include <coap/coap.h>
87 #ifdef HAVE_ARPA_INET_H
88 #include <arpa/inet.h>
92 #define UINT32_MAX (0xFFFFFFFFUL)
95 //-----------------------------------------------------------------------------
97 //-----------------------------------------------------------------------------
100 OC_STACK_UNINITIALIZED = 0,
101 OC_STACK_INITIALIZED,
102 OC_STACK_UNINIT_IN_PROGRESS
108 OC_PRESENCE_UNINITIALIZED = 0,
109 OC_PRESENCE_INITIALIZED
113 //-----------------------------------------------------------------------------
115 //-----------------------------------------------------------------------------
116 static OCStackState stackState = OC_STACK_UNINITIALIZED;
118 OCResource *headResource = NULL;
119 static OCResource *tailResource = NULL;
120 static OCResourceHandle platformResource = {0};
121 static OCResourceHandle deviceResource = {0};
123 static OCResourceHandle brokerResource = {0};
127 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
128 static PresenceResource presenceResource = {0};
129 static uint8_t PresenceTimeOutSize = 0;
130 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
133 static OCMode myStackMode;
135 //TODO: revisit this design
136 static bool gRASetInfo = false;
138 OCDeviceEntityHandler defaultDeviceHandler;
139 void* defaultDeviceHandlerCallbackParameter = NULL;
140 static const char COAP_TCP_SCHEME[] = "coap+tcp:";
141 static const char COAPS_TCP_SCHEME[] = "coaps+tcp:";
142 static const char CORESPEC[] = "core";
144 CAAdapterStateChangedCB g_adapterHandler = NULL;
145 CAConnectionStateChangedCB g_connectionHandler = NULL;
147 //-----------------------------------------------------------------------------
149 //-----------------------------------------------------------------------------
150 #define TAG "OIC_RI_STACK"
151 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
152 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
153 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
154 TAG, #arg " is NULL"); return (retVal); } }
155 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
156 TAG, #arg " is NULL"); return; } }
157 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
160 //TODO: we should allow the server to define this
161 #define MAX_OBSERVE_AGE (0x2FFFFUL)
163 #define MILLISECONDS_PER_SECOND (1000)
165 //-----------------------------------------------------------------------------
166 // Private internal function prototypes
167 //-----------------------------------------------------------------------------
170 * Generate handle of OCDoResource invocation for callback management.
172 * @return Generated OCDoResource handle.
174 static OCDoHandle GenerateInvocationHandle();
177 * Initialize resource data structures, variables, etc.
179 * @return ::OC_STACK_OK on success, some other value upon failure.
181 static OCStackResult initResources();
184 * Add a resource to the end of the linked list of resources.
186 * @param resource Resource to be added
188 static void insertResource(OCResource *resource);
191 * Find a resource in the linked list of resources.
193 * @param resource Resource to be found.
194 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
197 static OCResource *findResource(OCResource *resource);
200 * Insert a resource type into a resource's resource type linked list.
201 * If resource type already exists, it will not be inserted and the
202 * resourceType will be free'd.
203 * resourceType->next should be null to avoid memory leaks.
204 * Function returns silently for null args.
206 * @param resource Resource where resource type is to be inserted.
207 * @param resourceType Resource type to be inserted.
209 static void insertResourceType(OCResource *resource,
210 OCResourceType *resourceType);
213 * Get a resource type at the specified index within a resource.
215 * @param handle Handle of resource.
216 * @param index Index of resource type.
218 * @return Pointer to resource type if found, NULL otherwise.
220 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
224 * Insert a resource interface into a resource's resource interface linked list.
225 * If resource interface already exists, it will not be inserted and the
226 * resourceInterface will be free'd.
227 * resourceInterface->next should be null to avoid memory leaks.
229 * @param resource Resource where resource interface is to be inserted.
230 * @param resourceInterface Resource interface to be inserted.
232 static void insertResourceInterface(OCResource *resource,
233 OCResourceInterface *resourceInterface);
236 * Get a resource interface at the specified index within a resource.
238 * @param handle Handle of resource.
239 * @param index Index of resource interface.
241 * @return Pointer to resource interface if found, NULL otherwise.
243 static OCResourceInterface *findResourceInterfaceAtIndex(
244 OCResourceHandle handle, uint8_t index);
247 * Delete all of the dynamically allocated elements that were created for the resource type.
249 * @param resourceType Specified resource type.
251 static void deleteResourceType(OCResourceType *resourceType);
254 * Delete all of the dynamically allocated elements that were created for the resource interface.
256 * @param resourceInterface Specified resource interface.
258 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
261 * Delete all of the dynamically allocated elements that were created for the resource.
263 * @param resource Specified resource.
265 static void deleteResourceElements(OCResource *resource);
268 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
271 * @param handle Handle of resource to be deleted.
273 * @return ::OC_STACK_OK on success, some other value upon failure.
275 static OCStackResult deleteResource(OCResource *resource);
278 * Delete all of the resources in the resource list.
280 static void deleteAllResources();
283 * Increment resource sequence number. Handles rollover.
285 * @param resPtr Pointer to resource.
287 static void incrementSequenceNumber(OCResource * resPtr);
290 * Attempts to initialize every network interface that the CA Layer might have compiled in.
292 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
293 * return something other than @ref CA_STATUS_OK, then this function fails.
295 * @return ::CA_STATUS_OK on success, some other value upon failure.
297 static CAResult_t OCSelectNetwork();
300 * Get the CoAP ticks after the specified number of milli-seconds.
302 * @param afterMilliSeconds Milli-seconds.
306 static uint32_t GetTicks(uint32_t afterMilliSeconds);
309 * Convert CAResult_t to OCStackResult.
311 * @param caResult CAResult_t code.
312 * @return ::OC_STACK_OK on success, some other value upon failure.
314 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
317 * Convert CAResponseResult_t to OCStackResult.
319 * @param caCode CAResponseResult_t code.
320 * @return ::OC_STACK_OK on success, some other value upon failure.
322 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
325 * Convert OCTransportFlags_t to CATransportModifiers_t.
327 * @param ocConType OCTransportFlags_t input.
328 * @return CATransportFlags
330 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
333 * Convert CATransportFlags_t to OCTransportModifiers_t.
335 * @param caConType CATransportFlags_t input.
336 * @return OCTransportFlags
338 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
341 * Handle response from presence request.
343 * @param endPoint CA remote endpoint.
344 * @param responseInfo CA response info.
345 * @return ::OC_STACK_OK on success, some other value upon failure.
347 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
348 const CAResponseInfo_t *responseInfo);
351 * This function will be called back by CA layer when a response is received.
353 * @param endPoint CA remote endpoint.
354 * @param responseInfo CA response info.
356 static void HandleCAResponses(const CAEndpoint_t* endPoint,
357 const CAResponseInfo_t* responseInfo);
360 * This function will be called back by CA layer when a request is received.
362 * @param endPoint CA remote endpoint.
363 * @param requestInfo CA request info.
365 static void HandleCARequests(const CAEndpoint_t* endPoint,
366 const CARequestInfo_t* requestInfo);
369 * Extract query from a URI.
371 * @param uri Full URI with query.
372 * @param query Pointer to string that will contain query.
373 * @param newURI Pointer to string that will contain URI.
374 * @return ::OC_STACK_OK on success, some other value upon failure.
376 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
379 * Finds a resource type in an OCResourceType link-list.
381 * @param resourceTypeList The link-list to be searched through.
382 * @param resourceTypeName The key to search for.
384 * @return Resource type that matches the key (ie. resourceTypeName) or
385 * NULL if there is either an invalid parameter or this function was unable to find the key.
387 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
388 const char * resourceTypeName);
391 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
392 * TTL will be set to maxAge.
394 * @param cbNode Callback Node for which presence ttl is to be reset.
395 * @param maxAge New value of ttl in seconds.
397 * @return ::OC_STACK_OK on success, some other value upon failure.
399 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
402 * Ensure the accept header option is set appropriatly before sending the requests and routing
403 * header option is updated with destination.
405 * @param object CA remote endpoint.
406 * @param requestInfo CA request info.
408 * @return ::OC_STACK_OK on success, some other value upon failure.
410 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
413 * default adapter state change callback method
415 * @param adapter CA network adapter type.
416 * @param enabled current adapter state.
418 static void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled);
421 * default connection state change callback method
423 * @param info CAEndpoint which has address, port and etc.
424 * @param isConnected current connection state.
426 static void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected);
429 * Register network monitoring callback.
430 * Network status changes are delivered these callback.
431 * @param adapterHandler Adapter state monitoring callback.
432 * @param connectionHandler Connection state monitoring callback.
434 static void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
435 CAConnectionStateChangedCB connectionHandler);
437 //-----------------------------------------------------------------------------
438 // Internal functions
439 //-----------------------------------------------------------------------------
441 bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
443 if (!options || 0 == numOptions)
445 OIC_LOG (INFO, TAG, "No options present");
449 for (uint8_t i = 0; i < numOptions; i++)
451 if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
453 OIC_LOG(DEBUG, TAG, "Proxy URI is present");
460 uint32_t GetTicks(uint32_t afterMilliSeconds)
465 // Guard against overflow of uint32_t
466 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
467 COAP_TICKS_PER_SECOND)
469 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
477 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
479 VERIFY_NON_NULL_NR(in, FATAL);
480 VERIFY_NON_NULL_NR(out, FATAL);
482 out->adapter = (OCTransportAdapter)in->adapter;
483 out->flags = CAToOCTransportFlags(in->flags);
484 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
485 out->port = in->port;
486 out->ifindex = in->ifindex;
487 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
488 /* This assert is to prevent accidental mismatch between address size macros defined in
489 * RI and CA and cause crash here. */
490 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
491 "Address size mismatch between RI and CA");
492 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
496 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
498 VERIFY_NON_NULL_NR(in, FATAL);
499 VERIFY_NON_NULL_NR(out, FATAL);
501 out->adapter = (CATransportAdapter_t)in->adapter;
502 out->flags = OCToCATransportFlags(in->flags);
503 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
504 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
505 /* This assert is to prevent accidental mismatch between address size macros defined in
506 * RI and CA and cause crash here. */
507 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
508 "Address size mismatch between RI and CA");
509 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
511 out->port = in->port;
512 out->ifindex = in->ifindex;
515 void FixUpClientResponse(OCClientResponse *cr)
517 VERIFY_NON_NULL_NR(cr, FATAL);
519 cr->addr = &cr->devAddr;
520 cr->connType = (OCConnectivityType)
521 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
524 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
526 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
527 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
529 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
530 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
531 if (OC_STACK_OK != rmResult)
533 OIC_LOG(ERROR, TAG, "Add destination option failed");
538 // OC stack prefer CBOR encoded payloads.
539 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
540 CAResult_t result = CASendRequest(object, requestInfo);
541 if(CA_STATUS_OK != result)
543 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
544 return CAResultToOCResult(result);
548 //-----------------------------------------------------------------------------
549 // Internal API function
550 //-----------------------------------------------------------------------------
552 // This internal function is called to update the stack with the status of
553 // observers and communication failures
554 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
556 OCStackResult result = OC_STACK_ERROR;
557 ResourceObserver * observer = NULL;
558 OCEntityHandlerRequest ehRequest = {0};
562 case OC_OBSERVER_NOT_INTERESTED:
563 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
564 observer = GetObserverUsingToken (token, tokenLength);
567 result = FormOCEntityHandlerRequest(&ehRequest,
568 (OCRequestHandle)NULL,
571 (OCResourceHandle)NULL,
572 NULL, PAYLOAD_TYPE_REPRESENTATION,
574 OC_OBSERVE_DEREGISTER,
577 if(result != OC_STACK_OK)
581 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
582 observer->resource->entityHandlerCallbackParam);
585 result = DeleteObserverUsingToken (token, tokenLength);
586 if(result == OC_STACK_OK)
588 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
592 result = OC_STACK_OK;
593 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
597 case OC_OBSERVER_STILL_INTERESTED:
598 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
599 observer = GetObserverUsingToken (token, tokenLength);
602 observer->forceHighQos = 0;
603 observer->failedCommCount = 0;
604 result = OC_STACK_OK;
608 result = OC_STACK_OBSERVER_NOT_FOUND;
612 case OC_OBSERVER_FAILED_COMM:
613 OIC_LOG(DEBUG, TAG, "observer is unreachable");
614 observer = GetObserverUsingToken (token, tokenLength);
617 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
619 result = FormOCEntityHandlerRequest(&ehRequest,
620 (OCRequestHandle)NULL,
623 (OCResourceHandle)NULL,
624 NULL, PAYLOAD_TYPE_REPRESENTATION,
626 OC_OBSERVE_DEREGISTER,
629 if(result != OC_STACK_OK)
631 return OC_STACK_ERROR;
633 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
634 observer->resource->entityHandlerCallbackParam);
636 result = DeleteObserverUsingToken (token, tokenLength);
637 if(result == OC_STACK_OK)
639 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
643 result = OC_STACK_OK;
644 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
649 observer->failedCommCount++;
650 result = OC_STACK_CONTINUE;
652 observer->forceHighQos = 1;
653 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
657 OIC_LOG(ERROR, TAG, "Unknown status");
658 result = OC_STACK_ERROR;
664 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
666 OCStackResult ret = OC_STACK_ERROR;
670 case CA_ADAPTER_NOT_ENABLED:
671 case CA_SERVER_NOT_STARTED:
672 ret = OC_STACK_ADAPTER_NOT_ENABLED;
674 case CA_MEMORY_ALLOC_FAILED:
675 ret = OC_STACK_NO_MEMORY;
677 case CA_STATUS_INVALID_PARAM:
678 ret = OC_STACK_INVALID_PARAM;
686 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
688 OCStackResult ret = OC_STACK_ERROR;
692 ret = OC_STACK_RESOURCE_CREATED;
695 ret = OC_STACK_RESOURCE_DELETED;
698 ret = OC_STACK_RESOURCE_CHANGED;
705 ret = OC_STACK_INVALID_QUERY;
707 case CA_UNAUTHORIZED_REQ:
708 ret = OC_STACK_UNAUTHORIZED_REQ;
711 ret = OC_STACK_INVALID_OPTION;
714 ret = OC_STACK_NO_RESOURCE;
716 case CA_RETRANSMIT_TIMEOUT:
717 ret = OC_STACK_COMM_ERROR;
719 case CA_REQUEST_ENTITY_TOO_LARGE:
720 ret = OC_STACK_TOO_LARGE_REQ;
722 case CA_FORBIDDEN_REQ:
723 ret = OC_STACK_FORBIDDEN_REQ;
725 case CA_INTERNAL_SERVER_ERROR:
726 ret = OC_STACK_INTERNAL_SERVER_ERROR;
734 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
736 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
745 // This Response Code is like HTTP 204 "No Content" but only used in
746 // response to POST and PUT requests.
750 // This Response Code is like HTTP 200 "OK" but only used in response to
755 // This should not happen but,
756 // give it a value just in case but output an error
758 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
762 case OC_STACK_RESOURCE_CREATED:
765 case OC_STACK_RESOURCE_DELETED:
768 case OC_STACK_RESOURCE_CHANGED:
771 case OC_STACK_INVALID_QUERY:
774 case OC_STACK_INVALID_OPTION:
777 case OC_STACK_NO_RESOURCE:
780 case OC_STACK_COMM_ERROR:
781 ret = CA_RETRANSMIT_TIMEOUT;
783 case OC_STACK_UNAUTHORIZED_REQ:
784 ret = CA_UNAUTHORIZED_REQ;
786 case OC_STACK_FORBIDDEN_REQ:
787 ret = CA_FORBIDDEN_REQ;
789 case OC_STACK_INTERNAL_SERVER_ERROR:
790 ret = CA_INTERNAL_SERVER_ERROR;
798 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
800 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
802 // supply default behavior.
803 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
805 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
807 if ((caFlags & OC_MASK_SCOPE) == 0)
809 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
814 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
816 return (OCTransportFlags)caFlags;
819 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
821 uint32_t lowerBound = 0;
822 uint32_t higherBound = 0;
824 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
826 return OC_STACK_INVALID_PARAM;
829 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
831 cbNode->presence->TTL = maxAgeSeconds;
833 for (int index = 0; index < PresenceTimeOutSize; index++)
835 // Guard against overflow
836 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
839 lowerBound = GetTicks((PresenceTimeOut[index] *
840 cbNode->presence->TTL *
841 MILLISECONDS_PER_SECOND)/100);
845 lowerBound = GetTicks(UINT32_MAX);
848 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
851 higherBound = GetTicks((PresenceTimeOut[index + 1] *
852 cbNode->presence->TTL *
853 MILLISECONDS_PER_SECOND)/100);
857 higherBound = GetTicks(UINT32_MAX);
860 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
862 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
863 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
864 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
867 cbNode->presence->TTLlevel = 0;
869 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
873 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
875 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
877 return OC_RSRVD_TRIGGER_CREATE;
879 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
881 return OC_RSRVD_TRIGGER_CHANGE;
885 return OC_RSRVD_TRIGGER_DELETE;
889 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
893 return OC_PRESENCE_TRIGGER_CREATE;
895 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
897 return OC_PRESENCE_TRIGGER_CREATE;
899 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
901 return OC_PRESENCE_TRIGGER_CHANGE;
905 return OC_PRESENCE_TRIGGER_DELETE;
909 OCStackResult OCEncodeAddressForRFC6874(char *outputAddress,
911 const char *inputAddress)
913 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
914 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
916 size_t inputLength = strnlen(inputAddress, outputSize);
918 // inputSize includes the null terminator
919 size_t inputSize = inputLength + 1;
921 if (inputSize > outputSize)
923 OIC_LOG_V(ERROR, TAG,
924 "OCEncodeAddressForRFC6874 failed: "
925 "outputSize (%zu) < inputSize (%zu)",
926 outputSize, inputSize);
928 return OC_STACK_ERROR;
931 char* percentChar = strchr(inputAddress, '%');
933 // If there is no '%' character, then no change is required to the string.
934 if (NULL == percentChar)
936 OICStrcpy(outputAddress, outputSize, inputAddress);
940 const char* addressPart = &inputAddress[0];
941 const char* scopeIdPart = percentChar + 1;
943 // Sanity check to make sure this string doesn't have more '%' characters
944 if (NULL != strchr(scopeIdPart, '%'))
946 return OC_STACK_ERROR;
949 // If no string follows the first '%', then the input was invalid.
950 if (scopeIdPart[0] == '\0')
952 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
953 return OC_STACK_ERROR;
956 // Check to see if the string is already encoded
957 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
959 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Input string is already encoded");
960 return OC_STACK_ERROR;
963 // Fail if we don't have room for encoded string's two additional chars
964 if (outputSize < (inputSize + 2))
966 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: encoded output will not fit!");
967 return OC_STACK_ERROR;
970 // Restore the null terminator with an escaped '%' character, per RFC 6874
971 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
972 strcat(outputAddress, "%25");
973 strcat(outputAddress, scopeIdPart);
978 OCStackResult OCDecodeAddressForRFC6874(char *outputAddress,
980 const char *inputAddress,
983 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
984 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
988 end = inputAddress + strlen(inputAddress);
990 size_t inputLength = end - inputAddress;
992 const char *percent = strchr(inputAddress, '%');
993 if (!percent || (percent > end))
995 OICStrcpyPartial(outputAddress, outputSize, inputAddress, inputLength);
999 if (percent[1] != '2' || percent[2] != '5')
1001 return OC_STACK_INVALID_URI;
1004 int addrlen = percent - inputAddress + 1;
1005 OICStrcpyPartial(outputAddress, outputSize, inputAddress, addrlen);
1006 OICStrcpyPartial(outputAddress + addrlen, outputSize - addrlen,
1007 percent + 3, end - percent - 3);
1014 * The cononical presence allows constructed URIs to be string compared.
1016 * requestUri must be a char array of size CA_MAX_URI_LENGTH
1018 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
1019 char *presenceUri, bool isMulticast)
1021 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
1022 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1026 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1027 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1030 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1031 if (ep->adapter == CA_ADAPTER_IP)
1033 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1035 if ('\0' == ep->addr[0]) // multicast
1037 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1041 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1043 OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1044 sizeof(addressEncoded),
1047 if (OC_STACK_OK != result)
1052 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1053 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1058 if ('\0' == ep->addr[0]) // multicast
1060 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1061 ep->port = OC_MULTICAST_PORT;
1063 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1064 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1068 // might work for other adapters (untested, but better than nothing)
1069 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1070 OC_RSRVD_PRESENCE_URI);
1074 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1075 const CAResponseInfo_t *responseInfo)
1077 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1078 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1080 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1081 ClientCB * cbNode = NULL;
1082 char *resourceTypeName = NULL;
1083 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1084 OCStackResult result = OC_STACK_ERROR;
1085 uint32_t maxAge = 0;
1087 char presenceUri[CA_MAX_URI_LENGTH];
1089 int presenceSubscribe = 0;
1090 int multicastPresenceSubscribe = 0;
1092 if (responseInfo->result != CA_CONTENT)
1094 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1095 return OC_STACK_ERROR;
1098 response.payload = NULL;
1099 response.result = OC_STACK_OK;
1101 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1102 FixUpClientResponse(&response);
1104 if (responseInfo->info.payload)
1106 result = OCParsePayload(&response.payload,
1107 PAYLOAD_TYPE_PRESENCE,
1108 responseInfo->info.payload,
1109 responseInfo->info.payloadSize);
1111 if(result != OC_STACK_OK)
1113 OIC_LOG(ERROR, TAG, "Presence parse failed");
1116 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1118 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1119 result = OC_STACK_ERROR;
1122 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1123 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1124 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1127 // check for unicast presence
1128 uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1129 responseInfo->isMulticast);
1130 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1132 return OC_STACK_INVALID_URI;
1134 OIC_LOG(ERROR, TAG, "check for unicast presence");
1135 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1138 presenceSubscribe = 1;
1142 // check for multicast presence
1143 OIC_LOG(ERROR, TAG, "check for multicast presence");
1144 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1147 multicastPresenceSubscribe = 1;
1151 if (!presenceSubscribe && !multicastPresenceSubscribe)
1153 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1157 if (presenceSubscribe)
1159 if(cbNode->sequenceNumber == response.sequenceNumber)
1161 OIC_LOG(INFO, TAG, "No presence change");
1162 ResetPresenceTTL(cbNode, maxAge);
1163 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1169 OIC_LOG(INFO, TAG, "Stopping presence");
1170 response.result = OC_STACK_PRESENCE_STOPPED;
1171 if(cbNode->presence)
1173 OICFree(cbNode->presence->timeOut);
1174 OICFree(cbNode->presence);
1175 cbNode->presence = NULL;
1180 if(!cbNode->presence)
1182 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1184 if(!(cbNode->presence))
1186 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1187 result = OC_STACK_NO_MEMORY;
1191 VERIFY_NON_NULL_V(cbNode->presence);
1192 cbNode->presence->timeOut = NULL;
1193 cbNode->presence->timeOut = (uint32_t *)
1194 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1195 if(!(cbNode->presence->timeOut)){
1197 "Could not allocate memory for cbNode->presence->timeOut");
1198 OICFree(cbNode->presence);
1199 result = OC_STACK_NO_MEMORY;
1204 ResetPresenceTTL(cbNode, maxAge);
1206 cbNode->sequenceNumber = response.sequenceNumber;
1211 // This is the multicast case
1212 OIC_LOG(INFO, TAG, "this is the multicast presence");
1215 OIC_LOG(INFO, TAG, "Stopping presence");
1216 response.result = OC_STACK_PRESENCE_STOPPED;
1220 // Ensure that a filter is actually applied.
1221 if (resourceTypeName && cbNode->filterResourceType)
1223 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1224 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1230 OIC_LOG(INFO, TAG, "Callback for presence");
1232 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1234 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1236 FindAndDeleteClientCB(cbNode);
1240 OCPayloadDestroy(response.payload);
1244 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1246 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1248 if(responseInfo->info.resourceUri &&
1249 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1251 HandlePresenceResponse(endPoint, responseInfo);
1255 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1256 responseInfo->info.tokenLength, NULL, NULL);
1258 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1259 responseInfo->info.tokenLength);
1263 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1264 if(responseInfo->result == CA_EMPTY)
1266 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1267 // We do not have a case for the client to receive a RESET
1268 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1270 //This is the case of receiving an ACK on a request to a slow resource!
1271 OIC_LOG(INFO, TAG, "This is a pure ACK");
1272 //TODO: should we inform the client
1273 // app that at least the request was received at the server?
1276 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1278 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1279 OIC_LOG(INFO, TAG, "Calling into application address space");
1281 OCClientResponse response =
1282 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1283 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1284 FixUpClientResponse(&response);
1285 response.resourceUri = responseInfo->info.resourceUri;
1286 memcpy(response.identity.id, responseInfo->info.identity.id,
1287 sizeof (response.identity.id));
1288 response.identity.id_length = responseInfo->info.identity.id_length;
1290 response.result = CAResponseToOCStackResult(responseInfo->result);
1291 cbNode->callBack(cbNode->context,
1292 cbNode->handle, &response);
1293 FindAndDeleteClientCB(cbNode);
1297 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1298 OIC_LOG(INFO, TAG, "Calling into application address space");
1300 OCClientResponse response =
1301 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1302 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1303 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1304 FixUpClientResponse(&response);
1305 response.resourceUri = responseInfo->info.resourceUri;
1306 memcpy(response.identity.id, responseInfo->info.identity.id,
1307 sizeof (response.identity.id));
1308 response.identity.id_length = responseInfo->info.identity.id_length;
1310 response.result = CAResponseToOCStackResult(responseInfo->result);
1312 if(responseInfo->info.payload &&
1313 responseInfo->info.payloadSize)
1315 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1316 // check the security resource
1317 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1319 type = PAYLOAD_TYPE_SECURITY;
1321 else if (cbNode->method == OC_REST_DISCOVER)
1323 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1324 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1326 type = PAYLOAD_TYPE_DISCOVERY;
1329 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1331 type = PAYLOAD_TYPE_DISCOVERY;
1334 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1336 type = PAYLOAD_TYPE_DEVICE;
1338 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1340 type = PAYLOAD_TYPE_PLATFORM;
1342 #ifdef ROUTING_GATEWAY
1343 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1345 type = PAYLOAD_TYPE_REPRESENTATION;
1348 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1350 type = PAYLOAD_TYPE_REPRESENTATION ;
1353 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1355 type = PAYLOAD_TYPE_REPRESENTATION;
1360 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1361 cbNode->method, cbNode->requestUri);
1365 else if (cbNode->method == OC_REST_GET ||
1366 cbNode->method == OC_REST_PUT ||
1367 cbNode->method == OC_REST_POST ||
1368 cbNode->method == OC_REST_OBSERVE ||
1369 cbNode->method == OC_REST_OBSERVE_ALL ||
1370 cbNode->method == OC_REST_DELETE)
1372 if (cbNode->requestUri)
1374 if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1376 type = PAYLOAD_TYPE_PLATFORM;
1378 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1380 type = PAYLOAD_TYPE_DEVICE;
1382 if (type == PAYLOAD_TYPE_INVALID)
1384 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1385 cbNode->method, cbNode->requestUri);
1386 type = PAYLOAD_TYPE_REPRESENTATION;
1391 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1392 type = PAYLOAD_TYPE_REPRESENTATION;
1397 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1398 cbNode->method, cbNode->requestUri);
1402 if(OC_STACK_OK != OCParsePayload(&response.payload,
1404 responseInfo->info.payload,
1405 responseInfo->info.payloadSize))
1407 OIC_LOG(ERROR, TAG, "Error converting payload");
1408 OCPayloadDestroy(response.payload);
1413 response.numRcvdVendorSpecificHeaderOptions = 0;
1414 if(responseInfo->info.numOptions > 0)
1417 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1418 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1421 uint32_t observationOption;
1422 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1423 for (observationOption=0, i=0;
1424 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1428 (observationOption << 8) | optionData[i];
1430 response.sequenceNumber = observationOption;
1431 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1436 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1439 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1441 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1442 OCPayloadDestroy(response.payload);
1446 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1448 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1449 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1453 if (cbNode->method == OC_REST_OBSERVE &&
1454 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1455 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1456 response.sequenceNumber <= cbNode->sequenceNumber)
1458 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1459 response.sequenceNumber);
1464 // if request uri is '/oic/rd', update ins value of resource.
1465 char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
1468 OCUpdateResourceInsWithResponse(cbNode->requestUri, &response);
1471 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1474 cbNode->sequenceNumber = response.sequenceNumber;
1476 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1478 FindAndDeleteClientCB(cbNode);
1482 // To keep discovery callbacks active.
1483 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1484 MILLISECONDS_PER_SECOND);
1488 //Need to send ACK when the response is CON
1489 if(responseInfo->info.type == CA_MSG_CONFIRM)
1491 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1492 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1495 OCPayloadDestroy(response.payload);
1502 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1503 if(responseInfo->result == CA_EMPTY)
1505 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1506 if(responseInfo->info.type == CA_MSG_RESET)
1508 OIC_LOG(INFO, TAG, "This is a RESET");
1509 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1510 OC_OBSERVER_NOT_INTERESTED);
1512 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1514 OIC_LOG(INFO, TAG, "This is a pure ACK");
1515 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1516 OC_OBSERVER_STILL_INTERESTED);
1519 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1521 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1522 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1523 OC_OBSERVER_FAILED_COMM);
1528 if(!cbNode && !observer)
1530 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1531 || myStackMode == OC_GATEWAY)
1533 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1534 if(responseInfo->result == CA_EMPTY)
1536 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1540 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1541 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1542 CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1546 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1547 || myStackMode == OC_GATEWAY)
1549 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1550 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1552 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1553 responseInfo->info.messageId);
1555 if (responseInfo->info.type == CA_MSG_RESET)
1557 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1558 responseInfo->info.messageId);
1566 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1568 VERIFY_NON_NULL_NR(endPoint, FATAL);
1569 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1571 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1573 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1574 #ifdef ROUTING_GATEWAY
1575 bool needRIHandling = false;
1577 * Routing manager is going to update either of endpoint or response or both.
1578 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1579 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1582 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1584 if(ret != OC_STACK_OK || !needRIHandling)
1586 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1592 * Put source in sender endpoint so that the next packet from application can be routed to
1593 * proper destination and remove "RM" coap header option before passing request / response to
1594 * RI as this option will make no sense to either RI or application.
1596 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1597 (uint8_t *) &(responseInfo->info.numOptions),
1598 (CAEndpoint_t *) endPoint);
1601 OCHandleResponse(endPoint, responseInfo);
1603 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1607 * This function handles error response from CA
1608 * code shall be added to handle the errors
1610 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1612 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1614 if (NULL == endPoint)
1616 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1620 if (NULL == errorInfo)
1622 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1626 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1627 errorInfo->info.tokenLength, NULL, NULL);
1630 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1631 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1632 FixUpClientResponse(&response);
1633 response.resourceUri = errorInfo->info.resourceUri;
1634 memcpy(response.identity.id, errorInfo->info.identity.id,
1635 sizeof (response.identity.id));
1636 response.identity.id_length = errorInfo->info.identity.id_length;
1637 response.result = CAResultToOCStackResult(errorInfo->result);
1639 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1642 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1646 * This function sends out Direct Stack Responses. These are responses that are not coming
1647 * from the application entity handler. These responses have no payload and are usually ACKs,
1648 * RESETs or some error conditions that were caught by the stack.
1650 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1651 const CAResponseResult_t responseResult, const CAMessageType_t type,
1652 const uint8_t numOptions, const CAHeaderOption_t *options,
1653 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1654 CADataType_t dataType)
1656 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1657 CAResponseInfo_t respInfo = {
1658 .result = responseResult
1660 respInfo.info.messageId = coapID;
1661 respInfo.info.numOptions = numOptions;
1663 if (respInfo.info.numOptions)
1665 respInfo.info.options =
1666 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1667 memcpy (respInfo.info.options, options,
1668 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1672 respInfo.info.payload = NULL;
1673 respInfo.info.token = token;
1674 respInfo.info.tokenLength = tokenLength;
1675 respInfo.info.type = type;
1676 respInfo.info.resourceUri = OICStrdup (resourceUri);
1677 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1678 respInfo.info.dataType = dataType;
1680 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1681 // Add the destination to route option from the endpoint->routeData.
1682 bool doPost = false;
1683 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1684 if(OC_STACK_OK != result)
1686 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1687 OICFree (respInfo.info.resourceUri);
1688 OICFree (respInfo.info.options);
1693 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1694 CARequestInfo_t reqInfo = {.method = CA_POST };
1695 /* The following initialization is not done in a single initializer block as in
1696 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1697 * does not have designated initalizers. This is a work-around for now.
1699 reqInfo.info.type = CA_MSG_NONCONFIRM;
1700 reqInfo.info.messageId = coapID;
1701 reqInfo.info.tokenLength = tokenLength;
1702 reqInfo.info.token = token;
1703 reqInfo.info.numOptions = respInfo.info.numOptions;
1704 reqInfo.info.payload = NULL;
1705 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1706 if (reqInfo.info.numOptions)
1708 reqInfo.info.options =
1709 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1710 if (NULL == reqInfo.info.options)
1712 OIC_LOG(ERROR, TAG, "Calloc failed");
1713 OICFree (reqInfo.info.resourceUri);
1714 OICFree (respInfo.info.resourceUri);
1715 OICFree (respInfo.info.options);
1716 return OC_STACK_NO_MEMORY;
1718 memcpy (reqInfo.info.options, respInfo.info.options,
1719 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1722 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1723 OICFree (reqInfo.info.resourceUri);
1724 OICFree (reqInfo.info.options);
1725 OICFree (respInfo.info.resourceUri);
1726 OICFree (respInfo.info.options);
1727 if (CA_STATUS_OK != caResult)
1729 OIC_LOG(ERROR, TAG, "CASendRequest error");
1730 return CAResultToOCResult(caResult);
1736 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1738 // resourceUri in the info field is cloned in the CA layer and
1739 // thus ownership is still here.
1740 OICFree (respInfo.info.resourceUri);
1741 OICFree (respInfo.info.options);
1742 if(CA_STATUS_OK != caResult)
1744 OIC_LOG(ERROR, TAG, "CASendResponse error");
1745 return CAResultToOCResult(caResult);
1748 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1752 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1754 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1755 OCStackResult result = OC_STACK_ERROR;
1756 if(!protocolRequest)
1758 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1759 return OC_STACK_INVALID_PARAM;
1762 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1763 protocolRequest->tokenLength);
1766 OIC_LOG(INFO, TAG, "This is a new Server Request");
1767 result = AddServerRequest(&request, protocolRequest->coapID,
1768 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1769 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1770 protocolRequest->observationOption, protocolRequest->qos,
1771 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1772 protocolRequest->payload, protocolRequest->requestToken,
1773 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1774 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1775 &protocolRequest->devAddr);
1776 if (OC_STACK_OK != result)
1778 OIC_LOG(ERROR, TAG, "Error adding server request");
1784 OIC_LOG(ERROR, TAG, "Out of Memory");
1785 return OC_STACK_NO_MEMORY;
1788 if(!protocolRequest->reqMorePacket)
1790 request->requestComplete = 1;
1795 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1798 if(request->requestComplete)
1800 OIC_LOG(INFO, TAG, "This Server Request is complete");
1801 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1802 OCResource *resource = NULL;
1803 result = DetermineResourceHandling (request, &resHandling, &resource);
1804 if (result == OC_STACK_OK)
1806 result = ProcessRequest(resHandling, resource, request);
1811 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1812 result = OC_STACK_CONTINUE;
1817 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1819 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1821 OCStackResult requestResult = OC_STACK_ERROR;
1823 if(myStackMode == OC_CLIENT)
1825 //TODO: should the client be responding to requests?
1829 OCServerProtocolRequest serverRequest = {0};
1831 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1833 char * uriWithoutQuery = NULL;
1834 char * query = NULL;
1836 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1838 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1840 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1843 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1844 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1846 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1848 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1849 OICFree(uriWithoutQuery);
1853 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1854 OICFree(uriWithoutQuery);
1861 if(strlen(query) < MAX_QUERY_LENGTH)
1863 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1868 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1874 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1876 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1877 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1878 if (!serverRequest.payload)
1880 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1883 memcpy (serverRequest.payload, requestInfo->info.payload,
1884 requestInfo->info.payloadSize);
1888 serverRequest.reqTotalSize = 0;
1891 switch (requestInfo->method)
1894 serverRequest.method = OC_REST_GET;
1897 serverRequest.method = OC_REST_PUT;
1900 serverRequest.method = OC_REST_POST;
1903 serverRequest.method = OC_REST_DELETE;
1906 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1907 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1908 requestInfo->info.type, requestInfo->info.numOptions,
1909 requestInfo->info.options, requestInfo->info.token,
1910 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1912 OICFree(serverRequest.payload);
1916 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1917 requestInfo->info.tokenLength);
1919 serverRequest.tokenLength = requestInfo->info.tokenLength;
1920 if (serverRequest.tokenLength) {
1922 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1924 if (!serverRequest.requestToken)
1926 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1927 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1928 requestInfo->info.type, requestInfo->info.numOptions,
1929 requestInfo->info.options, requestInfo->info.token,
1930 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1932 OICFree(serverRequest.payload);
1935 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1938 switch (requestInfo->info.acceptFormat)
1940 case CA_FORMAT_APPLICATION_CBOR:
1941 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1943 case CA_FORMAT_UNDEFINED:
1944 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1947 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1950 if (requestInfo->info.type == CA_MSG_CONFIRM)
1952 serverRequest.qos = OC_HIGH_QOS;
1956 serverRequest.qos = OC_LOW_QOS;
1958 // CA does not need the following field
1959 // Are we sure CA does not need them? how is it responding to multicast
1960 serverRequest.delayedResNeeded = 0;
1962 serverRequest.coapID = requestInfo->info.messageId;
1964 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1966 // copy vendor specific header options
1967 uint8_t tempNum = (requestInfo->info.numOptions);
1969 // Assume no observation requested and it is a pure GET.
1970 // If obs registration/de-registration requested it'll be fetched from the
1971 // options in GetObserveHeaderOption()
1972 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1974 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1975 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1978 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1979 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1980 requestInfo->info.type, requestInfo->info.numOptions,
1981 requestInfo->info.options, requestInfo->info.token,
1982 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1984 OICFree(serverRequest.payload);
1985 OICFree(serverRequest.requestToken);
1988 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1989 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1991 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1992 sizeof(CAHeaderOption_t)*tempNum);
1995 requestResult = HandleStackRequests (&serverRequest);
1997 // Send ACK to client as precursor to slow response
1998 if (requestResult == OC_STACK_SLOW_RESOURCE)
2000 if (requestInfo->info.type == CA_MSG_CONFIRM)
2002 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2003 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2007 if (requestResult == OC_STACK_RESOURCE_ERROR
2008 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2010 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2012 else if(!OCResultToSuccess(requestResult))
2014 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2016 CAResponseResult_t stackResponse =
2017 OCToCAStackResult(requestResult, serverRequest.method);
2019 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2020 requestInfo->info.type, requestInfo->info.numOptions,
2021 requestInfo->info.options, requestInfo->info.token,
2022 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2025 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2026 // The token is copied in there, and is thus still owned by this function.
2027 OICFree(serverRequest.payload);
2028 OICFree(serverRequest.requestToken);
2029 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2032 //This function will be called back by CA layer when a request is received
2033 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2035 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2038 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2044 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2048 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2049 #ifdef ROUTING_GATEWAY
2050 bool needRIHandling = false;
2051 bool isEmptyMsg = false;
2053 * Routing manager is going to update either of endpoint or request or both.
2054 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2055 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2056 * destination. It can also remove "RM" coap header option before passing request / response to
2057 * RI as this option will make no sense to either RI or application.
2059 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2060 &needRIHandling, &isEmptyMsg);
2061 if(OC_STACK_OK != ret || !needRIHandling)
2063 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2069 * Put source in sender endpoint so that the next packet from application can be routed to
2070 * proper destination and remove RM header option.
2072 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2073 (uint8_t *) &(requestInfo->info.numOptions),
2074 (CAEndpoint_t *) endPoint);
2076 #ifdef ROUTING_GATEWAY
2080 * In Gateways, the MSGType in route option is used to check if the actual
2081 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2082 * EMPTY response is sent in the form of POST request which need to be changed
2083 * to a EMPTY response by RM. This translation is done in this part of the code.
2085 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2086 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2087 .info.messageId = requestInfo->info.messageId,
2088 .info.type = CA_MSG_ACKNOWLEDGE};
2089 OCHandleResponse(endPoint, &respInfo);
2095 // Normal handling of the packet
2096 OCHandleRequests(endPoint, requestInfo);
2098 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2101 bool validatePlatformInfo(OCPlatformInfo info)
2104 if (!info.platformID)
2106 OIC_LOG(ERROR, TAG, "No platform ID found.");
2110 if (info.manufacturerName)
2112 size_t lenManufacturerName = strlen(info.manufacturerName);
2114 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2116 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2122 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2126 if (info.manufacturerUrl)
2128 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2130 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2137 //-----------------------------------------------------------------------------
2139 //-----------------------------------------------------------------------------
2141 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2144 !raInfo->username ||
2145 !raInfo->hostname ||
2146 !raInfo->xmpp_domain)
2149 return OC_STACK_INVALID_PARAM;
2151 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2152 gRASetInfo = (result == OC_STACK_OK)? true : false;
2158 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2162 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2165 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2167 if(stackState == OC_STACK_INITIALIZED)
2169 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2170 OCStop() between them are ignored.");
2174 #ifndef ROUTING_GATEWAY
2175 if (OC_GATEWAY == mode)
2177 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2178 return OC_STACK_INVALID_PARAM;
2185 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2186 return OC_STACK_ERROR;
2190 OCStackResult result = OC_STACK_ERROR;
2191 OIC_LOG(INFO, TAG, "Entering OCInit");
2194 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2195 || (mode == OC_GATEWAY)))
2197 OIC_LOG(ERROR, TAG, "Invalid mode");
2198 return OC_STACK_ERROR;
2202 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2204 caglobals.client = true;
2206 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2208 caglobals.server = true;
2211 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2212 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2214 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2216 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2217 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2219 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2222 defaultDeviceHandler = NULL;
2223 defaultDeviceHandlerCallbackParameter = NULL;
2225 result = InitializeScheduleResourceList();
2226 VERIFY_SUCCESS(result, OC_STACK_OK);
2228 result = CAResultToOCResult(CAInitialize());
2229 VERIFY_SUCCESS(result, OC_STACK_OK);
2231 result = CAResultToOCResult(OCSelectNetwork());
2232 VERIFY_SUCCESS(result, OC_STACK_OK);
2234 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2235 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2236 VERIFY_SUCCESS(result, OC_STACK_OK);
2238 switch (myStackMode)
2241 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2242 result = CAResultToOCResult(CAStartDiscoveryServer());
2243 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2246 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2247 result = CAResultToOCResult(CAStartListeningServer());
2248 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2250 case OC_CLIENT_SERVER:
2252 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2253 result = CAResultToOCResult(CAStartListeningServer());
2254 if(result == OC_STACK_OK)
2256 result = CAResultToOCResult(CAStartDiscoveryServer());
2260 VERIFY_SUCCESS(result, OC_STACK_OK);
2263 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2266 #ifdef WITH_PRESENCE
2267 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2268 #endif // WITH_PRESENCE
2270 //Update Stack state to initialized
2271 stackState = OC_STACK_INITIALIZED;
2273 // Initialize resource
2274 if(myStackMode != OC_CLIENT)
2276 result = initResources();
2279 // Initialize the SRM Policy Engine
2280 if(result == OC_STACK_OK)
2282 result = SRMInitPolicyEngine();
2283 // TODO after BeachHead delivery: consolidate into single SRMInit()
2285 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2286 RMSetStackMode(mode);
2287 #ifdef ROUTING_GATEWAY
2288 if (OC_GATEWAY == myStackMode)
2290 result = RMInitialize();
2296 if (result == OC_STACK_OK)
2298 result = InitializeKeepAlive(myStackMode);
2303 if(result != OC_STACK_OK)
2305 OIC_LOG(ERROR, TAG, "Stack initialization error");
2306 deleteAllResources();
2308 TerminateScheduleResourceList();
2309 stackState = OC_STACK_UNINITIALIZED;
2314 OCStackResult OCStop()
2316 OIC_LOG(INFO, TAG, "Entering OCStop");
2318 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2320 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2323 else if (stackState != OC_STACK_INITIALIZED)
2325 OIC_LOG(ERROR, TAG, "Stack not initialized");
2326 return OC_STACK_ERROR;
2329 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2331 #ifdef WITH_PRESENCE
2332 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2333 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2334 presenceResource.presenceTTL = 0;
2335 #endif // WITH_PRESENCE
2337 #ifdef ROUTING_GATEWAY
2338 if (OC_GATEWAY == myStackMode)
2345 TerminateKeepAlive(myStackMode);
2348 // Free memory dynamically allocated for resources
2349 deleteAllResources();
2351 DeletePlatformInfo();
2353 TerminateScheduleResourceList();
2354 // Remove all observers
2355 DeleteObserverList();
2356 // Remove all the client callbacks
2357 DeleteClientCBList();
2359 // De-init the SRM Policy Engine
2360 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2361 SRMDeInitPolicyEngine();
2364 stackState = OC_STACK_UNINITIALIZED;
2368 OCStackResult OCStartMulticastServer()
2370 if(stackState != OC_STACK_INITIALIZED)
2372 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2373 return OC_STACK_ERROR;
2375 CAResult_t ret = CAStartListeningServer();
2376 if (CA_STATUS_OK != ret)
2378 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2379 return OC_STACK_ERROR;
2384 OCStackResult OCStopMulticastServer()
2386 CAResult_t ret = CAStopListeningServer();
2387 if (CA_STATUS_OK != ret)
2389 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2390 return OC_STACK_ERROR;
2395 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2400 return CA_MSG_CONFIRM;
2405 return CA_MSG_NONCONFIRM;
2410 * A request uri consists of the following components in order:
2413 * CoAP over UDP prefix "coap://"
2414 * CoAP over TCP prefix "coap+tcp://"
2415 * CoAP over DTLS prefix "coaps://"
2416 * CoAP over TLS prefix "coaps+tcp://"
2418 * IPv6 address "[1234::5678]"
2419 * IPv4 address "192.168.1.1"
2420 * optional port ":5683"
2421 * resource uri "/oc/core..."
2423 * for PRESENCE requests, extract resource type.
2425 static OCStackResult ParseRequestUri(const char *fullUri,
2426 OCTransportAdapter adapter,
2427 OCTransportFlags flags,
2428 OCDevAddr **devAddr,
2430 char **resourceType)
2432 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2434 OCStackResult result = OC_STACK_OK;
2435 OCDevAddr *da = NULL;
2439 // provide defaults for all returned values
2446 *resourceUri = NULL;
2450 *resourceType = NULL;
2453 // delimit url prefix, if any
2454 const char *start = fullUri;
2455 char *slash2 = strstr(start, "//");
2460 char *slash = strchr(start, '/');
2463 return OC_STACK_INVALID_URI;
2466 // process url scheme
2467 size_t prefixLen = slash2 - fullUri;
2471 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2472 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2478 // TODO: this logic should come in with unit tests exercising the various strings
2479 // processs url prefix, if any
2480 size_t urlLen = slash - start;
2484 if (urlLen && devAddr)
2485 { // construct OCDevAddr
2486 if (start[0] == '[')
2488 char *close = strchr(++start, ']');
2489 if (!close || close > slash)
2491 return OC_STACK_INVALID_URI;
2494 if (close[1] == ':')
2501 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2505 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2507 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2511 char *dot = strchr(start, '.');
2512 if (dot && dot < slash)
2514 colon = strchr(start, ':');
2515 end = (colon && colon < slash) ? colon : slash;
2520 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2524 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2526 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2534 if (len >= sizeof(da->addr))
2536 return OC_STACK_INVALID_URI;
2538 // collect port, if any
2539 if (colon && colon < slash)
2541 for (colon++; colon < slash; colon++)
2544 if (c < '0' || c > '9')
2546 return OC_STACK_INVALID_URI;
2548 port = 10 * port + c - '0';
2553 if (len >= sizeof(da->addr))
2555 return OC_STACK_INVALID_URI;
2558 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2561 return OC_STACK_NO_MEMORY;
2564 // Decode address per RFC 6874.
2565 result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2566 if (result != OC_STACK_OK)
2573 da->adapter = adapter;
2575 if (!strncmp(fullUri, "coaps", 5))
2577 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2582 // process resource uri, if any
2584 { // request uri and query
2585 size_t ulen = strlen(slash); // resource uri length
2586 size_t tlen = 0; // resource type length
2589 static const char strPresence[] = "/oic/ad?rt=";
2590 static const size_t lenPresence = sizeof(strPresence) - 1;
2591 if (!strncmp(slash, strPresence, lenPresence))
2593 type = slash + lenPresence;
2594 tlen = ulen - lenPresence;
2599 *resourceUri = (char *)OICMalloc(ulen + 1);
2602 result = OC_STACK_NO_MEMORY;
2605 strcpy(*resourceUri, slash);
2608 if (type && resourceType)
2610 *resourceType = (char *)OICMalloc(tlen + 1);
2613 result = OC_STACK_NO_MEMORY;
2617 OICStrcpy(*resourceType, (tlen+1), type);
2624 // free all returned values
2631 OICFree(*resourceUri);
2635 OICFree(*resourceType);
2640 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2644 char uri[CA_MAX_URI_LENGTH];
2646 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2648 *requestUri = OICStrdup(uri);
2651 return OC_STACK_NO_MEMORY;
2658 * Discover or Perform requests on a specified resource
2660 OCStackResult OCDoResource(OCDoHandle *handle,
2662 const char *requestUri,
2663 const OCDevAddr *destination,
2665 OCConnectivityType connectivityType,
2666 OCQualityOfService qos,
2667 OCCallbackData *cbData,
2668 OCHeaderOption *options,
2671 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2673 // Validate input parameters
2674 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2675 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2677 OCStackResult result = OC_STACK_ERROR;
2678 CAResult_t caResult;
2679 CAToken_t token = NULL;
2680 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2681 ClientCB *clientCB = NULL;
2682 OCDoHandle resHandle = NULL;
2683 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2684 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2686 OCTransportAdapter adapter;
2687 OCTransportFlags flags;
2688 // the request contents are put here
2689 CARequestInfo_t requestInfo = {.method = CA_GET};
2690 // requestUri will be parsed into the following three variables
2691 OCDevAddr *devAddr = NULL;
2692 char *resourceUri = NULL;
2693 char *resourceType = NULL;
2696 * Support original behavior with address on resourceUri argument.
2698 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2699 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2703 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2704 if (result != OC_STACK_OK)
2706 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2710 else if (!checkProxyUri(options, numOptions))
2712 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2719 case OC_REST_OBSERVE:
2720 case OC_REST_OBSERVE_ALL:
2721 requestInfo.method = CA_GET;
2724 requestInfo.method = CA_PUT;
2727 requestInfo.method = CA_POST;
2729 case OC_REST_DELETE:
2730 requestInfo.method = CA_DELETE;
2732 case OC_REST_DISCOVER:
2734 #ifdef WITH_PRESENCE
2735 case OC_REST_PRESENCE:
2737 if (destination || devAddr)
2739 requestInfo.isMulticast = false;
2743 tmpDevAddr.adapter = adapter;
2744 tmpDevAddr.flags = flags;
2745 destination = &tmpDevAddr;
2746 requestInfo.isMulticast = true;
2748 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
2749 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
2750 // replacing method type with GET.
2751 requestInfo.method = CA_GET;
2754 result = OC_STACK_INVALID_METHOD;
2758 if (!devAddr && !destination)
2760 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2761 result = OC_STACK_INVALID_PARAM;
2765 /* If not original behavior, use destination argument */
2766 if (destination && !devAddr)
2768 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2771 result = OC_STACK_NO_MEMORY;
2774 *devAddr = *destination;
2777 resHandle = GenerateInvocationHandle();
2780 result = OC_STACK_NO_MEMORY;
2784 caResult = CAGenerateToken(&token, tokenLength);
2785 if (caResult != CA_STATUS_OK)
2787 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2788 result= OC_STACK_ERROR;
2792 // fill in request data
2793 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2794 requestInfo.info.token = token;
2795 requestInfo.info.tokenLength = tokenLength;
2797 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2799 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2800 options, numOptions, OC_OBSERVE_REGISTER);
2801 if (result != OC_STACK_OK)
2805 requestInfo.info.numOptions = numOptions + 1;
2809 requestInfo.info.numOptions = numOptions;
2810 requestInfo.info.options =
2811 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2812 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2813 numOptions * sizeof(CAHeaderOption_t));
2816 CopyDevAddrToEndpoint(devAddr, &endpoint);
2821 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2824 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2827 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2831 requestInfo.info.payload = NULL;
2832 requestInfo.info.payloadSize = 0;
2833 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2836 // prepare for response
2837 #ifdef WITH_PRESENCE
2838 if (method == OC_REST_PRESENCE)
2840 char *presenceUri = NULL;
2841 result = OCPreparePresence(&endpoint, &presenceUri,
2842 requestInfo.isMulticast);
2843 if (OC_STACK_OK != result)
2848 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2849 // Presence notification will form a canonical uri to
2850 // look for callbacks into the application.
2853 OICFree(resourceUri);
2855 resourceUri = presenceUri;
2859 // update resourceUri onto requestInfo after check presence uri
2860 requestInfo.info.resourceUri = resourceUri;
2862 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2863 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2864 method, devAddr, resourceUri, resourceType, ttl);
2865 if (OC_STACK_OK != result)
2870 devAddr = NULL; // Client CB list entry now owns it
2871 resourceUri = NULL; // Client CB list entry now owns it
2872 resourceType = NULL; // Client CB list entry now owns it
2874 #ifdef WITH_PRESENCE
2875 if (method == OC_REST_PRESENCE)
2877 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
2881 *handle = resHandle;
2889 result = OCSendRequest(&endpoint, &requestInfo);
2890 if (OC_STACK_OK != result)
2897 *handle = resHandle;
2901 if (result != OC_STACK_OK)
2903 OIC_LOG(ERROR, TAG, "OCDoResource error");
2904 FindAndDeleteClientCB(clientCB);
2905 CADestroyToken(token);
2913 // This is the owner of the payload object, so we free it
2914 OCPayloadDestroy(payload);
2915 OICFree(requestInfo.info.payload);
2917 OICFree(resourceUri);
2918 OICFree(resourceType);
2919 OICFree(requestInfo.info.options);
2923 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2927 * This ftn is implemented one of two ways in the case of observation:
2929 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2930 * Remove the callback associated on client side.
2931 * When the next notification comes in from server,
2932 * reply with RESET message to server.
2933 * Keep in mind that the server will react to RESET only
2934 * if the last notification was sent as CON
2936 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2937 * and it is associated with an observe request
2938 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2939 * Send CON Observe request to server with
2940 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2941 * Remove the callback associated on client side.
2943 OCStackResult ret = OC_STACK_OK;
2944 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2945 CARequestInfo_t requestInfo = {.method = CA_GET};
2949 return OC_STACK_INVALID_PARAM;
2952 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2955 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2956 return OC_STACK_ERROR;
2959 switch (clientCB->method)
2961 case OC_REST_OBSERVE:
2962 case OC_REST_OBSERVE_ALL:
2964 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2966 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2968 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2970 FindAndDeleteClientCB(clientCB);
2974 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2976 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2977 requestInfo.info.token = clientCB->token;
2978 requestInfo.info.tokenLength = clientCB->tokenLength;
2980 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2981 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2983 return OC_STACK_ERROR;
2985 requestInfo.info.numOptions = numOptions + 1;
2986 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2989 ret = OCSendRequest(&endpoint, &requestInfo);
2991 if (requestInfo.info.options)
2993 OICFree (requestInfo.info.options);
2995 if (requestInfo.info.resourceUri)
2997 OICFree (requestInfo.info.resourceUri);
3002 case OC_REST_DISCOVER:
3003 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3004 clientCB->requestUri);
3005 FindAndDeleteClientCB(clientCB);
3008 #ifdef WITH_PRESENCE
3009 case OC_REST_PRESENCE:
3010 FindAndDeleteClientCB(clientCB);
3015 ret = OC_STACK_INVALID_METHOD;
3023 * @brief Register Persistent storage callback.
3024 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3026 * OC_STACK_OK - No errors; Success
3027 * OC_STACK_INVALID_PARAM - Invalid parameter
3029 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3031 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3032 if(!persistentStorageHandler)
3034 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3035 return OC_STACK_INVALID_PARAM;
3039 if( !persistentStorageHandler->open ||
3040 !persistentStorageHandler->close ||
3041 !persistentStorageHandler->read ||
3042 !persistentStorageHandler->unlink ||
3043 !persistentStorageHandler->write)
3045 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3046 return OC_STACK_INVALID_PARAM;
3049 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3052 #ifdef WITH_PRESENCE
3054 OCStackResult OCProcessPresence()
3056 OCStackResult result = OC_STACK_OK;
3058 // the following line floods the log with messages that are irrelevant
3059 // to most purposes. Uncomment as needed.
3060 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3061 ClientCB* cbNode = NULL;
3062 OCClientResponse clientResponse;
3063 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3065 LL_FOREACH(cbList, cbNode)
3067 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3072 uint32_t now = GetTicks(0);
3073 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3074 cbNode->presence->TTLlevel);
3075 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3077 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3082 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3084 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3085 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3087 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3089 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3091 clientResponse.sequenceNumber = 0;
3092 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3093 clientResponse.devAddr = *cbNode->devAddr;
3094 FixUpClientResponse(&clientResponse);
3095 clientResponse.payload = NULL;
3097 // Increment the TTLLevel (going to a next state), so we don't keep
3098 // sending presence notification to client.
3099 cbNode->presence->TTLlevel++;
3100 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3101 cbNode->presence->TTLlevel);
3103 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3104 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3106 FindAndDeleteClientCB(cbNode);
3110 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3115 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3116 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3117 CARequestInfo_t requestInfo = {.method = CA_GET};
3119 OIC_LOG(DEBUG, TAG, "time to test server presence");
3121 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3123 requestData.type = CA_MSG_NONCONFIRM;
3124 requestData.token = cbNode->token;
3125 requestData.tokenLength = cbNode->tokenLength;
3126 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3127 requestInfo.method = CA_GET;
3128 requestInfo.info = requestData;
3130 result = OCSendRequest(&endpoint, &requestInfo);
3131 if (OC_STACK_OK != result)
3136 cbNode->presence->TTLlevel++;
3137 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3140 if (result != OC_STACK_OK)
3142 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3147 #endif // WITH_PRESENCE
3149 OCStackResult OCProcess()
3151 #ifdef WITH_PRESENCE
3152 OCProcessPresence();
3154 CAHandleRequestResponse();
3156 #ifdef ROUTING_GATEWAY
3166 #ifdef WITH_PRESENCE
3167 OCStackResult OCStartPresence(const uint32_t ttl)
3169 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3170 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3171 OCChangeResourceProperty(
3172 &(((OCResource *)presenceResource.handle)->resourceProperties),
3175 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3177 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3178 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3182 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3183 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3187 presenceResource.presenceTTL = ttl;
3189 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3191 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3193 presenceState = OC_PRESENCE_INITIALIZED;
3195 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3197 CAToken_t caToken = NULL;
3198 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3199 if (caResult != CA_STATUS_OK)
3201 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3202 CADestroyToken(caToken);
3203 return OC_STACK_ERROR;
3206 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3207 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3208 CADestroyToken(caToken);
3211 // Each time OCStartPresence is called
3212 // a different random 32-bit integer number is used
3213 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3215 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3216 OC_PRESENCE_TRIGGER_CREATE);
3219 OCStackResult OCStopPresence()
3221 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3222 OCStackResult result = OC_STACK_ERROR;
3224 if(presenceResource.handle)
3226 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3228 // make resource inactive
3229 result = OCChangeResourceProperty(
3230 &(((OCResource *) presenceResource.handle)->resourceProperties),
3234 if(result != OC_STACK_OK)
3237 "Changing the presence resource properties to ACTIVE not successful");
3241 return SendStopNotification();
3245 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3246 void* callbackParameter)
3248 defaultDeviceHandler = entityHandler;
3249 defaultDeviceHandlerCallbackParameter = callbackParameter;
3254 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3256 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3258 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3260 if (validatePlatformInfo(platformInfo))
3262 return SavePlatformInfo(platformInfo);
3266 return OC_STACK_INVALID_PARAM;
3271 return OC_STACK_ERROR;
3275 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3277 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3279 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3281 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3282 return OC_STACK_INVALID_PARAM;
3285 if (deviceInfo.types)
3287 OCStringLL *type = deviceInfo.types;
3288 OCResource *resource = findResource((OCResource *) deviceResource);
3291 return OC_STACK_INVALID_PARAM;
3296 OCBindResourceTypeToResource(deviceResource, type->value);
3300 return SaveDeviceInfo(deviceInfo);
3303 OCStackResult OCCreateResource(OCResourceHandle *handle,
3304 const char *resourceTypeName,
3305 const char *resourceInterfaceName,
3306 const char *uri, OCEntityHandler entityHandler,
3307 void* callbackParam,
3308 uint8_t resourceProperties)
3311 OCResource *pointer = NULL;
3312 OCStackResult result = OC_STACK_ERROR;
3314 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3316 if(myStackMode == OC_CLIENT)
3318 return OC_STACK_INVALID_PARAM;
3320 // Validate parameters
3321 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3323 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3324 return OC_STACK_INVALID_URI;
3326 // Is it presented during resource discovery?
3327 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3329 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3330 return OC_STACK_INVALID_PARAM;
3333 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3335 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3339 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3341 // Make sure resourceProperties bitmask has allowed properties specified
3342 if (resourceProperties
3343 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3344 OC_EXPLICIT_DISCOVERABLE
3353 OIC_LOG(ERROR, TAG, "Invalid property");
3354 return OC_STACK_INVALID_PARAM;
3357 // If the headResource is NULL, then no resources have been created...
3358 pointer = headResource;
3361 // At least one resources is in the resource list, so we need to search for
3362 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3365 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3367 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3368 return OC_STACK_INVALID_PARAM;
3370 pointer = pointer->next;
3373 // Create the pointer and insert it into the resource list
3374 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3377 result = OC_STACK_NO_MEMORY;
3380 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3382 insertResource(pointer);
3385 pointer->uri = OICStrdup(uri);
3388 result = OC_STACK_NO_MEMORY;
3392 // Set properties. Set OC_ACTIVE
3393 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3396 // Add the resourcetype to the resource
3397 result = BindResourceTypeToResource(pointer, resourceTypeName);
3398 if (result != OC_STACK_OK)
3400 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3404 // Add the resourceinterface to the resource
3405 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3406 if (result != OC_STACK_OK)
3408 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3412 // If an entity handler has been passed, attach it to the newly created
3413 // resource. Otherwise, set the default entity handler.
3416 pointer->entityHandler = entityHandler;
3417 pointer->entityHandlerCallbackParam = callbackParam;
3421 pointer->entityHandler = defaultResourceEHandler;
3422 pointer->entityHandlerCallbackParam = NULL;
3425 // Initialize a pointer indicating child resources in case of collection
3426 pointer->rsrcChildResourcesHead = NULL;
3429 result = OC_STACK_OK;
3431 #ifdef WITH_PRESENCE
3432 if (presenceResource.handle)
3434 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3435 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3439 if (result != OC_STACK_OK)
3441 // Deep delete of resource and other dynamic elements that it contains
3442 deleteResource(pointer);
3447 OCStackResult OCBindResource(
3448 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3450 OCResource *resource = NULL;
3451 OCChildResource *tempChildResource = NULL;
3452 OCChildResource *newChildResource = NULL;
3454 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3456 // Validate parameters
3457 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3458 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3459 // Container cannot contain itself
3460 if (collectionHandle == resourceHandle)
3462 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3463 return OC_STACK_INVALID_PARAM;
3466 // Use the handle to find the resource in the resource linked list
3467 resource = findResource((OCResource *) collectionHandle);
3470 OIC_LOG(ERROR, TAG, "Collection handle not found");
3471 return OC_STACK_INVALID_PARAM;
3474 // Look for an open slot to add add the child resource.
3475 // If found, add it and return success
3477 tempChildResource = resource->rsrcChildResourcesHead;
3479 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3481 // TODO: what if one of child resource was deregistered without unbinding?
3482 tempChildResource = tempChildResource->next;
3485 // Do memory allocation for child resource
3486 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3487 if(!newChildResource)
3489 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3490 return OC_STACK_ERROR;
3493 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3494 newChildResource->next = NULL;
3496 if(!resource->rsrcChildResourcesHead)
3498 resource->rsrcChildResourcesHead = newChildResource;
3501 tempChildResource->next = newChildResource;
3504 OIC_LOG(INFO, TAG, "resource bound");
3506 #ifdef WITH_PRESENCE
3507 if (presenceResource.handle)
3509 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3510 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3511 OC_PRESENCE_TRIGGER_CHANGE);
3518 OCStackResult OCUnBindResource(
3519 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3521 OCResource *resource = NULL;
3522 OCChildResource *tempChildResource = NULL;
3523 OCChildResource *tempLastChildResource = NULL;
3525 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3527 // Validate parameters
3528 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3529 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3530 // Container cannot contain itself
3531 if (collectionHandle == resourceHandle)
3533 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3534 return OC_STACK_INVALID_PARAM;
3537 // Use the handle to find the resource in the resource linked list
3538 resource = findResource((OCResource *) collectionHandle);
3541 OIC_LOG(ERROR, TAG, "Collection handle not found");
3542 return OC_STACK_INVALID_PARAM;
3545 // Look for an open slot to add add the child resource.
3546 // If found, add it and return success
3547 if(!resource->rsrcChildResourcesHead)
3549 OIC_LOG(INFO, TAG, "resource not found in collection");
3551 // Unable to add resourceHandle, so return error
3552 return OC_STACK_ERROR;
3556 tempChildResource = resource->rsrcChildResourcesHead;
3558 while (tempChildResource)
3560 if(tempChildResource->rsrcResource == resourceHandle)
3562 // if resource going to be unbinded is the head one.
3563 if( tempChildResource == resource->rsrcChildResourcesHead )
3565 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3566 OICFree(resource->rsrcChildResourcesHead);
3567 resource->rsrcChildResourcesHead = temp;
3572 OCChildResource *temp = tempChildResource->next;
3573 OICFree(tempChildResource);
3574 tempLastChildResource->next = temp;
3578 OIC_LOG(INFO, TAG, "resource unbound");
3580 // Send notification when resource is unbounded successfully.
3581 #ifdef WITH_PRESENCE
3582 if (presenceResource.handle)
3584 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3585 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3586 OC_PRESENCE_TRIGGER_CHANGE);
3589 tempChildResource = NULL;
3590 tempLastChildResource = NULL;
3596 tempLastChildResource = tempChildResource;
3597 tempChildResource = tempChildResource->next;
3600 OIC_LOG(INFO, TAG, "resource not found in collection");
3602 tempChildResource = NULL;
3603 tempLastChildResource = NULL;
3605 // Unable to add resourceHandle, so return error
3606 return OC_STACK_ERROR;
3609 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3611 if (!resourceItemName)
3615 // Per RFC 6690 only registered values must follow the first rule below.
3616 // At this point in time the only values registered begin with "core", and
3617 // all other values are specified as opaque strings where multiple values
3618 // are separated by a space.
3619 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3621 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3623 if (resourceItemName[index] != '.'
3624 && resourceItemName[index] != '-'
3625 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3626 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3634 for (size_t index = 0; resourceItemName[index]; ++index)
3636 if (resourceItemName[index] == ' '
3637 || resourceItemName[index] == '\t'
3638 || resourceItemName[index] == '\r'
3639 || resourceItemName[index] == '\n')
3649 OCStackResult BindResourceTypeToResource(OCResource* resource,
3650 const char *resourceTypeName)
3652 OCResourceType *pointer = NULL;
3654 OCStackResult result = OC_STACK_ERROR;
3656 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3658 if (!ValidateResourceTypeInterface(resourceTypeName))
3660 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3661 return OC_STACK_INVALID_PARAM;
3664 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3667 result = OC_STACK_NO_MEMORY;
3671 str = OICStrdup(resourceTypeName);
3674 result = OC_STACK_NO_MEMORY;
3677 pointer->resourcetypename = str;
3678 pointer->next = NULL;
3680 insertResourceType(resource, pointer);
3681 result = OC_STACK_OK;
3684 if (result != OC_STACK_OK)
3693 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3694 const char *resourceInterfaceName)
3696 OCResourceInterface *pointer = NULL;
3698 OCStackResult result = OC_STACK_ERROR;
3700 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3702 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3704 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3705 return OC_STACK_INVALID_PARAM;
3708 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3710 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3713 result = OC_STACK_NO_MEMORY;
3717 str = OICStrdup(resourceInterfaceName);
3720 result = OC_STACK_NO_MEMORY;
3723 pointer->name = str;
3725 // Bind the resourceinterface to the resource
3726 insertResourceInterface(resource, pointer);
3728 result = OC_STACK_OK;
3731 if (result != OC_STACK_OK)
3740 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3741 const char *resourceTypeName)
3744 OCStackResult result = OC_STACK_ERROR;
3745 OCResource *resource = NULL;
3747 resource = findResource((OCResource *) handle);
3750 OIC_LOG(ERROR, TAG, "Resource not found");
3751 return OC_STACK_ERROR;
3754 result = BindResourceTypeToResource(resource, resourceTypeName);
3756 #ifdef WITH_PRESENCE
3757 if(presenceResource.handle)
3759 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3760 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3767 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3768 const char *resourceInterfaceName)
3771 OCStackResult result = OC_STACK_ERROR;
3772 OCResource *resource = NULL;
3774 resource = findResource((OCResource *) handle);
3777 OIC_LOG(ERROR, TAG, "Resource not found");
3778 return OC_STACK_ERROR;
3781 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3783 #ifdef WITH_PRESENCE
3784 if (presenceResource.handle)
3786 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3787 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3794 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3796 OCResource *pointer = headResource;
3798 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3802 *numResources = *numResources + 1;
3803 pointer = pointer->next;
3808 OCResourceHandle OCGetResourceHandle(uint8_t index)
3810 OCResource *pointer = headResource;
3812 for( uint8_t i = 0; i < index && pointer; ++i)
3814 pointer = pointer->next;
3816 return (OCResourceHandle) pointer;
3819 OCStackResult OCDeleteResource(OCResourceHandle handle)
3823 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3824 return OC_STACK_INVALID_PARAM;
3827 OCResource *resource = findResource((OCResource *) handle);
3828 if (resource == NULL)
3830 OIC_LOG(ERROR, TAG, "Resource not found");
3831 return OC_STACK_NO_RESOURCE;
3834 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3836 OIC_LOG(ERROR, TAG, "Error deleting resource");
3837 return OC_STACK_ERROR;
3843 const char *OCGetResourceUri(OCResourceHandle handle)
3845 OCResource *resource = NULL;
3847 resource = findResource((OCResource *) handle);
3850 return resource->uri;
3852 return (const char *) NULL;
3855 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3857 OCResource *resource = NULL;
3859 resource = findResource((OCResource *) handle);
3862 return resource->resourceProperties;
3864 return (OCResourceProperty)-1;
3867 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3868 uint8_t *numResourceTypes)
3870 OCResource *resource = NULL;
3871 OCResourceType *pointer = NULL;
3873 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3874 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3876 *numResourceTypes = 0;
3878 resource = findResource((OCResource *) handle);
3881 pointer = resource->rsrcType;
3884 *numResourceTypes = *numResourceTypes + 1;
3885 pointer = pointer->next;
3891 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3893 OCResourceType *resourceType = NULL;
3895 resourceType = findResourceTypeAtIndex(handle, index);
3898 return resourceType->resourcetypename;
3900 return (const char *) NULL;
3903 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3904 uint8_t *numResourceInterfaces)
3906 OCResourceInterface *pointer = NULL;
3907 OCResource *resource = NULL;
3909 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3910 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3912 *numResourceInterfaces = 0;
3913 resource = findResource((OCResource *) handle);
3916 pointer = resource->rsrcInterface;
3919 *numResourceInterfaces = *numResourceInterfaces + 1;
3920 pointer = pointer->next;
3926 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3928 OCResourceInterface *resourceInterface = NULL;
3930 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3931 if (resourceInterface)
3933 return resourceInterface->name;
3935 return (const char *) NULL;
3938 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3941 OCResource *resource = NULL;
3942 OCChildResource *tempChildResource = NULL;
3945 resource = findResource((OCResource *) collectionHandle);
3951 tempChildResource = resource->rsrcChildResourcesHead;
3953 while(tempChildResource)
3957 return tempChildResource->rsrcResource;
3960 tempChildResource = tempChildResource->next;
3963 // In this case, the number of resource handles in the collection exceeds the index
3964 tempChildResource = NULL;
3968 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3969 OCEntityHandler entityHandler,
3970 void* callbackParam)
3972 OCResource *resource = NULL;
3974 // Validate parameters
3975 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3977 // Use the handle to find the resource in the resource linked list
3978 resource = findResource((OCResource *)handle);
3981 OIC_LOG(ERROR, TAG, "Resource not found");
3982 return OC_STACK_ERROR;
3986 resource->entityHandler = entityHandler;
3987 resource->entityHandlerCallbackParam = callbackParam;
3989 #ifdef WITH_PRESENCE
3990 if (presenceResource.handle)
3992 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3993 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4000 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4002 OCResource *resource = NULL;
4004 resource = findResource((OCResource *)handle);
4007 OIC_LOG(ERROR, TAG, "Resource not found");
4012 return resource->entityHandler;
4015 void incrementSequenceNumber(OCResource * resPtr)
4017 // Increment the sequence number
4018 resPtr->sequenceNum += 1;
4019 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4021 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4026 #ifdef WITH_PRESENCE
4027 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4028 OCPresenceTrigger trigger)
4030 OIC_LOG(INFO, TAG, "SendPresenceNotification");
4031 OCResource *resPtr = NULL;
4032 OCStackResult result = OC_STACK_ERROR;
4033 OCMethod method = OC_REST_PRESENCE;
4034 uint32_t maxAge = 0;
4035 resPtr = findResource((OCResource *) presenceResource.handle);
4038 return OC_STACK_NO_RESOURCE;
4041 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4043 maxAge = presenceResource.presenceTTL;
4045 result = SendAllObserverNotification(method, resPtr, maxAge,
4046 trigger, resourceType, OC_LOW_QOS);
4052 OCStackResult SendStopNotification()
4054 OIC_LOG(INFO, TAG, "SendStopNotification");
4055 OCResource *resPtr = NULL;
4056 OCStackResult result = OC_STACK_ERROR;
4057 OCMethod method = OC_REST_PRESENCE;
4058 resPtr = findResource((OCResource *) presenceResource.handle);
4061 return OC_STACK_NO_RESOURCE;
4064 // maxAge is 0. ResourceType is NULL.
4065 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4071 #endif // WITH_PRESENCE
4072 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4074 OCResource *resPtr = NULL;
4075 OCStackResult result = OC_STACK_ERROR;
4076 OCMethod method = OC_REST_NOMETHOD;
4077 uint32_t maxAge = 0;
4079 OIC_LOG(INFO, TAG, "Notifying all observers");
4080 #ifdef WITH_PRESENCE
4081 if(handle == presenceResource.handle)
4085 #endif // WITH_PRESENCE
4086 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4088 // Verify that the resource exists
4089 resPtr = findResource ((OCResource *) handle);
4092 return OC_STACK_NO_RESOURCE;
4096 //only increment in the case of regular observing (not presence)
4097 incrementSequenceNumber(resPtr);
4098 method = OC_REST_OBSERVE;
4099 maxAge = MAX_OBSERVE_AGE;
4100 #ifdef WITH_PRESENCE
4101 result = SendAllObserverNotification (method, resPtr, maxAge,
4102 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4104 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4111 OCNotifyListOfObservers (OCResourceHandle handle,
4112 OCObservationId *obsIdList,
4113 uint8_t numberOfIds,
4114 const OCRepPayload *payload,
4115 OCQualityOfService qos)
4117 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4119 OCResource *resPtr = NULL;
4120 //TODO: we should allow the server to define this
4121 uint32_t maxAge = MAX_OBSERVE_AGE;
4123 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4124 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4125 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4127 resPtr = findResource ((OCResource *) handle);
4128 if (NULL == resPtr || myStackMode == OC_CLIENT)
4130 return OC_STACK_NO_RESOURCE;
4134 incrementSequenceNumber(resPtr);
4136 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4137 payload, maxAge, qos));
4140 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4142 OCStackResult result = OC_STACK_ERROR;
4143 OCServerRequest *serverRequest = NULL;
4145 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4147 // Validate input parameters
4148 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4149 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4152 // Get pointer to request info
4153 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4156 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4157 result = serverRequest->ehResponseHandler(ehResponse);
4163 //#ifdef DIRECT_PAIRING
4164 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4166 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4167 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4169 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4173 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4176 const OCDPDev_t* OCGetDirectPairedDevices()
4178 return (const OCDPDev_t*)DPGetPairedDevices();
4181 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4182 OCDirectPairingCB resultCallback)
4184 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4185 if(NULL == peer || NULL == pinNumber)
4187 OIC_LOG(ERROR, TAG, "Invalid parameters");
4188 return OC_STACK_INVALID_PARAM;
4190 if (NULL == resultCallback)
4192 OIC_LOG(ERROR, TAG, "Invalid callback");
4193 return OC_STACK_INVALID_CALLBACK;
4196 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4197 pinNumber, (OCDirectPairingResultCB)resultCallback);
4199 //#endif // DIRECT_PAIRING
4201 //-----------------------------------------------------------------------------
4202 // Private internal function definitions
4203 //-----------------------------------------------------------------------------
4204 static OCDoHandle GenerateInvocationHandle()
4206 OCDoHandle handle = NULL;
4207 // Generate token here, it will be deleted when the transaction is deleted
4208 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4211 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4217 #ifdef WITH_PRESENCE
4218 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4219 OCResourceProperty resourceProperties, uint8_t enable)
4223 return OC_STACK_INVALID_PARAM;
4225 if (resourceProperties
4226 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4228 OIC_LOG(ERROR, TAG, "Invalid property");
4229 return OC_STACK_INVALID_PARAM;
4233 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4237 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4243 OCStackResult initResources()
4245 OCStackResult result = OC_STACK_OK;
4247 headResource = NULL;
4248 tailResource = NULL;
4249 // Init Virtual Resources
4250 #ifdef WITH_PRESENCE
4251 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4253 result = OCCreateResource(&presenceResource.handle,
4254 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4256 OC_RSRVD_PRESENCE_URI,
4260 //make resource inactive
4261 result = OCChangeResourceProperty(
4262 &(((OCResource *) presenceResource.handle)->resourceProperties),
4265 #ifndef WITH_ARDUINO
4266 if (result == OC_STACK_OK)
4268 result = SRMInitSecureResources();
4272 if(result == OC_STACK_OK)
4274 CreateResetProfile();
4275 result = OCCreateResource(&deviceResource,
4276 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4277 OC_RSRVD_INTERFACE_DEFAULT,
4278 OC_RSRVD_DEVICE_URI,
4282 if(result == OC_STACK_OK)
4284 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4285 OC_RSRVD_INTERFACE_READ);
4289 if(result == OC_STACK_OK)
4291 result = OCCreateResource(&platformResource,
4292 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4293 OC_RSRVD_INTERFACE_DEFAULT,
4294 OC_RSRVD_PLATFORM_URI,
4298 if(result == OC_STACK_OK)
4300 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4301 OC_RSRVD_INTERFACE_READ);
4308 void insertResource(OCResource *resource)
4312 headResource = resource;
4313 tailResource = resource;
4317 tailResource->next = resource;
4318 tailResource = resource;
4320 resource->next = NULL;
4323 OCResource *findResource(OCResource *resource)
4325 OCResource *pointer = headResource;
4329 if (pointer == resource)
4333 pointer = pointer->next;
4338 void deleteAllResources()
4340 OCResource *pointer = headResource;
4341 OCResource *temp = NULL;
4345 temp = pointer->next;
4346 #ifdef WITH_PRESENCE
4347 if (pointer != (OCResource *) presenceResource.handle)
4349 #endif // WITH_PRESENCE
4350 deleteResource(pointer);
4351 #ifdef WITH_PRESENCE
4353 #endif // WITH_PRESENCE
4356 memset(&platformResource, 0, sizeof(platformResource));
4357 memset(&deviceResource, 0, sizeof(deviceResource));
4359 memset(&brokerResource, 0, sizeof(brokerResource));
4362 SRMDeInitSecureResources();
4364 #ifdef WITH_PRESENCE
4365 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4366 // presence notification attributed to their deletion to be processed.
4367 deleteResource((OCResource *) presenceResource.handle);
4368 memset(&presenceResource, 0, sizeof(presenceResource));
4369 #endif // WITH_PRESENCE
4372 OCStackResult deleteResource(OCResource *resource)
4374 OCResource *prev = NULL;
4375 OCResource *temp = NULL;
4378 OIC_LOG(DEBUG,TAG,"resource is NULL");
4379 return OC_STACK_INVALID_PARAM;
4382 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4384 temp = headResource;
4387 if (temp == resource)
4389 // Invalidate all Resource Properties.
4390 resource->resourceProperties = (OCResourceProperty) 0;
4391 #ifdef WITH_PRESENCE
4392 if(resource != (OCResource *) presenceResource.handle)
4394 #endif // WITH_PRESENCE
4395 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4396 #ifdef WITH_PRESENCE
4399 if(presenceResource.handle)
4401 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4402 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4405 // Only resource in list.
4406 if (temp == headResource && temp == tailResource)
4408 headResource = NULL;
4409 tailResource = NULL;
4412 else if (temp == headResource)
4414 headResource = temp->next;
4417 else if (temp == tailResource)
4419 tailResource = prev;
4420 tailResource->next = NULL;
4424 prev->next = temp->next;
4427 deleteResourceElements(temp);
4438 return OC_STACK_ERROR;
4441 void deleteResourceElements(OCResource *resource)
4448 OICFree(resource->uri);
4449 deleteResourceType(resource->rsrcType);
4450 deleteResourceInterface(resource->rsrcInterface);
4453 void deleteResourceType(OCResourceType *resourceType)
4455 OCResourceType *pointer = resourceType;
4456 OCResourceType *next = NULL;
4460 next = pointer->next;
4461 OICFree(pointer->resourcetypename);
4467 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4469 OCResourceInterface *pointer = resourceInterface;
4470 OCResourceInterface *next = NULL;
4474 next = pointer->next;
4475 OICFree(pointer->name);
4481 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4483 OCResourceType *pointer = NULL;
4484 OCResourceType *previous = NULL;
4485 if (!resource || !resourceType)
4489 // resource type list is empty.
4490 else if (!resource->rsrcType)
4492 resource->rsrcType = resourceType;
4496 pointer = resource->rsrcType;
4500 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4502 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4503 OICFree(resourceType->resourcetypename);
4504 OICFree(resourceType);
4508 pointer = pointer->next;
4513 previous->next = resourceType;
4516 resourceType->next = NULL;
4518 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4521 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4523 OCResource *resource = NULL;
4524 OCResourceType *pointer = NULL;
4526 // Find the specified resource
4527 resource = findResource((OCResource *) handle);
4533 // Make sure a resource has a resourcetype
4534 if (!resource->rsrcType)
4539 // Iterate through the list
4540 pointer = resource->rsrcType;
4541 for(uint8_t i = 0; i< index && pointer; ++i)
4543 pointer = pointer->next;
4548 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4550 if(resourceTypeList && resourceTypeName)
4552 OCResourceType * rtPointer = resourceTypeList;
4553 while(resourceTypeName && rtPointer)
4555 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4556 if(rtPointer->resourcetypename &&
4557 strcmp(resourceTypeName, (const char *)
4558 (rtPointer->resourcetypename)) == 0)
4562 rtPointer = rtPointer->next;
4570 * Insert a new interface into interface linked list only if not already present.
4571 * If alredy present, 2nd arg is free'd.
4572 * Default interface will always be first if present.
4574 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4576 OCResourceInterface *pointer = NULL;
4577 OCResourceInterface *previous = NULL;
4579 newInterface->next = NULL;
4581 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4583 if (!*firstInterface)
4585 // If first interface is not oic.if.baseline, by default add it as first interface type.
4586 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4588 *firstInterface = newInterface;
4592 OCStackResult result = BindResourceInterfaceToResource(resource,
4593 OC_RSRVD_INTERFACE_DEFAULT);
4594 if (result != OC_STACK_OK)
4596 OICFree(newInterface->name);
4597 OICFree(newInterface);
4600 if (*firstInterface)
4602 (*firstInterface)->next = newInterface;
4606 // If once add oic.if.baseline, later too below code take care of freeing memory.
4607 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4609 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4611 OICFree(newInterface->name);
4612 OICFree(newInterface);
4615 // This code will not hit anymore, keeping
4618 newInterface->next = *firstInterface;
4619 *firstInterface = newInterface;
4624 pointer = *firstInterface;
4627 if (strcmp(newInterface->name, pointer->name) == 0)
4629 OICFree(newInterface->name);
4630 OICFree(newInterface);
4634 pointer = pointer->next;
4639 previous->next = newInterface;
4644 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4647 OCResource *resource = NULL;
4648 OCResourceInterface *pointer = NULL;
4650 // Find the specified resource
4651 resource = findResource((OCResource *) handle);
4657 // Make sure a resource has a resourceinterface
4658 if (!resource->rsrcInterface)
4663 // Iterate through the list
4664 pointer = resource->rsrcInterface;
4666 for (uint8_t i = 0; i < index && pointer; ++i)
4668 pointer = pointer->next;
4674 * This function splits the uri using the '?' delimiter.
4675 * "uriWithoutQuery" is the block of characters between the beginning
4676 * till the delimiter or '\0' which ever comes first.
4677 * "query" is whatever is to the right of the delimiter if present.
4678 * No delimiter sets the query to NULL.
4679 * If either are present, they will be malloc'ed into the params 2, 3.
4680 * The first param, *uri is left untouched.
4682 * NOTE: This function does not account for whitespace at the end of the uri NOR
4683 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4684 * part of the query.
4686 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4690 return OC_STACK_INVALID_URI;
4692 if(!query || !uriWithoutQuery)
4694 return OC_STACK_INVALID_PARAM;
4698 *uriWithoutQuery = NULL;
4700 size_t uriWithoutQueryLen = 0;
4701 size_t queryLen = 0;
4702 size_t uriLen = strlen(uri);
4704 char *pointerToDelimiter = strstr(uri, "?");
4706 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4707 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4709 if (uriWithoutQueryLen)
4711 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4712 if (!*uriWithoutQuery)
4716 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4720 *query = (char *) OICCalloc(queryLen + 1, 1);
4723 OICFree(*uriWithoutQuery);
4724 *uriWithoutQuery = NULL;
4727 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4733 return OC_STACK_NO_MEMORY;
4736 static const OicUuid_t* OCGetServerInstanceID(void)
4738 static bool generated = false;
4739 static OicUuid_t sid;
4745 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4747 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4754 const char* OCGetServerInstanceIDString(void)
4756 static bool generated = false;
4757 static char sidStr[UUID_STRING_SIZE];
4764 const OicUuid_t *sid = OCGetServerInstanceID();
4765 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4767 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4775 CAResult_t OCSelectNetwork()
4777 CAResult_t retResult = CA_STATUS_FAILED;
4778 CAResult_t caResult = CA_STATUS_OK;
4780 CATransportAdapter_t connTypes[] = {
4782 CA_ADAPTER_RFCOMM_BTEDR,
4783 CA_ADAPTER_GATT_BTLE,
4786 ,CA_ADAPTER_REMOTE_ACCESS
4793 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4795 for(int i = 0; i < numConnTypes; i++)
4797 // If CA status is not initialized, CASelectNetwork() will not be called.
4798 if (caResult != CA_STATUS_NOT_INITIALIZED)
4800 caResult = CASelectNetwork(connTypes[i]);
4801 if (caResult == CA_STATUS_OK)
4803 retResult = CA_STATUS_OK;
4808 if (retResult != CA_STATUS_OK)
4810 return caResult; // Returns error of appropriate transport that failed fatally.
4816 OCStackResult CAResultToOCResult(CAResult_t caResult)
4822 case CA_STATUS_INVALID_PARAM:
4823 return OC_STACK_INVALID_PARAM;
4824 case CA_ADAPTER_NOT_ENABLED:
4825 return OC_STACK_ADAPTER_NOT_ENABLED;
4826 case CA_SERVER_STARTED_ALREADY:
4828 case CA_SERVER_NOT_STARTED:
4829 return OC_STACK_ERROR;
4830 case CA_DESTINATION_NOT_REACHABLE:
4831 return OC_STACK_COMM_ERROR;
4832 case CA_SOCKET_OPERATION_FAILED:
4833 return OC_STACK_COMM_ERROR;
4834 case CA_SEND_FAILED:
4835 return OC_STACK_COMM_ERROR;
4836 case CA_RECEIVE_FAILED:
4837 return OC_STACK_COMM_ERROR;
4838 case CA_MEMORY_ALLOC_FAILED:
4839 return OC_STACK_NO_MEMORY;
4840 case CA_REQUEST_TIMEOUT:
4841 return OC_STACK_TIMEOUT;
4842 case CA_DESTINATION_DISCONNECTED:
4843 return OC_STACK_COMM_ERROR;
4844 case CA_STATUS_FAILED:
4845 return OC_STACK_ERROR;
4846 case CA_NOT_SUPPORTED:
4847 return OC_STACK_NOTIMPL;
4849 return OC_STACK_ERROR;
4853 bool OCResultToSuccess(OCStackResult ocResult)
4858 case OC_STACK_RESOURCE_CREATED:
4859 case OC_STACK_RESOURCE_DELETED:
4860 case OC_STACK_CONTINUE:
4861 case OC_STACK_RESOURCE_CHANGED:
4862 case OC_STACK_SLOW_RESOURCE:
4870 OCStackResult OCSetProxyURI(const char *uri)
4872 return CAResultToOCResult(CASetProxyUri(uri));
4876 #if defined(RD_CLIENT) || defined(RD_SERVER)
4877 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
4879 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4881 OCResource *resource = NULL;
4883 resource = findResource((OCResource *) handle);
4886 OIC_LOG(ERROR, TAG, "Resource not found");
4887 return OC_STACK_ERROR;
4890 resource->ins = ins;
4896 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
4897 const OCClientResponse *response)
4899 // Validate input parameters
4900 VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
4901 VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
4903 char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
4906 return OC_STACK_NO_MEMORY;
4908 strncpy(targetUri, requestUri, strlen(requestUri) + 1);
4910 if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
4912 OIC_LOG(DEBUG, TAG, "update the ins of published resource");
4914 char rdPubUri[MAX_URI_LENGTH] = { 0 };
4915 snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
4916 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
4918 if (strcmp(rdPubUri, targetUri) == 0)
4920 // Update resource unique id in stack.
4923 if (response->payload)
4925 OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
4926 OCRepPayload **links = NULL;
4927 size_t dimensions[MAX_REP_ARRAY_DEPTH];
4928 if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
4929 &links, dimensions))
4932 for (; i < dimensions[0]; i++)
4935 if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
4937 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
4939 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
4941 OCBindResourceInsToResource(handle, ins);
4950 else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
4952 OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
4954 uint8_t numResources = 0;
4955 OCGetNumberOfResources(&numResources);
4957 char *ins = strstr(targetUri, OC_RSRVD_INS);
4960 for (uint8_t i = 0; i < numResources; i++)
4962 OCResourceHandle resHandle = OCGetResourceHandle(i);
4965 OCBindResourceInsToResource(resHandle, 0);
4971 const char *token = "&";
4972 char *iterTokenPtr = NULL;
4973 char *start = strtok_r(targetUri, token, &iterTokenPtr);
4975 while (start != NULL)
4977 char *query = start;
4978 query = strstr(query, OC_RSRVD_INS);
4981 uint8_t queryIns = atoi(query + 4);
4982 for (uint8_t i = 0; i < numResources; i++)
4984 OCResourceHandle resHandle = OCGetResourceHandle(i);
4988 OCGetResourceIns(resHandle, &resIns);
4989 if (queryIns && queryIns == resIns)
4991 OCBindResourceInsToResource(resHandle, 0);
4997 start = strtok_r(NULL, token, &iterTokenPtr);
5006 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5010 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5014 OCResource *pointer = headResource;
5018 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5020 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5023 pointer = pointer->next;
5028 OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
5030 OCResource *resource = NULL;
5032 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5033 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5035 resource = findResource((OCResource *) handle);
5038 *ins = resource->ins;
5041 return OC_STACK_ERROR;
5045 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5046 void* optionData, size_t optionDataLength)
5050 OIC_LOG (INFO, TAG, "Header options are NULL");
5051 return OC_STACK_INVALID_PARAM;
5056 OIC_LOG (INFO, TAG, "optionData are NULL");
5057 return OC_STACK_INVALID_PARAM;
5062 OIC_LOG (INFO, TAG, "numOptions is NULL");
5063 return OC_STACK_INVALID_PARAM;
5066 if (*numOptions >= MAX_HEADER_OPTIONS)
5068 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5069 return OC_STACK_NO_MEMORY;
5072 ocHdrOpt += *numOptions;
5073 ocHdrOpt->protocolID = OC_COAP_ID;
5074 ocHdrOpt->optionID = optionID;
5075 ocHdrOpt->optionLength =
5076 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
5077 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5078 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5084 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5085 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5087 if (!ocHdrOpt || !numOptions)
5089 OIC_LOG (INFO, TAG, "No options present");
5095 OIC_LOG (INFO, TAG, "optionData are NULL");
5096 return OC_STACK_INVALID_PARAM;
5099 if (!receivedDataLength)
5101 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5102 return OC_STACK_INVALID_PARAM;
5105 for (uint8_t i = 0; i < numOptions; i++)
5107 if (ocHdrOpt[i].optionID == optionID)
5109 if (optionDataLength >= ocHdrOpt->optionLength)
5111 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5112 *receivedDataLength = ocHdrOpt->optionLength;
5117 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5118 return OC_STACK_ERROR;
5125 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5127 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5128 if (g_adapterHandler)
5130 g_adapterHandler(adapter, enabled);
5134 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5136 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5137 if (g_connectionHandler)
5139 g_connectionHandler(info, isConnected);
5143 void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
5144 CAConnectionStateChangedCB connectionHandler)
5146 OIC_LOG(DEBUG, TAG, "OCSetNetworkMonitorHandler");
5147 g_adapterHandler = adapterHandler;
5148 g_connectionHandler = connectionHandler;
5151 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5154 OCStackResult ret = OC_STACK_ERROR;
5156 ret = GetDoxmDeviceID(&oicUuid);
5157 if (OC_STACK_OK == ret)
5159 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5163 OIC_LOG(ERROR, TAG, "Device ID Get error");
5168 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5171 OCStackResult ret = OC_STACK_ERROR;
5173 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5174 for (int i = 0; i < UUID_LENGTH; i++)
5176 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5178 ret = SetDoxmDeviceID(&oicUuid);