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"
40 #include "iotivity_debug.h"
50 #include "ocstackinternal.h"
51 #include "ocresourcehandler.h"
52 #include "occlientcb.h"
53 #include "ocobserve.h"
55 #include "oic_malloc.h"
56 #include "oic_string.h"
59 #include "ocserverrequest.h"
60 #include "secureresourcemanager.h"
61 #include "psinterface.h"
62 #include "doxmresource.h"
64 #include "cainterface.h"
65 #include "ocpayload.h"
66 #include "ocpayloadcbor.h"
67 #include "cautilinterface.h"
68 #include "cainterface.h"
70 #include "ocendpoint.h"
72 #include "platform_features.h"
74 #if defined(TCP_ADAPTER) && defined(WITH_CLOUD)
75 #include "occonnectionmanager.h"
78 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
79 #include "routingutility.h"
80 #ifdef ROUTING_GATEWAY
81 #include "routingmanager.h"
86 #include "oickeepalive.h"
89 //#ifdef DIRECT_PAIRING
90 #include "directpairing.h"
93 #ifdef HAVE_ARDUINO_TIME_H
96 #ifdef HAVE_SYS_TIME_H
99 #include <coap/coap.h>
101 #ifdef HAVE_ARPA_INET_H
102 #include <arpa/inet.h>
106 #define UINT32_MAX (0xFFFFFFFFUL)
109 //-----------------------------------------------------------------------------
111 //-----------------------------------------------------------------------------
114 OC_STACK_UNINITIALIZED = 0,
121 OC_PRESENCE_UNINITIALIZED = 0,
122 OC_PRESENCE_INITIALIZED
126 //-----------------------------------------------------------------------------
128 //-----------------------------------------------------------------------------
129 static OCStackState stackState = OC_STACK_UNINITIALIZED;
131 OCResource *headResource = NULL;
132 static OCResource *tailResource = NULL;
133 static OCResourceHandle platformResource = {0};
134 static OCResourceHandle deviceResource = {0};
135 static OCResourceHandle introspectionResource = {0};
136 static OCResourceHandle introspectionPayloadResource = {0};
137 static OCResourceHandle wellKnownResource = {0};
139 static OCResourceHandle brokerResource = {0};
143 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
144 static PresenceResource presenceResource = {0};
145 static uint8_t PresenceTimeOutSize = 0;
146 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
149 static OCMode myStackMode;
151 //TODO: revisit this design
152 static bool gRASetInfo = false;
154 OCDeviceEntityHandler defaultDeviceHandler;
155 void* defaultDeviceHandlerCallbackParameter = NULL;
156 static const char COAP_TCP_SCHEME[] = "coap+tcp:";
157 static const char COAPS_TCP_SCHEME[] = "coaps+tcp:";
158 static const char CORESPEC[] = "core";
160 CAAdapterStateChangedCB g_adapterHandler = NULL;
161 CAConnectionStateChangedCB g_connectionHandler = NULL;
162 // Persistent Storage callback handler for open/read/write/close/unlink
163 static OCPersistentStorage *g_PersistentStorageHandler = NULL;
164 // Number of users of OCStack, based on the successful calls to OCInit2 prior to OCStop
165 // The variable must not be declared static because it is also referenced by the unit test
166 uint32_t g_ocStackStartCount = 0;
167 // Number of threads currently executing OCInit2 or OCStop
168 volatile int32_t g_ocStackStartStopThreadCount = 0;
170 //-----------------------------------------------------------------------------
172 //-----------------------------------------------------------------------------
173 #define TAG "OIC_RI_STACK"
174 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
175 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
176 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
177 TAG, #arg " is NULL"); return (retVal); } }
178 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
179 TAG, #arg " is NULL"); return; } }
180 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
183 //TODO: we should allow the server to define this
184 #define MAX_OBSERVE_AGE (0x2FFFFUL)
186 #define MILLISECONDS_PER_SECOND (1000)
188 //-----------------------------------------------------------------------------
189 // Private internal function prototypes
190 //-----------------------------------------------------------------------------
193 * Generate handle of OCDoResource invocation for callback management.
195 * @return Generated OCDoResource handle.
197 static OCDoHandle GenerateInvocationHandle();
200 * Initialize resource data structures, variables, etc.
202 * @return ::OC_STACK_OK on success, some other value upon failure.
204 static OCStackResult initResources();
207 * Add a resource to the end of the linked list of resources.
209 * @param resource Resource to be added
211 static void insertResource(OCResource *resource);
214 * Find a resource in the linked list of resources.
216 * @param resource Resource to be found.
217 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
220 static OCResource *findResource(OCResource *resource);
223 * Insert a resource type into a resource's resource type linked list.
224 * If resource type already exists, it will not be inserted and the
225 * resourceType will be free'd.
226 * resourceType->next should be null to avoid memory leaks.
227 * Function returns silently for null args.
229 * @param resource Resource where resource type is to be inserted.
230 * @param resourceType Resource type to be inserted.
232 static void insertResourceType(OCResource *resource,
233 OCResourceType *resourceType);
236 * Get a resource type at the specified index within a resource.
238 * @param handle Handle of resource.
239 * @param index Index of resource type.
241 * @return Pointer to resource type if found, NULL otherwise.
243 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
247 * Insert a resource interface into a resource's resource interface linked list.
248 * If resource interface already exists, it will not be inserted and the
249 * resourceInterface will be free'd.
250 * resourceInterface->next should be null to avoid memory leaks.
252 * @param resource Resource where resource interface is to be inserted.
253 * @param resourceInterface Resource interface to be inserted.
255 static void insertResourceInterface(OCResource *resource,
256 OCResourceInterface *resourceInterface);
259 * Get a resource interface at the specified index within a resource.
261 * @param handle Handle of resource.
262 * @param index Index of resource interface.
264 * @return Pointer to resource interface if found, NULL otherwise.
266 static OCResourceInterface *findResourceInterfaceAtIndex(
267 OCResourceHandle handle, uint8_t index);
270 * Delete all of the dynamically allocated elements that were created for the resource type.
272 * @param resourceType Specified resource type.
274 static void deleteResourceType(OCResourceType *resourceType);
277 * Delete all of the dynamically allocated elements that were created for the resource interface.
279 * @param resourceInterface Specified resource interface.
281 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
284 * Delete all of the dynamically allocated elements that were created for the resource.
286 * @param resource Specified resource.
288 static void deleteResourceElements(OCResource *resource);
291 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
294 * @param handle Handle of resource to be deleted.
296 * @return ::OC_STACK_OK on success, some other value upon failure.
298 static OCStackResult deleteResource(OCResource *resource);
301 * Delete all of the resources in the resource list.
303 static void deleteAllResources();
306 * Increment resource sequence number. Handles rollover.
308 * @param resPtr Pointer to resource.
310 static void incrementSequenceNumber(OCResource * resPtr);
313 * Attempts to initialize every network interface that the CA Layer might have compiled in.
315 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
316 * return something other than @ref CA_STATUS_OK, then this function fails.
317 * @param transportType OCTransportAdapter value to select.
318 * @return ::CA_STATUS_OK on success, some other value upon failure.
320 static CAResult_t OCSelectNetwork(OCTransportAdapter transportType);
323 * Convert CAResponseResult_t to OCStackResult.
325 * @param caCode CAResponseResult_t code.
326 * @return ::OC_STACK_OK on success, some other value upon failure.
328 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
331 * Convert OCTransportFlags_t to CATransportModifiers_t.
333 * @param ocConType OCTransportFlags_t input.
334 * @return CATransportFlags
336 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
339 * Convert CATransportFlags_t to OCTransportModifiers_t.
341 * @param caConType CATransportFlags_t input.
342 * @return OCTransportFlags
344 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
347 * Handle response from presence request.
349 * @param endPoint CA remote endpoint.
350 * @param responseInfo CA response info.
351 * @return ::OC_STACK_OK on success, some other value upon failure.
353 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
354 const CAResponseInfo_t *responseInfo);
357 * This function will be called back by CA layer when a response is received.
359 * @param endPoint CA remote endpoint.
360 * @param responseInfo CA response info.
362 static void HandleCAResponses(const CAEndpoint_t* endPoint,
363 const CAResponseInfo_t* responseInfo);
366 * This function will be called back by CA layer when a request is received.
368 * @param endPoint CA remote endpoint.
369 * @param requestInfo CA request info.
371 static void HandleCARequests(const CAEndpoint_t* endPoint,
372 const CARequestInfo_t* requestInfo);
375 * Extract query from a URI.
377 * @param uri Full URI with query.
378 * @param query Pointer to string that will contain query.
379 * @param newURI Pointer to string that will contain URI.
380 * @return ::OC_STACK_OK on success, some other value upon failure.
382 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
385 * Finds a resource type in an OCResourceType link-list.
387 * @param resourceTypeList The link-list to be searched through.
388 * @param resourceTypeName The key to search for.
390 * @return Resource type that matches the key (ie. resourceTypeName) or
391 * NULL if there is either an invalid parameter or this function was unable to find the key.
393 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
394 const char * resourceTypeName);
397 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
398 * TTL will be set to maxAge.
400 * @param cbNode Callback Node for which presence ttl is to be reset.
401 * @param maxAge New value of ttl in seconds.
403 * @return ::OC_STACK_OK on success, some other value upon failure.
405 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
408 * Ensure the accept header option is set appropriatly before sending the requests and routing
409 * header option is updated with destination.
411 * @param object CA remote endpoint.
412 * @param requestInfo CA request info.
414 * @return ::OC_STACK_OK on success, some other value upon failure.
416 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
419 * default adapter state change callback method
421 * @param adapter CA network adapter type.
422 * @param enabled current adapter state.
424 static void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled);
427 * default connection state change callback method
429 * @param info CAEndpoint which has address, port and etc.
430 * @param isConnected current connection state.
432 static void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected);
435 * Register network monitoring callback.
436 * Network status changes are delivered these callback.
437 * @param adapterHandler Adapter state monitoring callback.
438 * @param connectionHandler Connection state monitoring callback.
440 static void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
441 CAConnectionStateChangedCB connectionHandler);
443 * Map zoneId to endpoint address which scope is ipv6 link-local.
444 * @param payload Discovery payload which has Endpoint information.
445 * @param ifindex index which indicate network interface.
448 static OCStackResult OCMapZoneIdToLinkLocalEndpoint(OCDiscoveryPayload *payload, uint32_t ifindex);
452 * Initialize the stack.
453 * Caller of this function must serialize calls to this function and the stop counterpart.
454 * @param mode Mode of operation.
455 * @param serverFlags The server flag used when the mode of operation is a server mode.
456 * @param clientFlags The client flag used when the mode of operation is a client mode.
457 * @param transportType The transport type.
459 * @return ::OC_STACK_OK on success, some other value upon failure.
461 static OCStackResult OCInitializeInternal(OCMode mode, OCTransportFlags serverFlags,
462 OCTransportFlags clientFlags, OCTransportAdapter transportType);
465 * DeInitialize the stack.
466 * Caller of this function must serialize calls to this function and the init counterpart.
468 * @return ::OC_STACK_OK on success, some other value upon failure.
470 static OCStackResult OCDeInitializeInternal();
472 //-----------------------------------------------------------------------------
473 // Internal functions
474 //-----------------------------------------------------------------------------
475 static void OCEnterInitializer()
479 int32_t initCount = oc_atomic_increment(&g_ocStackStartStopThreadCount);
480 assert(initCount > 0);
485 OC_VERIFY(oc_atomic_decrement(&g_ocStackStartStopThreadCount) >= 0);
486 #if !defined(ARDUINO)
487 // Yield execution to the thread that is holding the lock.
490 assert(!"Not expecting initCount to go above 1 on Arduino");
496 static void OCLeaveInitializer()
498 OC_VERIFY(oc_atomic_decrement(&g_ocStackStartStopThreadCount) >= 0);
501 bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
503 if (!options || 0 == numOptions)
505 OIC_LOG (INFO, TAG, "No options present");
509 for (uint8_t i = 0; i < numOptions; i++)
511 if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
513 OIC_LOG(DEBUG, TAG, "Proxy URI is present");
520 uint32_t GetTicks(uint32_t milliSeconds)
525 // Guard against overflow of uint32_t
526 if (milliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
527 COAP_TICKS_PER_SECOND)
529 return now + (milliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
537 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
539 VERIFY_NON_NULL_NR(in, FATAL);
540 VERIFY_NON_NULL_NR(out, FATAL);
542 out->adapter = (OCTransportAdapter)in->adapter;
543 out->flags = CAToOCTransportFlags(in->flags);
544 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
545 out->port = in->port;
546 out->ifindex = in->ifindex;
547 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
548 /* This assert is to prevent accidental mismatch between address size macros defined in
549 * RI and CA and cause crash here. */
550 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
551 "Address size mismatch between RI and CA");
552 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
556 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
558 VERIFY_NON_NULL_NR(in, FATAL);
559 VERIFY_NON_NULL_NR(out, FATAL);
561 out->adapter = (CATransportAdapter_t)in->adapter;
562 out->flags = OCToCATransportFlags(in->flags);
563 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
564 OICStrcpy(out->remoteId, sizeof(out->remoteId), in->remoteId);
565 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
566 /* This assert is to prevent accidental mismatch between address size macros defined in
567 * RI and CA and cause crash here. */
568 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
569 "Address size mismatch between RI and CA");
570 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
572 out->port = in->port;
573 out->ifindex = in->ifindex;
576 void FixUpClientResponse(OCClientResponse *cr)
578 VERIFY_NON_NULL_NR(cr, FATAL);
580 cr->addr = &cr->devAddr;
581 cr->connType = (OCConnectivityType)
582 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
585 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
587 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
588 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
590 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
591 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
592 if (OC_STACK_OK != rmResult)
594 OIC_LOG(ERROR, TAG, "Add destination option failed");
599 uint16_t acceptVersion = OC_SPEC_VERSION_VALUE;
600 // From OCF onwards, check settings of version option.
601 if (DEFAULT_ACCEPT_VERSION_VALUE <= acceptVersion)
603 if (requestInfo->info.numOptions > 0 && requestInfo->info.options)
605 for (uint8_t i = 0; i < requestInfo->info.numOptions; i++)
607 if (COAP_OPTION_ACCEPT_VERSION == requestInfo->info.options[i].protocolID)
609 acceptVersion = requestInfo->info.options[i].optionData[0];
612 else if (COAP_OPTION_CONTENT_VERSION == requestInfo->info.options[i].protocolID)
614 acceptVersion = requestInfo->info.options[i].optionData[0];
621 if (DEFAULT_CONTENT_VERSION_VALUE <= acceptVersion)
623 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_VND_OCF_CBOR;
624 requestInfo->info.acceptVersion = acceptVersion;
628 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
631 CAResult_t result = CASendRequest(object, requestInfo);
632 if(CA_STATUS_OK != result)
634 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
635 return CAResultToOCResult(result);
639 //-----------------------------------------------------------------------------
640 // Internal API function
641 //-----------------------------------------------------------------------------
643 // This internal function is called to update the stack with the status of
644 // observers and communication failures
645 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
647 OCStackResult result = OC_STACK_ERROR;
648 ResourceObserver * observer = NULL;
649 OCEntityHandlerRequest ehRequest = {0};
653 case OC_OBSERVER_NOT_INTERESTED:
654 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
655 observer = GetObserverUsingToken(token, tokenLength);
658 result = FormOCEntityHandlerRequest(&ehRequest,
659 (OCRequestHandle)NULL,
662 (OCResourceHandle)NULL,
663 NULL, PAYLOAD_TYPE_REPRESENTATION,
665 OC_OBSERVE_DEREGISTER,
668 if (result != OC_STACK_OK)
673 if (observer->resource && observer->resource->entityHandler)
675 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
676 observer->resource->entityHandlerCallbackParam);
680 result = DeleteObserverUsingToken(token, tokenLength);
681 if (result == OC_STACK_OK)
683 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
687 result = OC_STACK_OK;
688 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
692 case OC_OBSERVER_STILL_INTERESTED:
693 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
694 observer = GetObserverUsingToken(token, tokenLength);
697 observer->forceHighQos = 0;
698 observer->failedCommCount = 0;
699 result = OC_STACK_OK;
703 result = OC_STACK_OBSERVER_NOT_FOUND;
707 case OC_OBSERVER_FAILED_COMM:
708 OIC_LOG(DEBUG, TAG, "observer is unreachable");
709 observer = GetObserverUsingToken (token, tokenLength);
712 if (observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
714 result = FormOCEntityHandlerRequest(&ehRequest,
715 (OCRequestHandle)NULL,
718 (OCResourceHandle)NULL,
719 NULL, PAYLOAD_TYPE_REPRESENTATION,
721 OC_OBSERVE_DEREGISTER,
724 if (result != OC_STACK_OK)
726 return OC_STACK_ERROR;
729 if (observer->resource && observer->resource->entityHandler)
731 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
732 observer->resource->entityHandlerCallbackParam);
735 result = DeleteObserverUsingToken(token, tokenLength);
736 if (result == OC_STACK_OK)
738 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
742 result = OC_STACK_OK;
743 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
748 observer->failedCommCount++;
749 observer->forceHighQos = 1;
750 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",
751 observer->failedCommCount);
752 result = OC_STACK_CONTINUE;
757 OIC_LOG(ERROR, TAG, "Unknown status");
758 result = OC_STACK_ERROR;
764 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
766 OCStackResult ret = OC_STACK_ERROR;
770 ret = OC_STACK_RESOURCE_CREATED;
773 ret = OC_STACK_RESOURCE_DELETED;
776 ret = OC_STACK_RESOURCE_CHANGED;
783 ret = OC_STACK_INVALID_QUERY;
785 case CA_UNAUTHORIZED_REQ:
786 ret = OC_STACK_UNAUTHORIZED_REQ;
789 ret = OC_STACK_INVALID_OPTION;
792 ret = OC_STACK_NO_RESOURCE;
794 case CA_RETRANSMIT_TIMEOUT:
795 ret = OC_STACK_COMM_ERROR;
797 case CA_REQUEST_ENTITY_TOO_LARGE:
798 ret = OC_STACK_TOO_LARGE_REQ;
800 case CA_NOT_ACCEPTABLE:
801 ret = OC_STACK_NOT_ACCEPTABLE;
803 case CA_FORBIDDEN_REQ:
804 ret = OC_STACK_FORBIDDEN_REQ;
806 case CA_INTERNAL_SERVER_ERROR:
807 ret = OC_STACK_INTERNAL_SERVER_ERROR;
815 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
817 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
826 // This Response Code is like HTTP 204 "No Content" but only used in
827 // response to POST and PUT requests.
831 // This Response Code is like HTTP 200 "OK" but only used in response to
836 // This should not happen but,
837 // give it a value just in case but output an error
839 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
843 case OC_STACK_RESOURCE_CREATED:
846 case OC_STACK_RESOURCE_DELETED:
849 case OC_STACK_RESOURCE_CHANGED:
852 case OC_STACK_INVALID_QUERY:
855 case OC_STACK_INVALID_OPTION:
858 case OC_STACK_NO_RESOURCE:
861 case OC_STACK_COMM_ERROR:
862 ret = CA_RETRANSMIT_TIMEOUT;
864 case OC_STACK_NOT_ACCEPTABLE:
865 ret = CA_NOT_ACCEPTABLE;
867 case OC_STACK_UNAUTHORIZED_REQ:
868 ret = CA_UNAUTHORIZED_REQ;
870 case OC_STACK_FORBIDDEN_REQ:
871 ret = CA_FORBIDDEN_REQ;
873 case OC_STACK_INTERNAL_SERVER_ERROR:
874 ret = CA_INTERNAL_SERVER_ERROR;
876 case OC_STACK_BAD_ENDPOINT:
884 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
886 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
888 // supply default behavior.
889 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
891 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
893 if ((caFlags & OC_MASK_SCOPE) == 0)
895 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
900 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
902 return (OCTransportFlags)caFlags;
905 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
907 uint32_t lowerBound = 0;
908 uint32_t higherBound = 0;
910 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
912 return OC_STACK_INVALID_PARAM;
915 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
917 cbNode->presence->TTL = maxAgeSeconds;
919 for (int index = 0; index < PresenceTimeOutSize; index++)
921 // Guard against overflow
922 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
925 lowerBound = GetTicks((PresenceTimeOut[index] *
926 cbNode->presence->TTL *
927 MILLISECONDS_PER_SECOND)/100);
931 lowerBound = GetTicks(UINT32_MAX);
934 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
937 higherBound = GetTicks((PresenceTimeOut[index + 1] *
938 cbNode->presence->TTL *
939 MILLISECONDS_PER_SECOND)/100);
943 higherBound = GetTicks(UINT32_MAX);
946 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
948 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
949 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
950 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
953 cbNode->presence->TTLlevel = 0;
955 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
959 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
961 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
963 return OC_RSRVD_TRIGGER_CREATE;
965 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
967 return OC_RSRVD_TRIGGER_CHANGE;
971 return OC_RSRVD_TRIGGER_DELETE;
975 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
979 return OC_PRESENCE_TRIGGER_CREATE;
981 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
983 return OC_PRESENCE_TRIGGER_CREATE;
985 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
987 return OC_PRESENCE_TRIGGER_CHANGE;
991 return OC_PRESENCE_TRIGGER_DELETE;
995 OCStackResult OCEncodeAddressForRFC6874(char *outputAddress,
997 const char *inputAddress)
999 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
1000 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
1002 size_t inputLength = strnlen(inputAddress, outputSize);
1004 // inputSize includes the null terminator
1005 size_t inputSize = inputLength + 1;
1007 if (inputSize > outputSize)
1009 OIC_LOG_V(ERROR, TAG,
1010 "OCEncodeAddressForRFC6874 failed: "
1011 "outputSize (%zu) < inputSize (%zu)",
1012 outputSize, inputSize);
1014 return OC_STACK_ERROR;
1017 char* percentChar = strchr(inputAddress, '%');
1019 // If there is no '%' character, then no change is required to the string.
1020 if (NULL == percentChar)
1022 OICStrcpy(outputAddress, outputSize, inputAddress);
1026 const char* addressPart = &inputAddress[0];
1027 const char* scopeIdPart = percentChar + 1;
1029 // Sanity check to make sure this string doesn't have more '%' characters
1030 if (NULL != strchr(scopeIdPart, '%'))
1032 return OC_STACK_ERROR;
1035 // If no string follows the first '%', then the input was invalid.
1036 if (scopeIdPart[0] == '\0')
1038 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
1039 return OC_STACK_ERROR;
1042 // Check to see if the string is already encoded
1043 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
1045 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Input string is already encoded");
1046 return OC_STACK_ERROR;
1049 // Fail if we don't have room for encoded string's two additional chars
1050 if (outputSize < (inputSize + 2))
1052 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: encoded output will not fit!");
1053 return OC_STACK_ERROR;
1056 // Restore the null terminator with an escaped '%' character, per RFC 6874
1057 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
1058 strcat(outputAddress, "%25");
1059 strcat(outputAddress, scopeIdPart);
1064 OCStackResult OCDecodeAddressForRFC6874(char *outputAddress,
1066 const char *inputAddress,
1069 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
1070 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
1074 end = inputAddress + strlen(inputAddress);
1076 size_t inputLength = end - inputAddress;
1078 const char *percent = strchr(inputAddress, '%');
1079 if (!percent || (percent > end))
1081 OICStrcpyPartial(outputAddress, outputSize, inputAddress, inputLength);
1085 if (percent[1] != '2' || percent[2] != '5')
1087 return OC_STACK_INVALID_URI;
1090 size_t addrlen = percent - inputAddress + 1;
1091 OICStrcpyPartial(outputAddress, outputSize, inputAddress, addrlen);
1092 OICStrcpyPartial(outputAddress + addrlen, outputSize - addrlen,
1093 percent + 3, end - percent - 3);
1100 * The cononical presence allows constructed URIs to be string compared.
1102 * requestUri must be a char array of size CA_MAX_URI_LENGTH
1104 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
1105 char *presenceUri, bool isMulticast)
1107 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
1108 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1112 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1113 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1116 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1117 if (ep->adapter == CA_ADAPTER_IP)
1119 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1121 if ('\0' == ep->addr[0]) // multicast
1123 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1127 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1129 OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1130 sizeof(addressEncoded),
1133 if (OC_STACK_OK != result)
1138 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1139 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1144 if ('\0' == ep->addr[0]) // multicast
1146 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1147 ep->port = OC_MULTICAST_PORT;
1149 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1150 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1154 // might work for other adapters (untested, but better than nothing)
1155 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1156 OC_RSRVD_PRESENCE_URI);
1160 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1161 const CAResponseInfo_t *responseInfo)
1163 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1164 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1166 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1167 ClientCB * cbNode = NULL;
1168 char *resourceTypeName = NULL;
1169 OCClientResponse *response = NULL;
1170 OCStackResult result = OC_STACK_ERROR;
1171 uint32_t maxAge = 0;
1173 char presenceUri[CA_MAX_URI_LENGTH];
1175 int presenceSubscribe = 0;
1176 int multicastPresenceSubscribe = 0;
1178 if (responseInfo->result != CA_CONTENT)
1180 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1181 return OC_STACK_ERROR;
1184 response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1187 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1188 return OC_STACK_ERROR;
1190 response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1192 response->payload = NULL;
1193 response->result = OC_STACK_OK;
1195 CopyEndpointToDevAddr(endpoint, &response->devAddr);
1196 FixUpClientResponse(response);
1198 if (responseInfo->info.payload)
1200 result = OCParsePayload(&response->payload,
1201 PAYLOAD_TYPE_PRESENCE,
1202 responseInfo->info.payload,
1203 responseInfo->info.payloadSize);
1205 if(result != OC_STACK_OK)
1207 OIC_LOG(ERROR, TAG, "Presence parse failed");
1210 if(!response->payload || response->payload->type != PAYLOAD_TYPE_PRESENCE)
1212 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1213 result = OC_STACK_ERROR;
1216 response->sequenceNumber = ((OCPresencePayload*)response->payload)->sequenceNumber;
1217 resourceTypeName = ((OCPresencePayload*)response->payload)->resourceType;
1218 maxAge = ((OCPresencePayload*)response->payload)->maxAge;
1221 // check for unicast presence
1222 uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1223 responseInfo->isMulticast);
1224 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1226 result = OC_STACK_INVALID_URI;
1229 OIC_LOG(INFO, TAG, "check for unicast presence");
1230 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1233 presenceSubscribe = 1;
1237 // check for multicast presence
1238 OIC_LOG(INFO, TAG, "check for multicast presence");
1239 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1242 multicastPresenceSubscribe = 1;
1246 if (!presenceSubscribe && !multicastPresenceSubscribe)
1248 OIC_LOG(INFO, TAG, "Received a presence notification, "
1249 "but need to register presence callback, ignoring");
1253 if (presenceSubscribe)
1255 if(cbNode->sequenceNumber == response->sequenceNumber)
1257 OIC_LOG(INFO, TAG, "No presence change");
1258 ResetPresenceTTL(cbNode, maxAge);
1259 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1265 OIC_LOG(INFO, TAG, "Stopping presence");
1266 response->result = OC_STACK_PRESENCE_STOPPED;
1267 if(cbNode->presence)
1269 OICFree(cbNode->presence->timeOut);
1270 OICFree(cbNode->presence);
1271 cbNode->presence = NULL;
1276 if(!cbNode->presence)
1278 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1280 if(!(cbNode->presence))
1282 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1283 result = OC_STACK_NO_MEMORY;
1287 VERIFY_NON_NULL_V(cbNode->presence);
1288 cbNode->presence->timeOut = NULL;
1289 cbNode->presence->timeOut = (uint32_t *)
1290 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1291 if(!(cbNode->presence->timeOut)){
1293 "Could not allocate memory for cbNode->presence->timeOut");
1294 OICFree(cbNode->presence);
1295 result = OC_STACK_NO_MEMORY;
1300 ResetPresenceTTL(cbNode, maxAge);
1302 cbNode->sequenceNumber = response->sequenceNumber;
1307 // This is the multicast case
1308 OIC_LOG(INFO, TAG, "this is the multicast presence");
1311 OIC_LOG(INFO, TAG, "Stopping presence");
1312 response->result = OC_STACK_PRESENCE_STOPPED;
1316 // Ensure that a filter is actually applied.
1317 if (resourceTypeName && cbNode->filterResourceType)
1319 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1320 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1326 OIC_LOG(INFO, TAG, "Callback for presence");
1328 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response);
1330 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1332 FindAndDeleteClientCB(cbNode);
1336 OCPayloadDestroy(response->payload);
1341 OCStackResult HandleBatchResponse(char *requestUri, OCRepPayload **payload)
1343 if (requestUri && *payload)
1345 char *interfaceName = NULL;
1346 char *rtTypeName = NULL;
1347 char *uriQuery = NULL;
1348 char *uriWithoutQuery = NULL;
1349 if (OC_STACK_OK == getQueryFromUri(requestUri, &uriQuery, &uriWithoutQuery))
1351 if (OC_STACK_OK == ExtractFiltersFromQuery(uriQuery, &interfaceName, &rtTypeName))
1353 if (0 == strcmp(OC_RSRVD_INTERFACE_BATCH, interfaceName))
1355 char *uri = (*payload)->uri;
1356 if (uri && 0 != strcmp(uriWithoutQuery, uri))
1358 OCRepPayload *newPayload = OCRepPayloadCreate();
1361 OCRepPayloadSetUri(newPayload, uri);
1362 newPayload->next = *payload;
1363 *payload = newPayload;
1369 OICFree(interfaceName);
1370 OICFree(rtTypeName);
1372 OICFree(uriWithoutQuery);
1375 return OC_STACK_INVALID_PARAM;
1378 #ifndef WITH_ARDUINO
1379 OCStackResult OCMapZoneIdToLinkLocalEndpoint(OCDiscoveryPayload *payload, uint32_t ifindex)
1383 OIC_LOG(ERROR, TAG, "Given argument payload is NULL!!");
1384 return OC_STACK_INVALID_PARAM;
1387 OCResourcePayload *curRes = payload->resources;
1389 while (curRes != NULL)
1391 OCEndpointPayload* eps = curRes->eps;
1395 if (eps->family & OC_IP_USE_V6)
1397 CATransportFlags_t scopeLevel;
1398 if (CA_STATUS_OK == CAGetIpv6AddrScope(eps->addr, &scopeLevel))
1400 if (CA_SCOPE_LINK == scopeLevel)
1402 char *zoneId = NULL;
1403 if (OC_STACK_OK == OCGetLinkLocalZoneId(ifindex, &zoneId))
1405 assert(zoneId != NULL);
1406 // put zoneId to end of addr
1407 OICStrcat(eps->addr, OC_MAX_ADDR_STR_SIZE, "%");
1408 OICStrcat(eps->addr, OC_MAX_ADDR_STR_SIZE, zoneId);
1413 OIC_LOG(ERROR, TAG, "failed at parse zone-id for link-local address");
1414 return OC_STACK_ERROR;
1420 OIC_LOG(ERROR, TAG, "failed at parse ipv6 scope level");
1421 return OC_STACK_ERROR;
1426 curRes = curRes->next;
1433 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1435 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1437 if(responseInfo->info.resourceUri &&
1438 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1440 HandlePresenceResponse(endPoint, responseInfo);
1444 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1445 responseInfo->info.tokenLength, NULL, NULL);
1447 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1448 responseInfo->info.tokenLength);
1452 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1454 // check obs header option
1455 bool obsHeaderOpt = false;
1456 CAHeaderOption_t *options = responseInfo->info.options;
1457 for (uint8_t i = 0; i< responseInfo->info.numOptions; i++)
1459 if (options && (options[i].optionID == COAP_OPTION_OBSERVE))
1461 obsHeaderOpt = true;
1466 if(responseInfo->result == CA_EMPTY)
1468 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1469 // We do not have a case for the client to receive a RESET
1470 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1472 //This is the case of receiving an ACK on a request to a slow resource!
1473 OIC_LOG(INFO, TAG, "This is a pure ACK");
1474 //TODO: should we inform the client
1475 // app that at least the request was received at the server?
1478 else if (CA_RETRANSMIT_TIMEOUT == responseInfo->result
1479 || CA_NOT_ACCEPTABLE == responseInfo->result)
1481 if (CA_RETRANSMIT_TIMEOUT == responseInfo->result)
1483 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1484 OIC_LOG(INFO, TAG, "Calling into application address space");
1488 OIC_LOG(INFO, TAG, "Server doesn't support the requested payload format");
1489 OIC_LOG(INFO, TAG, "Calling into application address space");
1492 OCClientResponse *response = NULL;
1494 response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1497 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1501 response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1502 CopyEndpointToDevAddr(endPoint, &response->devAddr);
1503 FixUpClientResponse(response);
1504 response->resourceUri = responseInfo->info.resourceUri;
1505 memcpy(response->identity.id, responseInfo->info.identity.id,
1506 sizeof (response->identity.id));
1507 response->identity.id_length = responseInfo->info.identity.id_length;
1509 response->result = CAResponseToOCStackResult(responseInfo->result);
1510 cbNode->callBack(cbNode->context,
1511 cbNode->handle, response);
1512 FindAndDeleteClientCB(cbNode);
1515 else if ((cbNode->method == OC_REST_OBSERVE || cbNode->method == OC_REST_OBSERVE_ALL)
1516 && (responseInfo->result == CA_CONTENT) && !obsHeaderOpt)
1518 OCClientResponse *response = NULL;
1520 response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1523 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1527 response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1528 CopyEndpointToDevAddr(endPoint, &response->devAddr);
1529 FixUpClientResponse(response);
1530 response->resourceUri = responseInfo->info.resourceUri;
1531 memcpy(response->identity.id, responseInfo->info.identity.id,
1532 sizeof (response->identity.id));
1533 response->identity.id_length = responseInfo->info.identity.id_length;
1534 response->result = OC_STACK_OK;
1536 OIC_LOG(DEBUG, TAG, "This is response of observer cancel or observer request fail");
1538 cbNode->callBack(cbNode->context,
1541 FindAndDeleteClientCB(cbNode);
1546 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1547 OIC_LOG(INFO, TAG, "Calling into application address space");
1549 OCClientResponse *response = NULL;
1550 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1552 response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1555 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1559 response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1560 response->sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1561 CopyEndpointToDevAddr(endPoint, &response->devAddr);
1562 FixUpClientResponse(response);
1563 response->resourceUri = responseInfo->info.resourceUri;
1564 memcpy(response->identity.id, responseInfo->info.identity.id,
1565 sizeof (response->identity.id));
1566 response->identity.id_length = responseInfo->info.identity.id_length;
1568 response->result = CAResponseToOCStackResult(responseInfo->result);
1570 if(responseInfo->info.payload &&
1571 responseInfo->info.payloadSize)
1573 // check the security resource
1574 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1576 type = PAYLOAD_TYPE_SECURITY;
1578 else if (cbNode->method == OC_REST_DISCOVER)
1580 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1581 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1583 type = PAYLOAD_TYPE_DISCOVERY;
1586 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1588 type = PAYLOAD_TYPE_DISCOVERY;
1591 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1593 type = PAYLOAD_TYPE_REPRESENTATION;
1595 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1597 type = PAYLOAD_TYPE_REPRESENTATION;
1599 else if (strcmp(cbNode->requestUri, OC_RSRVD_INTROSPECTION_URI) == 0)
1601 type = PAYLOAD_TYPE_REPRESENTATION;
1603 else if (strcmp(cbNode->requestUri, OC_RSRVD_INTROSPECTION_PAYLOAD_URI) == 0)
1605 type = PAYLOAD_TYPE_REPRESENTATION;
1607 #ifdef ROUTING_GATEWAY
1608 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1610 type = PAYLOAD_TYPE_REPRESENTATION;
1613 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1615 type = PAYLOAD_TYPE_REPRESENTATION;
1618 else if (strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1620 type = PAYLOAD_TYPE_REPRESENTATION;
1625 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1626 cbNode->method, cbNode->requestUri);
1630 else if (cbNode->method == OC_REST_GET ||
1631 cbNode->method == OC_REST_PUT ||
1632 cbNode->method == OC_REST_POST ||
1633 cbNode->method == OC_REST_OBSERVE ||
1634 cbNode->method == OC_REST_OBSERVE_ALL ||
1635 cbNode->method == OC_REST_DELETE)
1637 if (cbNode->requestUri)
1639 if (0 == strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri))
1641 type = PAYLOAD_TYPE_REPRESENTATION;
1643 else if (0 == strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri))
1645 type = PAYLOAD_TYPE_REPRESENTATION;
1647 if (type == PAYLOAD_TYPE_INVALID)
1649 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1650 cbNode->method, cbNode->requestUri);
1651 type = PAYLOAD_TYPE_REPRESENTATION;
1656 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1657 type = PAYLOAD_TYPE_REPRESENTATION;
1662 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1663 cbNode->method, cbNode->requestUri);
1668 // In case of error, still want application to receive the error message.
1669 if (OCResultToSuccess(response->result) || PAYLOAD_TYPE_REPRESENTATION == type)
1671 if (OC_STACK_OK != OCParsePayload(&response->payload,
1673 responseInfo->info.payload,
1674 responseInfo->info.payloadSize))
1676 OIC_LOG(ERROR, TAG, "Error converting payload");
1677 OCPayloadDestroy(response->payload);
1681 // Check endpoints has link-local ipv6 address.
1682 // if there is, map zone-id which parsed from ifindex
1683 #ifndef WITH_ARDUINO
1684 if (PAYLOAD_TYPE_DISCOVERY == response->payload->type)
1686 OCDiscoveryPayload *disPayload = (OCDiscoveryPayload*)(response->payload);
1688 OCMapZoneIdToLinkLocalEndpoint(disPayload, response->devAddr.ifindex))
1690 OIC_LOG(ERROR, TAG, "failed at map zone-id for link-local address");
1691 OCPayloadDestroy(response->payload);
1699 response->resourceUri = OICStrdup(cbNode->requestUri);
1703 response->numRcvdVendorSpecificHeaderOptions = 0;
1704 if((responseInfo->info.numOptions > 0) && (responseInfo->info.options != NULL))
1707 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1708 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1711 uint32_t observationOption;
1712 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1713 for (observationOption=0, i=0;
1714 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1718 (observationOption << 8) | optionData[i];
1720 response->sequenceNumber = observationOption;
1721 response->numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1726 response->numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1729 if(response->numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1731 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1732 OCPayloadDestroy(response->payload);
1737 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1739 memcpy (&(response->rcvdVendorSpecificHeaderOptions[i-start]),
1740 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1744 if (cbNode->method == OC_REST_OBSERVE &&
1745 response->sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1746 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1747 response->sequenceNumber <= cbNode->sequenceNumber)
1749 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1750 response->sequenceNumber);
1755 if (cbNode->requestUri)
1757 // if request uri is '/oic/rd', update ins value of resource.
1758 char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
1761 OCUpdateResourceInsWithResponse(cbNode->requestUri, response);
1765 // set remoteID(device ID) into OCClientResponse callback parameter
1766 if (OC_REST_DISCOVER == cbNode->method && PAYLOAD_TYPE_DISCOVERY == type)
1768 OCDiscoveryPayload *payload = (OCDiscoveryPayload*) response->payload;
1769 // Payload can be empty in case of error message.
1770 if (payload && payload->sid)
1772 OICStrcpy(response->devAddr.remoteId, sizeof(response->devAddr.remoteId),
1774 OIC_LOG_V(INFO, TAG, "Device ID of response : %s",
1775 response->devAddr.remoteId);
1777 #if defined(TCP_ADAPTER) && defined(WITH_CLOUD)
1778 CAConnectUserPref_t connPrefer = CA_USER_PREF_CLOUD;
1779 CAResult_t ret = CAUtilCMGetConnectionUserConfig(&connPrefer);
1780 if (ret == CA_STATUS_OK && connPrefer != CA_USER_PREF_CLOUD)
1782 OCCMDiscoveryResource(response);
1787 if (response->payload && response->payload->type == PAYLOAD_TYPE_REPRESENTATION)
1789 HandleBatchResponse(cbNode->requestUri, (OCRepPayload **)&response->payload);
1792 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1795 cbNode->sequenceNumber = response->sequenceNumber;
1797 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1799 FindAndDeleteClientCB(cbNode);
1803 // To keep discovery callbacks active.
1804 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1805 MILLISECONDS_PER_SECOND);
1809 //Need to send ACK when the response is CON
1810 if(responseInfo->info.type == CA_MSG_CONFIRM)
1812 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1813 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1816 OCPayloadDestroy(response->payload);
1824 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1825 if(responseInfo->result == CA_EMPTY)
1827 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1828 if(responseInfo->info.type == CA_MSG_RESET)
1830 OIC_LOG(INFO, TAG, "This is a RESET");
1831 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1832 OC_OBSERVER_NOT_INTERESTED);
1834 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1836 OIC_LOG(INFO, TAG, "This is a pure ACK");
1837 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1838 OC_OBSERVER_STILL_INTERESTED);
1841 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1843 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1844 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1845 OC_OBSERVER_FAILED_COMM);
1850 if(!cbNode && !observer)
1852 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1853 || myStackMode == OC_GATEWAY)
1855 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1856 if(responseInfo->result == CA_EMPTY)
1858 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1862 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1863 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1864 CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1868 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1869 || myStackMode == OC_GATEWAY)
1871 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1872 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1874 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1875 responseInfo->info.messageId);
1877 if (responseInfo->info.type == CA_MSG_RESET)
1879 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1880 responseInfo->info.messageId);
1888 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1890 VERIFY_NON_NULL_NR(endPoint, FATAL);
1891 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1893 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1894 OIC_TRACE_BEGIN(%s:HandleCAResponses, TAG);
1895 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1896 #ifdef ROUTING_GATEWAY
1897 bool needRIHandling = false;
1899 * Routing manager is going to update either of endpoint or response or both.
1900 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1901 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1904 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1906 if(ret != OC_STACK_OK || !needRIHandling)
1908 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1915 * Put source in sender endpoint so that the next packet from application can be routed to
1916 * proper destination and remove "RM" coap header option before passing request / response to
1917 * RI as this option will make no sense to either RI or application.
1919 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1920 (uint8_t *) &(responseInfo->info.numOptions),
1921 (CAEndpoint_t *) endPoint);
1924 OCHandleResponse(endPoint, responseInfo);
1926 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1931 * This function handles error response from CA
1932 * code shall be added to handle the errors
1934 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1936 VERIFY_NON_NULL_NR(endPoint, FATAL);
1937 VERIFY_NON_NULL_NR(errorInfo, FATAL);
1939 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1940 OIC_TRACE_BEGIN(%s:HandleCAErrorResponse, TAG);
1942 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1943 errorInfo->info.tokenLength, NULL, NULL);
1946 OCClientResponse *response = NULL;
1948 response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1951 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1955 response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1956 CopyEndpointToDevAddr(endPoint, &response->devAddr);
1957 FixUpClientResponse(response);
1958 response->resourceUri = errorInfo->info.resourceUri;
1959 memcpy(response->identity.id, errorInfo->info.identity.id,
1960 sizeof (response->identity.id));
1961 response->identity.id_length = errorInfo->info.identity.id_length;
1962 response->result = CAResultToOCResult(errorInfo->result);
1964 cbNode->callBack(cbNode->context, cbNode->handle, response);
1968 ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1969 errorInfo->info.tokenLength);
1972 OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1973 OCStackResult result = CAResultToOCResult(errorInfo->result);
1974 if (OC_STACK_COMM_ERROR == result)
1976 OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1977 OC_OBSERVER_FAILED_COMM);
1981 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1986 * This function sends out Direct Stack Responses. These are responses that are not coming
1987 * from the application entity handler. These responses have no payload and are usually ACKs,
1988 * RESETs or some error conditions that were caught by the stack.
1990 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1991 const CAResponseResult_t responseResult, const CAMessageType_t type,
1992 const uint8_t numOptions, const CAHeaderOption_t *options,
1993 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1994 CADataType_t dataType)
1996 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1997 CAResponseInfo_t respInfo = {
1998 .result = responseResult
2000 respInfo.info.messageId = coapID;
2001 respInfo.info.numOptions = numOptions;
2003 if (respInfo.info.numOptions)
2005 respInfo.info.options =
2006 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
2007 memcpy (respInfo.info.options, options,
2008 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
2012 respInfo.info.payload = NULL;
2013 respInfo.info.token = token;
2014 respInfo.info.tokenLength = tokenLength;
2015 respInfo.info.type = type;
2016 respInfo.info.resourceUri = OICStrdup (resourceUri);
2017 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
2018 respInfo.info.dataType = dataType;
2020 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2021 // Add the destination to route option from the endpoint->routeData.
2022 bool doPost = false;
2023 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
2024 if(OC_STACK_OK != result)
2026 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
2027 OICFree (respInfo.info.resourceUri);
2028 OICFree (respInfo.info.options);
2033 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
2034 CARequestInfo_t reqInfo = {.method = CA_POST };
2035 /* The following initialization is not done in a single initializer block as in
2036 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
2037 * does not have designated initalizers. This is a work-around for now.
2039 reqInfo.info.type = CA_MSG_NONCONFIRM;
2040 reqInfo.info.messageId = coapID;
2041 reqInfo.info.tokenLength = tokenLength;
2042 reqInfo.info.token = token;
2043 reqInfo.info.numOptions = respInfo.info.numOptions;
2044 reqInfo.info.payload = NULL;
2045 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
2046 if (reqInfo.info.numOptions)
2048 reqInfo.info.options =
2049 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
2050 if (NULL == reqInfo.info.options)
2052 OIC_LOG(ERROR, TAG, "Calloc failed");
2053 OICFree (reqInfo.info.resourceUri);
2054 OICFree (respInfo.info.resourceUri);
2055 OICFree (respInfo.info.options);
2056 return OC_STACK_NO_MEMORY;
2058 memcpy (reqInfo.info.options, respInfo.info.options,
2059 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
2062 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
2063 OICFree (reqInfo.info.resourceUri);
2064 OICFree (reqInfo.info.options);
2065 OICFree (respInfo.info.resourceUri);
2066 OICFree (respInfo.info.options);
2067 if (CA_STATUS_OK != caResult)
2069 OIC_LOG(ERROR, TAG, "CASendRequest error");
2070 return CAResultToOCResult(caResult);
2076 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
2078 // resourceUri in the info field is cloned in the CA layer and
2079 // thus ownership is still here.
2080 OICFree (respInfo.info.resourceUri);
2081 OICFree (respInfo.info.options);
2082 if(CA_STATUS_OK != caResult)
2084 OIC_LOG(ERROR, TAG, "CASendResponse error");
2085 return CAResultToOCResult(caResult);
2088 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
2092 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
2094 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
2095 OCStackResult result = OC_STACK_ERROR;
2096 if (!protocolRequest)
2098 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
2099 return OC_STACK_INVALID_PARAM;
2102 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
2103 protocolRequest->tokenLength);
2106 OIC_LOG(INFO, TAG, "This is a new Server Request");
2107 result = AddServerRequest(&request, protocolRequest->coapID,
2108 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
2109 protocolRequest->numRcvdVendorSpecificHeaderOptions,
2110 protocolRequest->observationOption, protocolRequest->qos,
2111 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
2112 protocolRequest->payload, protocolRequest->requestToken,
2113 protocolRequest->tokenLength, protocolRequest->resourceUrl,
2114 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
2115 protocolRequest->acceptVersion, &protocolRequest->devAddr);
2116 if (OC_STACK_OK != result)
2118 OIC_LOG(ERROR, TAG, "Error adding server request");
2124 OIC_LOG(ERROR, TAG, "Out of Memory");
2125 return OC_STACK_NO_MEMORY;
2128 if(!protocolRequest->reqMorePacket)
2130 request->requestComplete = 1;
2135 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
2138 if (request->requestComplete)
2140 OIC_LOG(INFO, TAG, "This Server Request is complete");
2141 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2142 OCResource *resource = NULL;
2143 result = DetermineResourceHandling (request, &resHandling, &resource);
2144 if (result == OC_STACK_OK)
2146 result = ProcessRequest(resHandling, resource, request);
2151 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2152 result = OC_STACK_CONTINUE;
2157 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2159 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2160 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2162 if (myStackMode == OC_CLIENT)
2164 //TODO: should the client be responding to requests?
2168 // If the request message is Confirmable,
2169 // then the response SHOULD be returned in an Acknowledgement message.
2170 CAMessageType_t directResponseType = requestInfo->info.type;
2171 directResponseType = (directResponseType == CA_MSG_CONFIRM)
2172 ? CA_MSG_ACKNOWLEDGE : CA_MSG_NONCONFIRM;
2174 char * uriWithoutQuery = NULL;
2175 char * query = NULL;
2176 OCStackResult requestResult = OC_STACK_ERROR;
2178 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2180 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2182 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2185 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2186 OIC_LOG_V(INFO, TAG, "Query : %s", query);
2188 OCServerProtocolRequest serverRequest = { 0 };
2189 if (strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2191 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2192 OICFree(uriWithoutQuery);
2196 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2197 OICFree(uriWithoutQuery);
2204 if (strlen(query) < MAX_QUERY_LENGTH)
2206 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2211 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2217 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2219 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2220 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2221 if (!serverRequest.payload)
2223 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2226 memcpy (serverRequest.payload, requestInfo->info.payload,
2227 requestInfo->info.payloadSize);
2231 serverRequest.reqTotalSize = 0;
2234 switch (requestInfo->method)
2237 serverRequest.method = OC_REST_GET;
2240 serverRequest.method = OC_REST_PUT;
2243 serverRequest.method = OC_REST_POST;
2246 serverRequest.method = OC_REST_DELETE;
2249 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2250 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2251 directResponseType, requestInfo->info.numOptions,
2252 requestInfo->info.options, requestInfo->info.token,
2253 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2255 OICFree(serverRequest.payload);
2259 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2260 requestInfo->info.tokenLength);
2262 serverRequest.tokenLength = requestInfo->info.tokenLength;
2263 if (serverRequest.tokenLength)
2266 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2268 if (!serverRequest.requestToken)
2270 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2271 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2272 directResponseType, requestInfo->info.numOptions,
2273 requestInfo->info.options, requestInfo->info.token,
2274 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2276 OICFree(serverRequest.payload);
2279 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2282 switch (requestInfo->info.acceptFormat)
2284 case CA_FORMAT_APPLICATION_CBOR:
2285 serverRequest.acceptFormat = OC_FORMAT_CBOR;
2287 case CA_FORMAT_APPLICATION_VND_OCF_CBOR:
2288 serverRequest.acceptFormat = OC_FORMAT_VND_OCF_CBOR;
2290 case CA_FORMAT_UNDEFINED:
2291 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2294 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2297 if (requestInfo->info.type == CA_MSG_CONFIRM)
2299 serverRequest.qos = OC_HIGH_QOS;
2303 serverRequest.qos = OC_LOW_QOS;
2305 // CA does not need the following field
2306 // Are we sure CA does not need them? how is it responding to multicast
2307 serverRequest.delayedResNeeded = 0;
2309 serverRequest.coapID = requestInfo->info.messageId;
2311 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2313 // copy vendor specific header options
2314 uint8_t tempNum = (requestInfo->info.numOptions);
2316 // Assume no observation requested and it is a pure GET.
2317 // If obs registration/de-registration requested it'll be fetched from the
2318 // options in GetObserveHeaderOption()
2319 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2321 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2322 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2325 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2326 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2327 directResponseType, requestInfo->info.numOptions,
2328 requestInfo->info.options, requestInfo->info.token,
2329 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2331 OICFree(serverRequest.payload);
2332 OICFree(serverRequest.requestToken);
2335 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2336 if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2338 memcpy(&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
2339 sizeof(CAHeaderOption_t) * tempNum);
2342 requestResult = HandleStackRequests (&serverRequest);
2344 if (requestResult == OC_STACK_SLOW_RESOURCE)
2346 // Send ACK to client as precursor to slow response
2347 if (requestInfo->info.type == CA_MSG_CONFIRM)
2349 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2350 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2354 if (requestResult == OC_STACK_RESOURCE_ERROR
2355 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2357 OIC_LOG(ERROR, TAG, "Observe Registration failed due to resource error");
2359 else if (!OCResultToSuccess(requestResult))
2361 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2363 CAResponseResult_t stackResponse = OCToCAStackResult(requestResult, serverRequest.method);
2365 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2366 directResponseType, requestInfo->info.numOptions,
2367 requestInfo->info.options, requestInfo->info.token,
2368 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2371 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2372 // The token is copied in there, and is thus still owned by this function.
2373 OICFree(serverRequest.payload);
2374 OICFree(serverRequest.requestToken);
2375 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2378 //This function will be called back by CA layer when a request is received
2379 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2381 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2382 OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2385 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2392 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2397 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2398 #ifdef ROUTING_GATEWAY
2399 bool needRIHandling = false;
2400 bool isEmptyMsg = false;
2402 * Routing manager is going to update either of endpoint or request or both.
2403 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2404 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2405 * destination. It can also remove "RM" coap header option before passing request / response to
2406 * RI as this option will make no sense to either RI or application.
2408 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2409 &needRIHandling, &isEmptyMsg);
2410 if (OC_STACK_OK != ret || !needRIHandling)
2412 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2419 * Put source in sender endpoint so that the next packet from application can be routed to
2420 * proper destination and remove RM header option.
2422 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2423 (uint8_t *) &(requestInfo->info.numOptions),
2424 (CAEndpoint_t *) endPoint);
2426 #ifdef ROUTING_GATEWAY
2430 * In Gateways, the MSGType in route option is used to check if the actual
2431 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2432 * EMPTY response is sent in the form of POST request which need to be changed
2433 * to a EMPTY response by RM. This translation is done in this part of the code.
2435 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2436 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2437 .info.messageId = requestInfo->info.messageId,
2438 .info.type = CA_MSG_ACKNOWLEDGE};
2439 OCHandleResponse(endPoint, &respInfo);
2445 // Normal handling of the packet
2446 OCHandleRequests(endPoint, requestInfo);
2448 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2452 //-----------------------------------------------------------------------------
2454 //-----------------------------------------------------------------------------
2456 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2459 !raInfo->username ||
2460 !raInfo->hostname ||
2461 !raInfo->xmpp_domain)
2464 return OC_STACK_INVALID_PARAM;
2466 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2467 gRASetInfo = (result == OC_STACK_OK)? true : false;
2473 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2477 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2480 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2482 OIC_LOG(DEBUG, TAG, "call OCInit1");
2483 return OCInit2(mode, serverFlags, clientFlags, OC_DEFAULT_ADAPTER);
2486 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2487 OCTransportAdapter transportType)
2489 OIC_LOG(INFO, TAG, "Entering OCInit2");
2491 // Serialize calls to start and stop the stack.
2492 OCEnterInitializer();
2494 OCStackResult result = OC_STACK_OK;
2496 if (g_ocStackStartCount == 0)
2498 // This is the first call to initialize the stack so it gets to do the real work.
2499 result = OCInitializeInternal(mode, serverFlags, clientFlags, transportType);
2502 if (result == OC_STACK_OK)
2504 // Increment the start count since we're about to return success.
2505 assert(g_ocStackStartCount != UINT_MAX);
2506 assert(stackState == OC_STACK_INITIALIZED);
2507 g_ocStackStartCount++;
2510 OCLeaveInitializer();
2514 OCStackResult OCInitializeInternal(OCMode mode, OCTransportFlags serverFlags,
2515 OCTransportFlags clientFlags, OCTransportAdapter transportType)
2517 if (stackState == OC_STACK_INITIALIZED)
2519 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2520 OCStop() between them are ignored.");
2524 #ifndef ROUTING_GATEWAY
2525 if (OC_GATEWAY == mode)
2527 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2528 return OC_STACK_INVALID_PARAM;
2535 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2536 return OC_STACK_ERROR;
2540 OIC_LOG_V(INFO, TAG, "IoTivity version is v%s", IOTIVITY_VERSION);
2541 OCStackResult result = OC_STACK_ERROR;
2544 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2545 || (mode == OC_GATEWAY)))
2547 OIC_LOG(ERROR, TAG, "Invalid mode");
2548 return OC_STACK_ERROR;
2552 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2554 caglobals.client = true;
2556 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2558 caglobals.server = true;
2561 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2562 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2564 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2566 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2567 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2569 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2572 defaultDeviceHandler = NULL;
2573 defaultDeviceHandlerCallbackParameter = NULL;
2575 result = InitializeScheduleResourceList();
2576 VERIFY_SUCCESS(result, OC_STACK_OK);
2578 result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2579 VERIFY_SUCCESS(result, OC_STACK_OK);
2581 result = CAResultToOCResult(OCSelectNetwork(transportType));
2582 VERIFY_SUCCESS(result, OC_STACK_OK);
2584 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2585 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2586 VERIFY_SUCCESS(result, OC_STACK_OK);
2588 switch (myStackMode)
2591 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2592 result = CAResultToOCResult(CAStartDiscoveryServer());
2593 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2596 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2597 result = CAResultToOCResult(CAStartListeningServer());
2598 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2600 case OC_CLIENT_SERVER:
2602 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2603 result = CAResultToOCResult(CAStartListeningServer());
2604 if(result == OC_STACK_OK)
2606 result = CAResultToOCResult(CAStartDiscoveryServer());
2610 VERIFY_SUCCESS(result, OC_STACK_OK);
2613 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2616 #ifdef WITH_PRESENCE
2617 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2618 #endif // WITH_PRESENCE
2620 //Update Stack state to initialized
2621 stackState = OC_STACK_INITIALIZED;
2623 // Initialize resource
2624 if(myStackMode != OC_CLIENT)
2626 result = initResources();
2629 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2630 RMSetStackMode(mode);
2631 #ifdef ROUTING_GATEWAY
2632 if (OC_GATEWAY == myStackMode)
2634 result = RMInitialize();
2640 if (result == OC_STACK_OK)
2642 result = InitializeKeepAlive(myStackMode);
2646 #if defined(TCP_ADAPTER) && defined(WITH_CLOUD)
2647 // Initialize the Connection Manager
2648 if (result == OC_STACK_OK)
2650 result = OCCMInitialize();
2655 if(result != OC_STACK_OK)
2657 OIC_LOG(ERROR, TAG, "Stack initialization error");
2658 TerminateScheduleResourceList();
2659 deleteAllResources();
2661 stackState = OC_STACK_UNINITIALIZED;
2666 OCStackResult OCStop()
2668 OIC_LOG(INFO, TAG, "Entering OCStop");
2670 // Serialize calls to start and stop the stack.
2671 OCEnterInitializer();
2673 OCStackResult result = OC_STACK_OK;
2675 if (g_ocStackStartCount == 1)
2677 // This is the last call to stop the stack, do the real work.
2678 result = OCDeInitializeInternal();
2680 else if (g_ocStackStartCount == 0)
2682 OIC_LOG(ERROR, TAG, "Too many calls to OCStop");
2683 assert(!"Too many calls to OCStop");
2684 result = OC_STACK_ERROR;
2687 if (result == OC_STACK_OK)
2689 g_ocStackStartCount--;
2692 OCLeaveInitializer();
2696 OCStackResult OCDeInitializeInternal()
2698 assert(stackState == OC_STACK_INITIALIZED);
2700 #ifdef WITH_PRESENCE
2701 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2702 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2703 presenceResource.presenceTTL = 0;
2704 #endif // WITH_PRESENCE
2706 #ifdef ROUTING_GATEWAY
2707 if (OC_GATEWAY == myStackMode)
2714 TerminateKeepAlive(myStackMode);
2717 OCStackResult result = CAResultToOCResult(
2718 CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2719 OCDefaultConnectionStateChangedHandler));
2720 if (OC_STACK_OK != result)
2722 OIC_LOG(ERROR, TAG, "CAUnregisterNetworkMonitorHandler has failed");
2725 TerminateScheduleResourceList();
2726 // Remove all observers
2727 DeleteObserverList();
2728 // Free memory dynamically allocated for resources
2729 deleteAllResources();
2730 // Remove all the client callbacks
2731 DeleteClientCBList();
2732 // Terminate connectivity-abstraction layer.
2735 #if defined(TCP_ADAPTER) && defined(WITH_CLOUD)
2736 // Terminate the Connection Manager
2740 // Unset cautil config
2741 CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2742 CAUtilSetBTConfigure(configs);
2744 stackState = OC_STACK_UNINITIALIZED;
2748 OCStackResult OCStartMulticastServer()
2750 if(stackState != OC_STACK_INITIALIZED)
2752 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2753 return OC_STACK_ERROR;
2755 CAResult_t ret = CAStartListeningServer();
2756 if (CA_STATUS_OK != ret)
2758 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2759 return OC_STACK_ERROR;
2764 OCStackResult OCStopMulticastServer()
2766 CAResult_t ret = CAStopListeningServer();
2767 if (CA_STATUS_OK != ret)
2769 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2770 return OC_STACK_ERROR;
2775 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2780 return CA_MSG_CONFIRM;
2785 return CA_MSG_NONCONFIRM;
2790 * A request uri consists of the following components in order:
2793 * CoAP over UDP prefix "coap://"
2794 * CoAP over TCP prefix "coap+tcp://"
2795 * CoAP over DTLS prefix "coaps://"
2796 * CoAP over TLS prefix "coaps+tcp://"
2798 * IPv6 address "[1234::5678]"
2799 * IPv4 address "192.168.1.1"
2800 * optional port ":5683"
2801 * resource uri "/oc/core..."
2803 * for PRESENCE requests, extract resource type.
2805 static OCStackResult ParseRequestUri(const char *fullUri,
2806 OCTransportAdapter adapter,
2807 OCTransportFlags flags,
2808 OCDevAddr **devAddr,
2810 char **resourceType)
2812 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2814 OCStackResult result = OC_STACK_OK;
2815 OCDevAddr *da = NULL;
2819 // provide defaults for all returned values
2826 *resourceUri = NULL;
2830 *resourceType = NULL;
2833 // delimit url prefix, if any
2834 const char *start = fullUri;
2835 char *slash2 = strstr(start, "//");
2840 char *slash = strchr(start, '/');
2843 return OC_STACK_INVALID_URI;
2846 // process url scheme
2847 size_t prefixLen = slash2 - fullUri;
2851 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2852 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2858 // TODO: this logic should come in with unit tests exercising the various strings
2859 // processs url prefix, if any
2860 size_t urlLen = slash - start;
2864 if (urlLen && devAddr)
2865 { // construct OCDevAddr
2866 if (start[0] == '[')
2868 char *close = strchr(++start, ']');
2869 if (!close || close > slash)
2871 return OC_STACK_INVALID_URI;
2874 if (close[1] == ':')
2881 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2885 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2887 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2891 char *dot = strchr(start, '.');
2892 if (dot && dot < slash)
2894 colon = strchr(start, ':');
2895 end = (colon && colon < slash) ? colon : slash;
2900 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2904 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2906 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2914 if (len >= sizeof(da->addr))
2916 return OC_STACK_INVALID_URI;
2918 // collect port, if any
2919 if (colon && colon < slash)
2921 for (colon++; colon < slash; colon++)
2924 if (c < '0' || c > '9')
2926 return OC_STACK_INVALID_URI;
2928 port = 10 * port + c - '0';
2933 if (len >= sizeof(da->addr))
2935 return OC_STACK_INVALID_URI;
2938 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2941 return OC_STACK_NO_MEMORY;
2944 // Decode address per RFC 6874.
2945 result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2946 if (result != OC_STACK_OK)
2953 da->adapter = adapter;
2955 if (!strncmp(fullUri, "coaps", 5))
2957 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2962 // process resource uri, if any
2964 { // request uri and query
2965 size_t ulen = strlen(slash); // resource uri length
2966 size_t tlen = 0; // resource type length
2969 static const char strPresence[] = "/oic/ad?rt=";
2970 static const size_t lenPresence = sizeof(strPresence) - 1;
2971 if (!strncmp(slash, strPresence, lenPresence))
2973 type = slash + lenPresence;
2974 tlen = ulen - lenPresence;
2979 *resourceUri = (char *)OICMalloc(ulen + 1);
2982 result = OC_STACK_NO_MEMORY;
2985 strcpy(*resourceUri, slash);
2988 if (type && resourceType)
2990 *resourceType = (char *)OICMalloc(tlen + 1);
2993 result = OC_STACK_NO_MEMORY;
2997 OICStrcpy(*resourceType, (tlen+1), type);
3004 // free all returned values
3011 OICFree(*resourceUri);
3015 OICFree(*resourceType);
3020 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
3024 char uri[CA_MAX_URI_LENGTH];
3026 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
3028 *requestUri = OICStrdup(uri);
3031 return OC_STACK_NO_MEMORY;
3038 * Discover or Perform requests on a specified resource
3040 OCStackResult OCDoResource(OCDoHandle *handle,
3042 const char *requestUri,
3043 const OCDevAddr *destination,
3045 OCConnectivityType connectivityType,
3046 OCQualityOfService qos,
3047 OCCallbackData *cbData,
3048 OCHeaderOption *options,
3051 OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
3052 connectivityType, qos, cbData, options, numOptions);
3054 // This is the owner of the payload object, so we free it
3055 OCPayloadDestroy(payload);
3060 * Discover or Perform requests on a specified resource
3062 OCStackResult OCDoRequest(OCDoHandle *handle,
3064 const char *requestUri,
3065 const OCDevAddr *destination,
3067 OCConnectivityType connectivityType,
3068 OCQualityOfService qos,
3069 OCCallbackData *cbData,
3070 OCHeaderOption *options,
3073 OIC_LOG(INFO, TAG, "Entering OCDoResource");
3075 // Validate input parameters
3076 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
3077 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
3079 OCStackResult result = OC_STACK_ERROR;
3080 CAResult_t caResult;
3081 CAToken_t token = NULL;
3082 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3083 ClientCB *clientCB = NULL;
3084 OCDoHandle resHandle = NULL;
3085 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3086 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
3088 OCTransportAdapter adapter;
3089 OCTransportFlags flags;
3090 // the request contents are put here
3091 CARequestInfo_t requestInfo = {.method = CA_GET};
3092 // requestUri will be parsed into the following three variables
3093 OCDevAddr *devAddr = NULL;
3094 char *resourceUri = NULL;
3095 char *resourceType = NULL;
3098 * Support original behavior with address on resourceUri argument.
3100 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
3101 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
3105 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
3106 if (result != OC_STACK_OK)
3108 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
3112 else if (!checkProxyUri(options, numOptions))
3114 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
3121 case OC_REST_OBSERVE:
3122 case OC_REST_OBSERVE_ALL:
3123 requestInfo.method = CA_GET;
3126 requestInfo.method = CA_PUT;
3129 requestInfo.method = CA_POST;
3131 case OC_REST_DELETE:
3132 requestInfo.method = CA_DELETE;
3134 case OC_REST_DISCOVER:
3135 // intentional fall through don't add break
3136 #ifdef WITH_PRESENCE
3137 case OC_REST_PRESENCE:
3139 if (destination || devAddr)
3141 requestInfo.isMulticast = false;
3145 tmpDevAddr.adapter = adapter;
3146 tmpDevAddr.flags = flags;
3147 destination = &tmpDevAddr;
3148 requestInfo.isMulticast = true;
3151 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
3152 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
3153 // replacing method type with GET.
3154 requestInfo.method = CA_GET;
3157 result = OC_STACK_INVALID_METHOD;
3161 if (!devAddr && !destination)
3163 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
3164 result = OC_STACK_INVALID_PARAM;
3168 /* If not original behavior, use destination argument */
3169 if (destination && !devAddr)
3171 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
3174 result = OC_STACK_NO_MEMORY;
3177 OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
3178 *devAddr = *destination;
3183 OIC_LOG_V(DEBUG, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
3186 resHandle = GenerateInvocationHandle();
3189 result = OC_STACK_NO_MEMORY;
3193 caResult = CAGenerateToken(&token, tokenLength);
3194 if (caResult != CA_STATUS_OK)
3196 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3197 result= OC_STACK_ERROR;
3201 // fill in request data
3202 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3203 requestInfo.info.token = token;
3204 requestInfo.info.tokenLength = tokenLength;
3206 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3208 result = CreateObserveHeaderOption (&(requestInfo.info.options),
3209 options, numOptions, OC_OBSERVE_REGISTER);
3210 if (result != OC_STACK_OK)
3214 requestInfo.info.numOptions = numOptions + 1;
3218 requestInfo.info.numOptions = numOptions;
3219 requestInfo.info.options =
3220 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3221 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3222 numOptions * sizeof(CAHeaderOption_t));
3225 CopyDevAddrToEndpoint(devAddr, &endpoint);
3230 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3233 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3237 uint16_t payloadVersion = OC_SPEC_VERSION_VALUE;
3238 // From OCF onwards, check version option settings
3239 if (DEFAULT_CONTENT_VERSION_VALUE <= payloadVersion)
3241 if (numOptions > 0 && options)
3243 for (uint8_t i = 0; i < numOptions; i++)
3245 if (COAP_OPTION_CONTENT_VERSION == options[i].optionID)
3247 payloadVersion = options[i].optionData[0];
3250 else if (COAP_OPTION_ACCEPT_VERSION == options[i].optionID)
3252 payloadVersion = options[i].optionData[0];
3259 if (DEFAULT_CONTENT_VERSION_VALUE <= payloadVersion)
3261 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_VND_OCF_CBOR;
3262 requestInfo.info.payloadVersion = payloadVersion;
3266 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3271 requestInfo.info.payload = NULL;
3272 requestInfo.info.payloadSize = 0;
3273 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3276 // prepare for response
3277 #ifdef WITH_PRESENCE
3278 if (method == OC_REST_PRESENCE)
3280 char *presenceUri = NULL;
3281 result = OCPreparePresence(&endpoint, &presenceUri,
3282 requestInfo.isMulticast);
3283 if (OC_STACK_OK != result)
3288 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3289 // Presence notification will form a canonical uri to
3290 // look for callbacks into the application.
3293 OICFree(resourceUri);
3295 resourceUri = presenceUri;
3299 // update resourceUri onto requestInfo after check presence uri
3300 requestInfo.info.resourceUri = resourceUri;
3302 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3303 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3304 method, devAddr, resourceUri, resourceType, ttl);
3305 if (OC_STACK_OK != result)
3310 devAddr = NULL; // Client CB list entry now owns it
3311 resourceUri = NULL; // Client CB list entry now owns it
3312 resourceType = NULL; // Client CB list entry now owns it
3314 #ifdef WITH_PRESENCE
3315 if (method == OC_REST_PRESENCE)
3317 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3321 *handle = resHandle;
3329 result = OCSendRequest(&endpoint, &requestInfo);
3330 if (OC_STACK_OK != result)
3337 *handle = resHandle;
3341 if (result != OC_STACK_OK)
3343 OIC_LOG(ERROR, TAG, "OCDoResource error");
3344 FindAndDeleteClientCB(clientCB);
3345 CADestroyToken(token);
3353 OICFree(requestInfo.info.payload);
3355 OICFree(resourceUri);
3356 OICFree(resourceType);
3357 OICFree(requestInfo.info.options);
3361 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3365 * This ftn is implemented one of two ways in the case of observation:
3367 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3368 * Remove the callback associated on client side.
3369 * When the next notification comes in from server,
3370 * reply with RESET message to server.
3371 * Keep in mind that the server will react to RESET only
3372 * if the last notification was sent as CON
3374 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3375 * and it is associated with an observe request
3376 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3377 * Send CON Observe request to server with
3378 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3379 * Remove the callback associated on client side.
3381 OCStackResult ret = OC_STACK_OK;
3382 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3383 CARequestInfo_t requestInfo = {.method = CA_GET};
3387 return OC_STACK_INVALID_PARAM;
3390 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3393 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3394 return OC_STACK_ERROR;
3397 switch (clientCB->method)
3399 case OC_REST_OBSERVE:
3400 case OC_REST_OBSERVE_ALL:
3402 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3404 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3406 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
3408 FindAndDeleteClientCB(clientCB);
3412 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3414 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3415 requestInfo.info.token = clientCB->token;
3416 requestInfo.info.tokenLength = clientCB->tokenLength;
3418 if (CreateObserveHeaderOption (&(requestInfo.info.options),
3419 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3421 return OC_STACK_ERROR;
3423 requestInfo.info.numOptions = numOptions + 1;
3424 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3427 ret = OCSendRequest(&endpoint, &requestInfo);
3429 if (requestInfo.info.options)
3431 OICFree (requestInfo.info.options);
3433 if (requestInfo.info.resourceUri)
3435 OICFree (requestInfo.info.resourceUri);
3440 case OC_REST_DISCOVER:
3441 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3442 clientCB->requestUri);
3443 FindAndDeleteClientCB(clientCB);
3446 #ifdef WITH_PRESENCE
3447 case OC_REST_PRESENCE:
3448 FindAndDeleteClientCB(clientCB);
3453 ret = OC_STACK_INVALID_METHOD;
3461 * @brief Register Persistent storage callback.
3462 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3464 * OC_STACK_OK - No errors; Success
3465 * OC_STACK_INVALID_PARAM - Invalid parameter
3467 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3469 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3470 if(!persistentStorageHandler)
3472 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3473 return OC_STACK_INVALID_PARAM;
3477 if( !persistentStorageHandler->open ||
3478 !persistentStorageHandler->close ||
3479 !persistentStorageHandler->read ||
3480 !persistentStorageHandler->unlink ||
3481 !persistentStorageHandler->write)
3483 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3484 return OC_STACK_INVALID_PARAM;
3487 g_PersistentStorageHandler = persistentStorageHandler;
3491 OCPersistentStorage *OCGetPersistentStorageHandler()
3493 return g_PersistentStorageHandler;
3496 #ifdef WITH_PRESENCE
3498 OCStackResult OCProcessPresence()
3500 OCStackResult result = OC_STACK_OK;
3502 // the following line floods the log with messages that are irrelevant
3503 // to most purposes. Uncomment as needed.
3504 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3505 ClientCB* cbNode = NULL;
3506 ClientCB* cbTemp = NULL;
3507 OCClientResponse clientResponse;
3508 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3510 LL_FOREACH_SAFE(cbList, cbNode, cbTemp)
3512 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3517 uint32_t now = GetTicks(0);
3518 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3519 cbNode->presence->TTLlevel);
3520 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3522 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3527 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3529 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3530 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3532 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3534 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3536 clientResponse.sequenceNumber = 0;
3537 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3538 clientResponse.devAddr = *cbNode->devAddr;
3539 FixUpClientResponse(&clientResponse);
3540 clientResponse.payload = NULL;
3542 // Increment the TTLLevel (going to a next state), so we don't keep
3543 // sending presence notification to client.
3544 cbNode->presence->TTLlevel++;
3545 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3546 cbNode->presence->TTLlevel);
3548 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3549 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3551 FindAndDeleteClientCB(cbNode);
3555 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3560 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3561 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3562 CARequestInfo_t requestInfo = {.method = CA_GET};
3564 OIC_LOG(DEBUG, TAG, "time to test server presence");
3566 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3568 requestData.type = CA_MSG_NONCONFIRM;
3569 requestData.token = cbNode->token;
3570 requestData.tokenLength = cbNode->tokenLength;
3571 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3572 requestInfo.method = CA_GET;
3573 requestInfo.info = requestData;
3575 result = OCSendRequest(&endpoint, &requestInfo);
3576 if (OC_STACK_OK != result)
3581 cbNode->presence->TTLlevel++;
3582 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3585 if (result != OC_STACK_OK)
3587 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3592 #endif // WITH_PRESENCE
3594 OCStackResult OCProcess()
3596 if (stackState == OC_STACK_UNINITIALIZED)
3598 return OC_STACK_ERROR;
3600 #ifdef WITH_PRESENCE
3601 OCProcessPresence();
3603 CAHandleRequestResponse();
3605 #ifdef ROUTING_GATEWAY
3615 #ifdef WITH_PRESENCE
3616 OCStackResult OCStartPresence(const uint32_t ttl)
3618 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3619 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3620 OCChangeResourceProperty(
3621 &(((OCResource *)presenceResource.handle)->resourceProperties),
3624 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3626 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3627 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3631 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3632 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3636 presenceResource.presenceTTL = ttl;
3638 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3640 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3642 presenceState = OC_PRESENCE_INITIALIZED;
3644 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3646 CAToken_t caToken = NULL;
3647 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3648 if (caResult != CA_STATUS_OK)
3650 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3651 CADestroyToken(caToken);
3652 return OC_STACK_ERROR;
3655 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3656 (OCResource *) presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED,
3657 OC_SPEC_VERSION_VALUE, &devAddr);
3658 CADestroyToken(caToken);
3661 // Each time OCStartPresence is called
3662 // a different random 32-bit integer number is used
3663 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3665 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3666 OC_PRESENCE_TRIGGER_CREATE);
3669 OCStackResult OCStopPresence()
3671 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3672 OCStackResult result = OC_STACK_ERROR;
3674 if(presenceResource.handle)
3676 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3678 // make resource inactive
3679 result = OCChangeResourceProperty(
3680 &(((OCResource *) presenceResource.handle)->resourceProperties),
3684 if(result != OC_STACK_OK)
3687 "Changing the presence resource properties to ACTIVE not successful");
3691 return SendStopNotification();
3695 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3696 void* callbackParameter)
3698 defaultDeviceHandler = entityHandler;
3699 defaultDeviceHandlerCallbackParameter = callbackParameter;
3704 OCTpsSchemeFlags OCGetSupportedEndpointTpsFlags()
3706 return OCGetSupportedTpsFlags();
3709 OCStackResult OCCreateResource(OCResourceHandle *handle,
3710 const char *resourceTypeName,
3711 const char *resourceInterfaceName,
3712 const char *uri, OCEntityHandler entityHandler,
3713 void *callbackParam,
3714 uint8_t resourceProperties)
3716 return OCCreateResourceWithEp(handle,
3718 resourceInterfaceName,
3725 OCStackResult OCCreateResourceWithEp(OCResourceHandle *handle,
3726 const char *resourceTypeName,
3727 const char *resourceInterfaceName,
3728 const char *uri, OCEntityHandler entityHandler,
3729 void *callbackParam,
3730 uint8_t resourceProperties,
3731 OCTpsSchemeFlags resourceTpsTypes)
3734 OCResource *pointer = NULL;
3735 OCStackResult result = OC_STACK_ERROR;
3737 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3739 if(myStackMode == OC_CLIENT)
3741 return OC_STACK_INVALID_PARAM;
3743 // Validate parameters
3744 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3746 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3747 return OC_STACK_INVALID_URI;
3749 // Is it presented during resource discovery?
3750 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3752 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3753 return OC_STACK_INVALID_PARAM;
3756 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3758 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3762 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3764 // Make sure resourceProperties bitmask has allowed properties specified
3765 if (resourceProperties
3766 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3767 OC_EXPLICIT_DISCOVERABLE
3776 OIC_LOG(ERROR, TAG, "Invalid property");
3777 return OC_STACK_INVALID_PARAM;
3780 // Checking resourceTpsTypes param
3781 OCTpsSchemeFlags validTps = OC_NO_TPS;
3782 validTps = (OCTpsSchemeFlags)(validTps | OC_COAP | OC_COAPS);
3784 validTps = (OCTpsSchemeFlags)(validTps | OC_COAP_TCP | OC_COAPS_TCP);
3787 validTps = (OCTpsSchemeFlags)(validTps | OC_HTTP | OC_HTTP);
3790 validTps = (OCTpsSchemeFlags)(validTps | OC_COAP_RFCOMM);
3793 validTps = (OCTpsSchemeFlags)(validTps | OC_COAP_GATT);
3796 validTps = (OCTpsSchemeFlags)(validTps | OC_COAP_NFC);
3799 validTps = (OCTpsSchemeFlags)(validTps | OC_COAP_RA);
3802 if ((resourceTpsTypes < OC_COAP) || ((resourceTpsTypes != OC_ALL) &&
3803 (resourceTpsTypes > validTps)))
3805 OIC_LOG(ERROR, TAG, "Invalid TPS Types OC_ALL");
3806 return OC_STACK_INVALID_PARAM;
3809 // If the headResource is NULL, then no resources have been created...
3810 pointer = headResource;
3813 // At least one resources is in the resource list, so we need to search for
3814 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3817 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3819 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3820 return OC_STACK_INVALID_PARAM;
3822 pointer = pointer->next;
3825 // Create the pointer and insert it into the resource list
3826 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3829 result = OC_STACK_NO_MEMORY;
3832 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3834 insertResource(pointer);
3837 pointer->uri = OICStrdup(uri);
3840 result = OC_STACK_NO_MEMORY;
3844 // Set properties. Set OC_ACTIVE
3845 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3848 // Add the resourcetype to the resource
3849 result = BindResourceTypeToResource(pointer, resourceTypeName);
3850 if (result != OC_STACK_OK)
3852 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3856 // Add the resourceinterface to the resource
3857 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3858 if (result != OC_STACK_OK)
3860 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3864 result = BindTpsTypeToResource(pointer, resourceTpsTypes);
3865 if (result != OC_STACK_OK)
3867 OIC_LOG(ERROR, TAG, "Error adding resource TPS types");
3871 // If an entity handler has been passed, attach it to the newly created
3872 // resource. Otherwise, set the default entity handler.
3875 pointer->entityHandler = entityHandler;
3876 pointer->entityHandlerCallbackParam = callbackParam;
3880 pointer->entityHandler = defaultResourceEHandler;
3881 pointer->entityHandlerCallbackParam = NULL;
3884 // Initialize a pointer indicating child resources in case of collection
3885 pointer->rsrcChildResourcesHead = NULL;
3888 result = OC_STACK_OK;
3890 #ifdef WITH_PRESENCE
3891 if (presenceResource.handle)
3893 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3894 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3898 if (result != OC_STACK_OK)
3900 // Deep delete of resource and other dynamic elements that it contains
3901 deleteResource(pointer);
3906 OCStackResult OCBindResource(
3907 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3909 OCResource *resource = NULL;
3910 OCChildResource *tempChildResource = NULL;
3911 OCChildResource *newChildResource = NULL;
3913 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3915 // Validate parameters
3916 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3917 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3918 // Container cannot contain itself
3919 if (collectionHandle == resourceHandle)
3921 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3922 return OC_STACK_INVALID_PARAM;
3925 // Use the handle to find the resource in the resource linked list
3926 resource = findResource((OCResource *) collectionHandle);
3929 OIC_LOG(ERROR, TAG, "Collection handle not found");
3930 return OC_STACK_INVALID_PARAM;
3933 // Look for an open slot to add add the child resource.
3934 // If found, add it and return success
3936 tempChildResource = resource->rsrcChildResourcesHead;
3938 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3940 // TODO: what if one of child resource was deregistered without unbinding?
3941 tempChildResource = tempChildResource->next;
3944 // Do memory allocation for child resource
3945 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3946 if(!newChildResource)
3948 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3949 return OC_STACK_ERROR;
3952 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3953 newChildResource->next = NULL;
3955 if(!resource->rsrcChildResourcesHead)
3957 resource->rsrcChildResourcesHead = newChildResource;
3960 tempChildResource->next = newChildResource;
3963 OIC_LOG(INFO, TAG, "resource bound");
3965 #ifdef WITH_PRESENCE
3966 if (presenceResource.handle)
3968 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3969 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3970 OC_PRESENCE_TRIGGER_CHANGE);
3977 OCStackResult OCUnBindResource(
3978 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3980 OCResource *resource = NULL;
3981 OCChildResource *tempChildResource = NULL;
3982 OCChildResource *tempLastChildResource = NULL;
3984 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3986 // Validate parameters
3987 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3988 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3989 // Container cannot contain itself
3990 if (collectionHandle == resourceHandle)
3992 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3993 return OC_STACK_INVALID_PARAM;
3996 // Use the handle to find the resource in the resource linked list
3997 resource = findResource((OCResource *) collectionHandle);
4000 OIC_LOG(ERROR, TAG, "Collection handle not found");
4001 return OC_STACK_INVALID_PARAM;
4004 // Look for an open slot to add add the child resource.
4005 // If found, add it and return success
4006 if(!resource->rsrcChildResourcesHead)
4008 OIC_LOG(INFO, TAG, "resource not found in collection");
4010 // Unable to add resourceHandle, so return error
4011 return OC_STACK_ERROR;
4015 tempChildResource = resource->rsrcChildResourcesHead;
4017 while (tempChildResource)
4019 if(tempChildResource->rsrcResource == resourceHandle)
4021 // if resource going to be unbinded is the head one.
4022 if( tempChildResource == resource->rsrcChildResourcesHead )
4024 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
4025 OICFree(resource->rsrcChildResourcesHead);
4026 resource->rsrcChildResourcesHead = temp;
4031 OCChildResource *temp = tempChildResource->next;
4032 OICFree(tempChildResource);
4033 if (tempLastChildResource)
4035 tempLastChildResource->next = temp;
4040 OIC_LOG(INFO, TAG, "resource unbound");
4042 // Send notification when resource is unbounded successfully.
4043 #ifdef WITH_PRESENCE
4044 if (presenceResource.handle)
4046 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4047 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
4048 OC_PRESENCE_TRIGGER_CHANGE);
4051 tempChildResource = NULL;
4052 tempLastChildResource = NULL;
4058 tempLastChildResource = tempChildResource;
4059 tempChildResource = tempChildResource->next;
4062 OIC_LOG(INFO, TAG, "resource not found in collection");
4064 tempChildResource = NULL;
4065 tempLastChildResource = NULL;
4067 // Unable to add resourceHandle, so return error
4068 return OC_STACK_ERROR;
4071 static bool ValidateResourceTypeInterface(const char *resourceItemName)
4073 if (!resourceItemName)
4077 // Per RFC 6690 only registered values must follow the first rule below.
4078 // At this point in time the only values registered begin with "core", and
4079 // all other values are specified as opaque strings where multiple values
4080 // are separated by a space.
4081 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
4083 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
4085 if (resourceItemName[index] != '.'
4086 && resourceItemName[index] != '-'
4087 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
4088 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
4096 for (size_t index = 0; resourceItemName[index]; ++index)
4098 if (resourceItemName[index] == ' '
4099 || resourceItemName[index] == '\t'
4100 || resourceItemName[index] == '\r'
4101 || resourceItemName[index] == '\n')
4111 OCStackResult BindResourceTypeToResource(OCResource* resource,
4112 const char *resourceTypeName)
4114 OCResourceType *pointer = NULL;
4116 OCStackResult result = OC_STACK_ERROR;
4118 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
4120 if (!ValidateResourceTypeInterface(resourceTypeName))
4122 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
4123 return OC_STACK_INVALID_PARAM;
4126 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
4129 result = OC_STACK_NO_MEMORY;
4133 str = OICStrdup(resourceTypeName);
4136 result = OC_STACK_NO_MEMORY;
4139 pointer->resourcetypename = str;
4140 pointer->next = NULL;
4142 insertResourceType(resource, pointer);
4143 result = OC_STACK_OK;
4146 if (result != OC_STACK_OK)
4155 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
4156 const char *resourceInterfaceName)
4158 OCResourceInterface *pointer = NULL;
4160 OCStackResult result = OC_STACK_ERROR;
4162 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
4164 if (!ValidateResourceTypeInterface(resourceInterfaceName))
4166 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
4167 return OC_STACK_INVALID_PARAM;
4170 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
4172 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
4175 result = OC_STACK_NO_MEMORY;
4179 str = OICStrdup(resourceInterfaceName);
4182 result = OC_STACK_NO_MEMORY;
4185 pointer->name = str;
4187 // Bind the resourceinterface to the resource
4188 insertResourceInterface(resource, pointer);
4190 result = OC_STACK_OK;
4193 if (result != OC_STACK_OK)
4202 OCStackResult BindTpsTypeToResource(OCResource* resource,
4203 OCTpsSchemeFlags resourceTpsTypes)
4207 OIC_LOG(ERROR, TAG, "Resource pointer is NULL!!!");
4208 return OC_STACK_INVALID_PARAM;
4211 OCTpsSchemeFlags supportedTps = OC_NO_TPS;
4212 OCStackResult result = OCGetSupportedEndpointFlags(resourceTpsTypes,
4215 if (result != OC_STACK_OK)
4217 OIC_LOG(ERROR, TAG, "Failed at get supported endpoint flags");
4221 // If there isn`t any enabled flag, return error for notify to user.
4222 if (OC_NO_TPS == supportedTps)
4224 OIC_LOG_V(ERROR, TAG, "There isn`t any enabled flag on resource %s", resource->uri);
4225 return OC_STACK_BAD_ENDPOINT;
4228 OIC_LOG_V(INFO, TAG, "Binding %d TPS flags to %s", supportedTps, resource->uri);
4229 resource->endpointType = supportedTps;
4233 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
4234 const char *resourceTypeName)
4237 OCStackResult result = OC_STACK_ERROR;
4238 OCResource *resource = NULL;
4240 resource = findResource((OCResource *) handle);
4243 OIC_LOG(ERROR, TAG, "Resource not found");
4244 return OC_STACK_ERROR;
4247 result = BindResourceTypeToResource(resource, resourceTypeName);
4249 #ifdef WITH_PRESENCE
4250 if(presenceResource.handle)
4252 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4253 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4260 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
4261 const char *resourceInterfaceName)
4264 OCStackResult result = OC_STACK_ERROR;
4265 OCResource *resource = NULL;
4267 resource = findResource((OCResource *) handle);
4270 OIC_LOG(ERROR, TAG, "Resource not found");
4271 return OC_STACK_ERROR;
4274 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
4276 #ifdef WITH_PRESENCE
4277 if (presenceResource.handle)
4279 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4280 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4287 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
4289 OCResource *pointer = headResource;
4291 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
4295 *numResources = *numResources + 1;
4296 pointer = pointer->next;
4301 OCResourceHandle OCGetResourceHandle(uint8_t index)
4303 OCResource *pointer = headResource;
4305 for( uint8_t i = 0; i < index && pointer; ++i)
4307 pointer = pointer->next;
4309 return (OCResourceHandle) pointer;
4312 OCStackResult OCDeleteResource(OCResourceHandle handle)
4316 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4317 return OC_STACK_INVALID_PARAM;
4320 OCResource *resource = findResource((OCResource *) handle);
4321 if (resource == NULL)
4323 OIC_LOG(ERROR, TAG, "Resource not found");
4324 return OC_STACK_NO_RESOURCE;
4327 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4329 OIC_LOG(ERROR, TAG, "Error deleting resource");
4330 return OC_STACK_ERROR;
4336 const char *OCGetResourceUri(OCResourceHandle handle)
4338 OCResource *resource = NULL;
4340 resource = findResource((OCResource *) handle);
4343 return resource->uri;
4345 return (const char *) NULL;
4348 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4350 OCResource *resource = NULL;
4352 resource = findResource((OCResource *) handle);
4355 return resource->resourceProperties;
4357 return (OCResourceProperty)-1;
4360 OCStackResult OCSetResourceProperties(OCResourceHandle handle, uint8_t resourceProperties)
4362 OCResource *resource = NULL;
4364 resource = findResource((OCResource *) handle);
4365 if (resource == NULL)
4367 OIC_LOG(ERROR, TAG, "Resource not found");
4368 return OC_STACK_NO_RESOURCE;
4370 resource->resourceProperties = (OCResourceProperty) (resource->resourceProperties | resourceProperties);
4374 OCStackResult OCClearResourceProperties(OCResourceHandle handle, uint8_t resourceProperties)
4376 OCResource *resource = NULL;
4378 resource = findResource((OCResource *) handle);
4379 if (resource == NULL)
4381 OIC_LOG(ERROR, TAG, "Resource not found");
4382 return OC_STACK_NO_RESOURCE;
4384 resource->resourceProperties = (OCResourceProperty) (resource->resourceProperties & ~resourceProperties);
4388 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4389 uint8_t *numResourceTypes)
4391 OCResource *resource = NULL;
4392 OCResourceType *pointer = NULL;
4394 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4395 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4397 *numResourceTypes = 0;
4399 resource = findResource((OCResource *) handle);
4402 pointer = resource->rsrcType;
4405 *numResourceTypes = *numResourceTypes + 1;
4406 pointer = pointer->next;
4412 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4414 OCResourceType *resourceType = NULL;
4416 resourceType = findResourceTypeAtIndex(handle, index);
4419 return resourceType->resourcetypename;
4421 return (const char *) NULL;
4424 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4425 uint8_t *numResourceInterfaces)
4427 OCResourceInterface *pointer = NULL;
4428 OCResource *resource = NULL;
4430 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4431 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4433 *numResourceInterfaces = 0;
4434 resource = findResource((OCResource *) handle);
4437 pointer = resource->rsrcInterface;
4440 *numResourceInterfaces = *numResourceInterfaces + 1;
4441 pointer = pointer->next;
4447 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4449 OCResourceInterface *resourceInterface = NULL;
4451 resourceInterface = findResourceInterfaceAtIndex(handle, index);
4452 if (resourceInterface)
4454 return resourceInterface->name;
4456 return (const char *) NULL;
4459 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4462 OCResource *resource = NULL;
4463 OCChildResource *tempChildResource = NULL;
4466 resource = findResource((OCResource *) collectionHandle);
4472 tempChildResource = resource->rsrcChildResourcesHead;
4474 while(tempChildResource)
4478 return tempChildResource->rsrcResource;
4481 tempChildResource = tempChildResource->next;
4484 // In this case, the number of resource handles in the collection exceeds the index
4485 tempChildResource = NULL;
4489 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4490 OCEntityHandler entityHandler,
4491 void* callbackParam)
4493 OCResource *resource = NULL;
4495 // Validate parameters
4496 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4498 // Use the handle to find the resource in the resource linked list
4499 resource = findResource((OCResource *)handle);
4502 OIC_LOG(ERROR, TAG, "Resource not found");
4503 return OC_STACK_ERROR;
4507 resource->entityHandler = entityHandler;
4508 resource->entityHandlerCallbackParam = callbackParam;
4510 #ifdef WITH_PRESENCE
4511 if (presenceResource.handle)
4513 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4514 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4521 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4523 OCResource *resource = NULL;
4525 resource = findResource((OCResource *)handle);
4528 OIC_LOG(ERROR, TAG, "Resource not found");
4533 return resource->entityHandler;
4536 void incrementSequenceNumber(OCResource * resPtr)
4538 // Increment the sequence number
4539 resPtr->sequenceNum += 1;
4540 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4542 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4547 #ifdef WITH_PRESENCE
4548 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4549 OCPresenceTrigger trigger)
4551 OIC_LOG(INFO, TAG, "SendPresenceNotification");
4552 OCResource *resPtr = NULL;
4553 OCStackResult result = OC_STACK_ERROR;
4554 OCMethod method = OC_REST_PRESENCE;
4555 uint32_t maxAge = 0;
4556 resPtr = findResource((OCResource *) presenceResource.handle);
4559 return OC_STACK_NO_RESOURCE;
4562 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4564 maxAge = presenceResource.presenceTTL;
4566 result = SendAllObserverNotification(method, resPtr, maxAge,
4567 trigger, resourceType, OC_LOW_QOS);
4573 OCStackResult SendStopNotification()
4575 OIC_LOG(INFO, TAG, "SendStopNotification");
4576 OCResource *resPtr = NULL;
4577 OCStackResult result = OC_STACK_ERROR;
4578 OCMethod method = OC_REST_PRESENCE;
4579 resPtr = findResource((OCResource *) presenceResource.handle);
4582 return OC_STACK_NO_RESOURCE;
4585 // maxAge is 0. ResourceType is NULL.
4586 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4592 #endif // WITH_PRESENCE
4593 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4595 OCResource *resPtr = NULL;
4596 OCStackResult result = OC_STACK_ERROR;
4597 OCMethod method = OC_REST_NOMETHOD;
4598 uint32_t maxAge = 0;
4600 OIC_LOG(INFO, TAG, "Notifying all observers");
4601 #ifdef WITH_PRESENCE
4602 if(handle == presenceResource.handle)
4606 #endif // WITH_PRESENCE
4607 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4609 // Verify that the resource exists
4610 resPtr = findResource ((OCResource *) handle);
4613 return OC_STACK_NO_RESOURCE;
4617 //only increment in the case of regular observing (not presence)
4618 incrementSequenceNumber(resPtr);
4619 method = OC_REST_OBSERVE;
4620 maxAge = MAX_OBSERVE_AGE;
4621 #ifdef WITH_PRESENCE
4622 result = SendAllObserverNotification (method, resPtr, maxAge,
4623 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4625 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4632 OCNotifyListOfObservers (OCResourceHandle handle,
4633 OCObservationId *obsIdList,
4634 uint8_t numberOfIds,
4635 const OCRepPayload *payload,
4636 OCQualityOfService qos)
4638 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4640 OCResource *resPtr = NULL;
4641 //TODO: we should allow the server to define this
4642 uint32_t maxAge = MAX_OBSERVE_AGE;
4644 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4645 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4646 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4648 resPtr = findResource ((OCResource *) handle);
4649 if (NULL == resPtr || myStackMode == OC_CLIENT)
4651 return OC_STACK_NO_RESOURCE;
4655 incrementSequenceNumber(resPtr);
4657 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4658 payload, maxAge, qos));
4661 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4663 OCStackResult result = OC_STACK_ERROR;
4664 OCServerRequest *serverRequest = NULL;
4666 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4668 // Validate input parameters
4669 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4670 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4673 // Get pointer to request info
4674 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4677 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4678 result = serverRequest->ehResponseHandler(ehResponse);
4684 //#ifdef DIRECT_PAIRING
4685 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4687 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4688 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4690 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4694 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4697 const OCDPDev_t* OCGetDirectPairedDevices()
4699 return (const OCDPDev_t*)DPGetPairedDevices();
4702 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4703 OCDirectPairingCB resultCallback)
4705 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4706 if(NULL == peer || NULL == pinNumber)
4708 OIC_LOG(ERROR, TAG, "Invalid parameters");
4709 return OC_STACK_INVALID_PARAM;
4711 if (NULL == resultCallback)
4713 OIC_LOG(ERROR, TAG, "Invalid callback");
4714 return OC_STACK_INVALID_CALLBACK;
4717 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4718 pinNumber, (OCDirectPairingResultCB)resultCallback);
4720 //#endif // DIRECT_PAIRING
4722 //-----------------------------------------------------------------------------
4723 // Private internal function definitions
4724 //-----------------------------------------------------------------------------
4725 static OCDoHandle GenerateInvocationHandle()
4727 OCDoHandle handle = NULL;
4728 // Generate token here, it will be deleted when the transaction is deleted
4729 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4732 if (!OCGetRandomBytes((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN])))
4742 #ifdef WITH_PRESENCE
4743 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4744 OCResourceProperty resourceProperties, uint8_t enable)
4748 return OC_STACK_INVALID_PARAM;
4750 if (resourceProperties
4751 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4753 OIC_LOG(ERROR, TAG, "Invalid property");
4754 return OC_STACK_INVALID_PARAM;
4758 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4762 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4768 OCStackResult initResources()
4770 OCStackResult result = OC_STACK_OK;
4772 headResource = NULL;
4773 tailResource = NULL;
4774 // Init Virtual Resources
4775 #ifdef WITH_PRESENCE
4776 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4778 result = OCCreateResource(&presenceResource.handle,
4779 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4781 OC_RSRVD_PRESENCE_URI,
4785 //make resource inactive
4786 result = OCChangeResourceProperty(
4787 &(((OCResource *) presenceResource.handle)->resourceProperties),
4790 #ifndef WITH_ARDUINO
4791 if (result == OC_STACK_OK)
4793 result = SRMInitSecureResources();
4797 if(result == OC_STACK_OK)
4799 result = OCCreateResource(&wellKnownResource,
4800 OC_RSRVD_RESOURCE_TYPE_RES,
4801 OC_RSRVD_INTERFACE_LL,
4802 OC_RSRVD_WELL_KNOWN_URI,
4806 if(result == OC_STACK_OK)
4808 result = BindResourceInterfaceToResource((OCResource *)wellKnownResource,
4809 OC_RSRVD_INTERFACE_DEFAULT);
4813 if(result == OC_STACK_OK)
4815 CreateResetProfile();
4816 result = OCCreateResource(&deviceResource,
4817 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4818 OC_RSRVD_INTERFACE_DEFAULT,
4819 OC_RSRVD_DEVICE_URI,
4823 if(result == OC_STACK_OK)
4825 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4826 OC_RSRVD_INTERFACE_READ);
4830 if(result == OC_STACK_OK)
4832 result = OCCreateResource(&platformResource,
4833 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4834 OC_RSRVD_INTERFACE_DEFAULT,
4835 OC_RSRVD_PLATFORM_URI,
4839 if(result == OC_STACK_OK)
4841 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4842 OC_RSRVD_INTERFACE_READ);
4846 if (result == OC_STACK_OK)
4848 result = OCCreateResource(&introspectionResource,
4849 OC_RSRVD_RESOURCE_TYPE_INTROSPECTION,
4850 OC_RSRVD_INTERFACE_DEFAULT,
4851 OC_RSRVD_INTROSPECTION_URI,
4855 if (result == OC_STACK_OK)
4857 result = BindResourceInterfaceToResource((OCResource *)introspectionResource,
4858 OC_RSRVD_INTERFACE_READ);
4862 if (result == OC_STACK_OK)
4864 result = OCCreateResource(&introspectionPayloadResource,
4865 OC_RSRVD_RESOURCE_TYPE_INTROSPECTION_PAYLOAD,
4866 OC_RSRVD_INTERFACE_DEFAULT,
4867 OC_RSRVD_INTROSPECTION_PAYLOAD_URI,
4871 if (result == OC_STACK_OK)
4873 result = BindResourceInterfaceToResource((OCResource *)introspectionPayloadResource,
4874 OC_RSRVD_INTERFACE_READ);
4881 void insertResource(OCResource *resource)
4885 headResource = resource;
4886 tailResource = resource;
4890 tailResource->next = resource;
4891 tailResource = resource;
4893 resource->next = NULL;
4896 OCResource *findResource(OCResource *resource)
4898 OCResource *pointer = headResource;
4902 if (pointer == resource)
4906 pointer = pointer->next;
4911 void deleteAllResources()
4913 OCResource *pointer = headResource;
4914 OCResource *temp = NULL;
4918 temp = pointer->next;
4919 #ifdef WITH_PRESENCE
4920 if (pointer != (OCResource *) presenceResource.handle)
4922 #endif // WITH_PRESENCE
4923 deleteResource(pointer);
4924 #ifdef WITH_PRESENCE
4926 #endif // WITH_PRESENCE
4929 memset(&platformResource, 0, sizeof(platformResource));
4930 memset(&deviceResource, 0, sizeof(deviceResource));
4931 memset(&wellKnownResource, 0, sizeof(wellKnownResource));
4933 memset(&brokerResource, 0, sizeof(brokerResource));
4936 SRMDeInitSecureResources();
4938 #ifdef WITH_PRESENCE
4939 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4940 // presence notification attributed to their deletion to be processed.
4941 deleteResource((OCResource *) presenceResource.handle);
4942 memset(&presenceResource, 0, sizeof(presenceResource));
4943 #endif // WITH_PRESENCE
4946 OCStackResult deleteResource(OCResource *resource)
4948 OCResource *prev = NULL;
4949 OCResource *temp = NULL;
4952 OIC_LOG(DEBUG,TAG,"resource is NULL");
4953 return OC_STACK_INVALID_PARAM;
4956 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4958 temp = headResource;
4961 if (temp == resource)
4963 // Invalidate all Resource Properties.
4964 resource->resourceProperties = (OCResourceProperty) 0;
4965 #ifdef WITH_PRESENCE
4966 if(resource != (OCResource *) presenceResource.handle)
4968 #endif // WITH_PRESENCE
4969 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4970 #ifdef WITH_PRESENCE
4973 if(presenceResource.handle)
4975 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4976 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4979 // Only resource in list.
4980 if (temp == headResource && temp == tailResource)
4982 headResource = NULL;
4983 tailResource = NULL;
4986 else if (temp == headResource)
4988 headResource = temp->next;
4991 else if (temp == tailResource && prev)
4993 tailResource = prev;
4994 tailResource->next = NULL;
4998 prev->next = temp->next;
5001 deleteResourceElements(temp);
5013 return OC_STACK_ERROR;
5016 void deleteResourceElements(OCResource *resource)
5025 OICFree(resource->uri);
5027 if (resource->rsrcType)
5029 deleteResourceType(resource->rsrcType);
5031 if (resource->rsrcInterface)
5033 deleteResourceInterface(resource->rsrcInterface);
5035 if (resource->rsrcChildResourcesHead)
5037 OICFree(resource->rsrcChildResourcesHead);
5039 if (resource->rsrcAttributes)
5041 OCDeleteResourceAttributes(resource->rsrcAttributes);
5045 void deleteResourceType(OCResourceType *resourceType)
5047 OCResourceType *next = NULL;
5049 for (OCResourceType *pointer = resourceType; pointer; pointer = next)
5051 next = pointer->next;
5052 if (pointer->resourcetypename)
5054 OICFree(pointer->resourcetypename);
5060 void deleteResourceInterface(OCResourceInterface *resourceInterface)
5062 OCResourceInterface *next = NULL;
5063 for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
5065 next = pointer->next;
5068 OICFree(pointer->name);
5074 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
5076 OCAttribute *next = NULL;
5077 for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
5079 next = pointer->next;
5080 if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
5082 OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
5084 else if (pointer->attrValue)
5086 OICFree(pointer->attrValue);
5088 if (pointer->attrName)
5090 OICFree(pointer->attrName);
5096 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
5098 OCResourceType *pointer = NULL;
5099 OCResourceType *previous = NULL;
5100 if (!resource || !resourceType)
5104 // resource type list is empty.
5105 else if (!resource->rsrcType)
5107 resource->rsrcType = resourceType;
5111 pointer = resource->rsrcType;
5115 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
5117 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
5118 OICFree(resourceType->resourcetypename);
5119 OICFree(resourceType);
5123 pointer = pointer->next;
5128 previous->next = resourceType;
5131 resourceType->next = NULL;
5133 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
5136 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
5138 OCResource *resource = NULL;
5139 OCResourceType *pointer = NULL;
5141 // Find the specified resource
5142 resource = findResource((OCResource *) handle);
5148 // Make sure a resource has a resourcetype
5149 if (!resource->rsrcType)
5154 // Iterate through the list
5155 pointer = resource->rsrcType;
5156 for(uint8_t i = 0; i< index && pointer; ++i)
5158 pointer = pointer->next;
5163 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
5165 if(resourceTypeList && resourceTypeName)
5167 OCResourceType * rtPointer = resourceTypeList;
5168 while(resourceTypeName && rtPointer)
5170 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
5171 if(rtPointer->resourcetypename &&
5172 strcmp(resourceTypeName, (const char *)
5173 (rtPointer->resourcetypename)) == 0)
5177 rtPointer = rtPointer->next;
5185 * Insert a new interface into interface linked list only if not already present.
5186 * If alredy present, 2nd arg is free'd.
5187 * Default interface will always be first if present.
5189 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
5191 OCResourceInterface *pointer = NULL;
5192 OCResourceInterface *previous = NULL;
5194 newInterface->next = NULL;
5196 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
5198 if (!*firstInterface)
5200 // If first interface is not oic.if.baseline, by default add it as first interface type.
5201 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
5203 *firstInterface = newInterface;
5207 OCStackResult result = BindResourceInterfaceToResource(resource,
5208 OC_RSRVD_INTERFACE_DEFAULT);
5209 if (result != OC_STACK_OK)
5211 OICFree(newInterface->name);
5212 OICFree(newInterface);
5215 if (*firstInterface)
5217 (*firstInterface)->next = newInterface;
5221 // If once add oic.if.baseline, later too below code take care of freeing memory.
5222 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5224 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5226 OICFree(newInterface->name);
5227 OICFree(newInterface);
5230 // This code will not hit anymore, keeping
5233 newInterface->next = *firstInterface;
5234 *firstInterface = newInterface;
5239 pointer = *firstInterface;
5242 if (strcmp(newInterface->name, pointer->name) == 0)
5244 OICFree(newInterface->name);
5245 OICFree(newInterface);
5249 pointer = pointer->next;
5254 previous->next = newInterface;
5259 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
5262 OCResource *resource = NULL;
5263 OCResourceInterface *pointer = NULL;
5265 // Find the specified resource
5266 resource = findResource((OCResource *) handle);
5272 // Make sure a resource has a resourceinterface
5273 if (!resource->rsrcInterface)
5278 // Iterate through the list
5279 pointer = resource->rsrcInterface;
5281 for (uint8_t i = 0; i < index && pointer; ++i)
5283 pointer = pointer->next;
5289 * This function splits the uri using the '?' delimiter.
5290 * "uriWithoutQuery" is the block of characters between the beginning
5291 * till the delimiter or '\0' which ever comes first.
5292 * "query" is whatever is to the right of the delimiter if present.
5293 * No delimiter sets the query to NULL.
5294 * If either are present, they will be malloc'ed into the params 2, 3.
5295 * The first param, *uri is left untouched.
5297 * NOTE: This function does not account for whitespace at the end of the uri NOR
5298 * malformed uri's with '??'. Whitespace at the end will be assumed to be
5299 * part of the query.
5301 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
5305 return OC_STACK_INVALID_URI;
5307 if(!query || !uriWithoutQuery)
5309 return OC_STACK_INVALID_PARAM;
5313 *uriWithoutQuery = NULL;
5315 size_t uriWithoutQueryLen = 0;
5316 size_t queryLen = 0;
5317 size_t uriLen = strlen(uri);
5319 char *pointerToDelimiter = strstr(uri, "?");
5321 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
5322 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
5324 if (uriWithoutQueryLen)
5326 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
5327 if (!*uriWithoutQuery)
5331 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
5335 *query = (char *) OICCalloc(queryLen + 1, 1);
5338 OICFree(*uriWithoutQuery);
5339 *uriWithoutQuery = NULL;
5342 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5348 return OC_STACK_NO_MEMORY;
5351 static const OicUuid_t* OCGetServerInstanceID(void)
5353 static bool generated = false;
5354 static OicUuid_t sid;
5360 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5362 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
5369 const char* OCGetServerInstanceIDString(void)
5371 static bool generated = false;
5372 static char sidStr[UUID_STRING_SIZE];
5379 const OicUuid_t *sid = OCGetServerInstanceID();
5380 if(sid && !OCConvertUuidToString(sid->id, sidStr))
5382 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5390 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5392 OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5393 CAResult_t retResult = CA_STATUS_FAILED;
5394 CAResult_t caResult = CA_STATUS_OK;
5396 CATransportAdapter_t connTypes[] = {
5398 CA_ADAPTER_RFCOMM_BTEDR,
5399 CA_ADAPTER_GATT_BTLE,
5402 ,CA_ADAPTER_REMOTE_ACCESS
5409 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5411 for(int i = 0; i < numConnTypes; i++)
5413 // If CA status is not initialized, CASelectNetwork() will not be called.
5414 if (caResult != CA_STATUS_NOT_INITIALIZED)
5416 if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5418 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5419 caResult = CASelectNetwork(connTypes[i]);
5420 if (caResult == CA_STATUS_OK)
5422 retResult = CA_STATUS_OK;
5427 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5432 if (retResult != CA_STATUS_OK)
5434 return caResult; // Returns error of appropriate transport that failed fatally.
5440 OCStackResult CAResultToOCResult(CAResult_t caResult)
5446 case CA_STATUS_INVALID_PARAM:
5447 return OC_STACK_INVALID_PARAM;
5448 case CA_ADAPTER_NOT_ENABLED:
5449 return OC_STACK_ADAPTER_NOT_ENABLED;
5450 case CA_SERVER_STARTED_ALREADY:
5452 case CA_SERVER_NOT_STARTED:
5453 return OC_STACK_ERROR;
5454 case CA_DESTINATION_NOT_REACHABLE:
5455 return OC_STACK_COMM_ERROR;
5456 case CA_SOCKET_OPERATION_FAILED:
5457 return OC_STACK_COMM_ERROR;
5458 case CA_SEND_FAILED:
5459 return OC_STACK_COMM_ERROR;
5460 case CA_RECEIVE_FAILED:
5461 return OC_STACK_COMM_ERROR;
5462 case CA_MEMORY_ALLOC_FAILED:
5463 return OC_STACK_NO_MEMORY;
5464 case CA_REQUEST_TIMEOUT:
5465 return OC_STACK_TIMEOUT;
5466 case CA_DESTINATION_DISCONNECTED:
5467 return OC_STACK_COMM_ERROR;
5468 case CA_STATUS_FAILED:
5469 return OC_STACK_ERROR;
5470 case CA_NOT_SUPPORTED:
5471 return OC_STACK_NOTIMPL;
5473 return OC_STACK_ERROR;
5477 bool OCResultToSuccess(OCStackResult ocResult)
5482 case OC_STACK_RESOURCE_CREATED:
5483 case OC_STACK_RESOURCE_DELETED:
5484 case OC_STACK_CONTINUE:
5485 case OC_STACK_RESOURCE_CHANGED:
5486 case OC_STACK_SLOW_RESOURCE:
5493 OCStackResult OCSetProxyURI(const char *uri)
5495 return CAResultToOCResult(CASetProxyUri(uri));
5498 #if defined(RD_CLIENT) || defined(RD_SERVER)
5499 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5501 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5503 OCResource *resource = NULL;
5505 resource = findResource((OCResource *) handle);
5508 OIC_LOG(ERROR, TAG, "Resource not found");
5509 return OC_STACK_ERROR;
5512 resource->ins = ins;
5517 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5518 const OCClientResponse *response)
5520 // Validate input parameters
5521 VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5522 VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5524 char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5527 return OC_STACK_NO_MEMORY;
5529 strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5531 if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5533 OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5535 char rdPubUri[MAX_URI_LENGTH] = { 0 };
5536 snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5537 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5539 if (strcmp(rdPubUri, targetUri) == 0)
5541 // Update resource unique id in stack.
5544 if (response->payload)
5546 OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5547 OCRepPayload **links = NULL;
5548 size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5549 if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5550 &links, dimensions))
5553 for (; i < dimensions[0]; i++)
5556 if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5558 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5560 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5562 OCBindResourceInsToResource(handle, ins);
5571 else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5573 OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5575 uint8_t numResources = 0;
5576 OCGetNumberOfResources(&numResources);
5578 char *ins = strstr(targetUri, OC_RSRVD_INS);
5581 for (uint8_t i = 0; i < numResources; i++)
5583 OCResourceHandle resHandle = OCGetResourceHandle(i);
5586 OCBindResourceInsToResource(resHandle, 0);
5592 const char *token = "&";
5593 char *iterTokenPtr = NULL;
5594 char *start = strtok_r(targetUri, token, &iterTokenPtr);
5596 while (start != NULL)
5598 char *query = start;
5599 query = strstr(query, OC_RSRVD_INS);
5602 // Arduino's AVR-GCC doesn't support strtoll().
5604 int matchedItems = sscanf(query + 4, "%lld", &queryIns);
5606 if (0 == matchedItems)
5609 return OC_STACK_INVALID_QUERY;
5612 for (uint8_t i = 0; i < numResources; i++)
5614 OCResourceHandle resHandle = OCGetResourceHandle(i);
5618 OCGetResourceIns(resHandle, &resIns);
5619 if (queryIns && queryIns == resIns)
5621 OCBindResourceInsToResource(resHandle, 0);
5627 start = strtok_r(NULL, token, &iterTokenPtr);
5636 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t* ins)
5638 OCResource *resource = NULL;
5640 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5641 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5643 resource = findResource((OCResource *) handle);
5646 *ins = resource->ins;
5649 return OC_STACK_ERROR;
5651 #endif // RD_CLIENT || RD_SERVER
5653 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5657 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5661 OCResource *pointer = headResource;
5665 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5667 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5670 pointer = pointer->next;
5675 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5676 void* optionData, size_t optionDataLength)
5680 OIC_LOG (INFO, TAG, "Header options are NULL");
5681 return OC_STACK_INVALID_PARAM;
5686 OIC_LOG (INFO, TAG, "optionData are NULL");
5687 return OC_STACK_INVALID_PARAM;
5692 OIC_LOG (INFO, TAG, "numOptions is NULL");
5693 return OC_STACK_INVALID_PARAM;
5696 if (*numOptions >= MAX_HEADER_OPTIONS)
5698 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5699 return OC_STACK_NO_MEMORY;
5702 ocHdrOpt += *numOptions;
5703 ocHdrOpt->protocolID = OC_COAP_ID;
5704 ocHdrOpt->optionID = optionID;
5705 ocHdrOpt->optionLength =
5706 (optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH) ?
5707 (uint16_t)optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5708 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5714 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions,
5715 uint16_t optionID, void* optionData, size_t optionDataLength,
5716 uint16_t* receivedDataLength)
5718 if (!ocHdrOpt || !numOptions)
5720 OIC_LOG (INFO, TAG, "No options present");
5726 OIC_LOG (INFO, TAG, "optionData are NULL");
5727 return OC_STACK_INVALID_PARAM;
5730 if (!receivedDataLength)
5732 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5733 return OC_STACK_INVALID_PARAM;
5736 for (uint8_t i = 0; i < numOptions; i++)
5738 if (ocHdrOpt[i].optionID == optionID)
5740 if (optionDataLength >= ocHdrOpt->optionLength)
5742 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5743 *receivedDataLength = ocHdrOpt->optionLength;
5748 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5749 return OC_STACK_ERROR;
5756 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5758 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5759 if (g_adapterHandler)
5761 g_adapterHandler(adapter, enabled);
5765 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5767 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5768 if (g_connectionHandler)
5770 g_connectionHandler(info, isConnected);
5774 * If the client observes one or more resources over a reliable connection,
5775 * then the CoAP server (or intermediary in the role of the CoAP server)
5776 * MUST remove all entries associated with the client endpoint from the lists
5777 * of observers when the connection is either closed or times out.
5781 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5782 CopyEndpointToDevAddr(info, &devAddr);
5784 // remove observer list with remote device address.
5785 DeleteObserverUsingDevAddr(&devAddr);
5789 void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
5790 CAConnectionStateChangedCB connectionHandler)
5792 OIC_LOG(DEBUG, TAG, "OCSetNetworkMonitorHandler");
5793 g_adapterHandler = adapterHandler;
5794 g_connectionHandler = connectionHandler;
5797 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5800 OCStackResult ret = OC_STACK_ERROR;
5802 ret = GetDoxmDeviceID(&oicUuid);
5803 if (OC_STACK_OK == ret)
5805 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5809 OIC_LOG(ERROR, TAG, "Device ID Get error");
5814 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5817 OCStackResult ret = OC_STACK_ERROR;
5819 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5820 for (int i = 0; i < UUID_LENGTH; i++)
5822 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5824 ret = SetDoxmDeviceID(&oicUuid);
5828 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5830 bool isDeviceOwned = true;
5831 OCStackResult ret = OC_STACK_ERROR;
5833 ret = GetDoxmIsOwned(&isDeviceOwned);
5834 if (OC_STACK_OK == ret)
5836 *isOwned = isDeviceOwned;
5840 OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5845 OCStackResult OCGetLinkLocalZoneId(uint32_t ifindex, char **zoneId)
5847 return CAResultToOCResult(CAGetLinkLocalZoneId(ifindex, zoneId));