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_GATEWAY_TIMEOUT;
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_GATEWAY_TIMEOUT:
865 ret = CA_RETRANSMIT_TIMEOUT;
867 case OC_STACK_NOT_ACCEPTABLE:
868 ret = CA_NOT_ACCEPTABLE;
870 case OC_STACK_UNAUTHORIZED_REQ:
871 ret = CA_UNAUTHORIZED_REQ;
873 case OC_STACK_FORBIDDEN_REQ:
874 ret = CA_FORBIDDEN_REQ;
876 case OC_STACK_INTERNAL_SERVER_ERROR:
877 ret = CA_INTERNAL_SERVER_ERROR;
879 case OC_STACK_BAD_ENDPOINT:
887 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
889 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
891 // supply default behavior.
892 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
894 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
896 if ((caFlags & OC_MASK_SCOPE) == 0)
898 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
903 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
905 return (OCTransportFlags)caFlags;
908 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
910 uint32_t lowerBound = 0;
911 uint32_t higherBound = 0;
913 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
915 return OC_STACK_INVALID_PARAM;
918 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
920 cbNode->presence->TTL = maxAgeSeconds;
922 for (int index = 0; index < PresenceTimeOutSize; index++)
924 // Guard against overflow
925 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
928 lowerBound = GetTicks((PresenceTimeOut[index] *
929 cbNode->presence->TTL *
930 MILLISECONDS_PER_SECOND)/100);
934 lowerBound = GetTicks(UINT32_MAX);
937 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
940 higherBound = GetTicks((PresenceTimeOut[index + 1] *
941 cbNode->presence->TTL *
942 MILLISECONDS_PER_SECOND)/100);
946 higherBound = GetTicks(UINT32_MAX);
949 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
951 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
952 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
953 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
956 cbNode->presence->TTLlevel = 0;
958 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
962 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
964 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
966 return OC_RSRVD_TRIGGER_CREATE;
968 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
970 return OC_RSRVD_TRIGGER_CHANGE;
974 return OC_RSRVD_TRIGGER_DELETE;
978 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
982 return OC_PRESENCE_TRIGGER_CREATE;
984 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
986 return OC_PRESENCE_TRIGGER_CREATE;
988 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
990 return OC_PRESENCE_TRIGGER_CHANGE;
994 return OC_PRESENCE_TRIGGER_DELETE;
998 OCStackResult OCEncodeAddressForRFC6874(char *outputAddress,
1000 const char *inputAddress)
1002 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
1003 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
1005 size_t inputLength = strnlen(inputAddress, outputSize);
1007 // inputSize includes the null terminator
1008 size_t inputSize = inputLength + 1;
1010 if (inputSize > outputSize)
1012 OIC_LOG_V(ERROR, TAG,
1013 "OCEncodeAddressForRFC6874 failed: "
1014 "outputSize (%zu) < inputSize (%zu)",
1015 outputSize, inputSize);
1017 return OC_STACK_ERROR;
1020 char* percentChar = strchr(inputAddress, '%');
1022 // If there is no '%' character, then no change is required to the string.
1023 if (NULL == percentChar)
1025 OICStrcpy(outputAddress, outputSize, inputAddress);
1029 const char* addressPart = &inputAddress[0];
1030 const char* scopeIdPart = percentChar + 1;
1032 // Sanity check to make sure this string doesn't have more '%' characters
1033 if (NULL != strchr(scopeIdPart, '%'))
1035 return OC_STACK_ERROR;
1038 // If no string follows the first '%', then the input was invalid.
1039 if (scopeIdPart[0] == '\0')
1041 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
1042 return OC_STACK_ERROR;
1045 // Check to see if the string is already encoded
1046 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
1048 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Input string is already encoded");
1049 return OC_STACK_ERROR;
1052 // Fail if we don't have room for encoded string's two additional chars
1053 if (outputSize < (inputSize + 2))
1055 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: encoded output will not fit!");
1056 return OC_STACK_ERROR;
1059 // Restore the null terminator with an escaped '%' character, per RFC 6874
1060 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
1061 strcat(outputAddress, "%25");
1062 strcat(outputAddress, scopeIdPart);
1067 OCStackResult OCDecodeAddressForRFC6874(char *outputAddress,
1069 const char *inputAddress,
1072 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
1073 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
1077 end = inputAddress + strlen(inputAddress);
1079 size_t inputLength = end - inputAddress;
1081 const char *percent = strchr(inputAddress, '%');
1082 if (!percent || (percent > end))
1084 OICStrcpyPartial(outputAddress, outputSize, inputAddress, inputLength);
1088 if (percent[1] != '2' || percent[2] != '5')
1090 return OC_STACK_INVALID_URI;
1093 size_t addrlen = percent - inputAddress + 1;
1094 OICStrcpyPartial(outputAddress, outputSize, inputAddress, addrlen);
1095 OICStrcpyPartial(outputAddress + addrlen, outputSize - addrlen,
1096 percent + 3, end - percent - 3);
1103 * The cononical presence allows constructed URIs to be string compared.
1105 * requestUri must be a char array of size CA_MAX_URI_LENGTH
1107 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
1108 char *presenceUri, bool isMulticast)
1110 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
1111 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1115 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1116 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1119 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1120 if (ep->adapter == CA_ADAPTER_IP)
1122 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1124 if ('\0' == ep->addr[0]) // multicast
1126 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1130 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1132 OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1133 sizeof(addressEncoded),
1136 if (OC_STACK_OK != result)
1141 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1142 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1147 if ('\0' == ep->addr[0]) // multicast
1149 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1150 ep->port = OC_MULTICAST_PORT;
1152 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1153 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1157 // might work for other adapters (untested, but better than nothing)
1158 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1159 OC_RSRVD_PRESENCE_URI);
1163 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1164 const CAResponseInfo_t *responseInfo)
1166 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1167 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1169 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1170 ClientCB * cbNode = NULL;
1171 char *resourceTypeName = NULL;
1172 OCClientResponse *response = NULL;
1173 OCStackResult result = OC_STACK_ERROR;
1174 uint32_t maxAge = 0;
1176 char presenceUri[CA_MAX_URI_LENGTH];
1178 int presenceSubscribe = 0;
1179 int multicastPresenceSubscribe = 0;
1181 if (responseInfo->result != CA_CONTENT)
1183 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1184 return OC_STACK_ERROR;
1187 response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1190 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1191 return OC_STACK_ERROR;
1193 response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1195 response->payload = NULL;
1196 response->result = OC_STACK_OK;
1198 CopyEndpointToDevAddr(endpoint, &response->devAddr);
1199 FixUpClientResponse(response);
1201 if (responseInfo->info.payload)
1203 result = OCParsePayload(&response->payload,
1204 PAYLOAD_TYPE_PRESENCE,
1205 responseInfo->info.payload,
1206 responseInfo->info.payloadSize);
1208 if(result != OC_STACK_OK)
1210 OIC_LOG(ERROR, TAG, "Presence parse failed");
1213 if(!response->payload || response->payload->type != PAYLOAD_TYPE_PRESENCE)
1215 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1216 result = OC_STACK_ERROR;
1219 response->sequenceNumber = ((OCPresencePayload*)response->payload)->sequenceNumber;
1220 resourceTypeName = ((OCPresencePayload*)response->payload)->resourceType;
1221 maxAge = ((OCPresencePayload*)response->payload)->maxAge;
1224 // check for unicast presence
1225 uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1226 responseInfo->isMulticast);
1227 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1229 result = OC_STACK_INVALID_URI;
1232 OIC_LOG(INFO, TAG, "check for unicast presence");
1233 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1236 presenceSubscribe = 1;
1240 // check for multicast presence
1241 OIC_LOG(INFO, TAG, "check for multicast presence");
1242 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1245 multicastPresenceSubscribe = 1;
1249 if (!presenceSubscribe && !multicastPresenceSubscribe)
1251 OIC_LOG(INFO, TAG, "Received a presence notification, "
1252 "but need to register presence callback, ignoring");
1256 if (presenceSubscribe)
1258 if(cbNode->sequenceNumber == response->sequenceNumber)
1260 OIC_LOG(INFO, TAG, "No presence change");
1261 ResetPresenceTTL(cbNode, maxAge);
1262 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1268 OIC_LOG(INFO, TAG, "Stopping presence");
1269 response->result = OC_STACK_PRESENCE_STOPPED;
1270 if(cbNode->presence)
1272 OICFree(cbNode->presence->timeOut);
1273 OICFree(cbNode->presence);
1274 cbNode->presence = NULL;
1279 if(!cbNode->presence)
1281 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1283 if(!(cbNode->presence))
1285 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1286 result = OC_STACK_NO_MEMORY;
1290 VERIFY_NON_NULL_V(cbNode->presence);
1291 cbNode->presence->timeOut = NULL;
1292 cbNode->presence->timeOut = (uint32_t *)
1293 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1294 if(!(cbNode->presence->timeOut)){
1296 "Could not allocate memory for cbNode->presence->timeOut");
1297 OICFree(cbNode->presence);
1298 result = OC_STACK_NO_MEMORY;
1303 ResetPresenceTTL(cbNode, maxAge);
1305 cbNode->sequenceNumber = response->sequenceNumber;
1310 // This is the multicast case
1311 OIC_LOG(INFO, TAG, "this is the multicast presence");
1314 OIC_LOG(INFO, TAG, "Stopping presence");
1315 response->result = OC_STACK_PRESENCE_STOPPED;
1319 // Ensure that a filter is actually applied.
1320 if (resourceTypeName && cbNode->filterResourceType)
1322 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1323 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1329 OIC_LOG(INFO, TAG, "Callback for presence");
1331 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response);
1333 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1335 FindAndDeleteClientCB(cbNode);
1339 OCPayloadDestroy(response->payload);
1344 OCStackResult HandleBatchResponse(char *requestUri, OCRepPayload **payload)
1346 if (requestUri && *payload)
1348 char *interfaceName = NULL;
1349 char *rtTypeName = NULL;
1350 char *uriQuery = NULL;
1351 char *uriWithoutQuery = NULL;
1352 if (OC_STACK_OK == getQueryFromUri(requestUri, &uriQuery, &uriWithoutQuery))
1354 if (OC_STACK_OK == ExtractFiltersFromQuery(uriQuery, &interfaceName, &rtTypeName))
1356 if (0 == strcmp(OC_RSRVD_INTERFACE_BATCH, interfaceName))
1358 char *uri = (*payload)->uri;
1359 if (uri && 0 != strcmp(uriWithoutQuery, uri))
1361 OCRepPayload *newPayload = OCRepPayloadCreate();
1364 OCRepPayloadSetUri(newPayload, uri);
1365 newPayload->next = *payload;
1366 *payload = newPayload;
1372 OICFree(interfaceName);
1373 OICFree(rtTypeName);
1375 OICFree(uriWithoutQuery);
1378 return OC_STACK_INVALID_PARAM;
1381 #ifndef WITH_ARDUINO
1382 OCStackResult OCMapZoneIdToLinkLocalEndpoint(OCDiscoveryPayload *payload, uint32_t ifindex)
1386 OIC_LOG(ERROR, TAG, "Given argument payload is NULL!!");
1387 return OC_STACK_INVALID_PARAM;
1390 OCResourcePayload *curRes = payload->resources;
1392 while (curRes != NULL)
1394 OCEndpointPayload* eps = curRes->eps;
1398 if (eps->family & OC_IP_USE_V6)
1400 CATransportFlags_t scopeLevel;
1401 if (CA_STATUS_OK == CAGetIpv6AddrScope(eps->addr, &scopeLevel))
1403 if (CA_SCOPE_LINK == scopeLevel)
1405 char *zoneId = NULL;
1406 if (OC_STACK_OK == OCGetLinkLocalZoneId(ifindex, &zoneId))
1408 assert(zoneId != NULL);
1409 // put zoneId to end of addr
1410 OICStrcat(eps->addr, OC_MAX_ADDR_STR_SIZE, "%");
1411 OICStrcat(eps->addr, OC_MAX_ADDR_STR_SIZE, zoneId);
1416 OIC_LOG(ERROR, TAG, "failed at parse zone-id for link-local address");
1417 return OC_STACK_ERROR;
1423 OIC_LOG(ERROR, TAG, "failed at parse ipv6 scope level");
1424 return OC_STACK_ERROR;
1429 curRes = curRes->next;
1436 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1438 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1440 if(responseInfo->info.resourceUri &&
1441 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1443 HandlePresenceResponse(endPoint, responseInfo);
1447 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1448 responseInfo->info.tokenLength, NULL, NULL);
1450 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1451 responseInfo->info.tokenLength);
1455 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1457 // check obs header option
1458 bool obsHeaderOpt = false;
1459 CAHeaderOption_t *options = responseInfo->info.options;
1460 for (uint8_t i = 0; i< responseInfo->info.numOptions; i++)
1462 if (options && (options[i].optionID == COAP_OPTION_OBSERVE))
1464 obsHeaderOpt = true;
1469 if(responseInfo->result == CA_EMPTY)
1471 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1472 // We do not have a case for the client to receive a RESET
1473 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1475 //This is the case of receiving an ACK on a request to a slow resource!
1476 OIC_LOG(INFO, TAG, "This is a pure ACK");
1477 //TODO: should we inform the client
1478 // app that at least the request was received at the server?
1481 else if (CA_RETRANSMIT_TIMEOUT == responseInfo->result
1482 || CA_NOT_ACCEPTABLE == responseInfo->result)
1484 if (CA_RETRANSMIT_TIMEOUT == responseInfo->result)
1486 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1487 OIC_LOG(INFO, TAG, "Calling into application address space");
1491 OIC_LOG(INFO, TAG, "Server doesn't support the requested payload format");
1492 OIC_LOG(INFO, TAG, "Calling into application address space");
1495 OCClientResponse *response = NULL;
1497 response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1500 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1504 response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1505 CopyEndpointToDevAddr(endPoint, &response->devAddr);
1506 FixUpClientResponse(response);
1507 response->resourceUri = responseInfo->info.resourceUri;
1508 memcpy(response->identity.id, responseInfo->info.identity.id,
1509 sizeof (response->identity.id));
1510 response->identity.id_length = responseInfo->info.identity.id_length;
1512 response->result = CAResponseToOCStackResult(responseInfo->result);
1513 cbNode->callBack(cbNode->context,
1514 cbNode->handle, response);
1515 FindAndDeleteClientCB(cbNode);
1518 else if ((cbNode->method == OC_REST_OBSERVE || cbNode->method == OC_REST_OBSERVE_ALL)
1519 && (responseInfo->result == CA_CONTENT) && !obsHeaderOpt)
1521 OCClientResponse *response = NULL;
1523 response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1526 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1530 response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1531 CopyEndpointToDevAddr(endPoint, &response->devAddr);
1532 FixUpClientResponse(response);
1533 response->resourceUri = responseInfo->info.resourceUri;
1534 memcpy(response->identity.id, responseInfo->info.identity.id,
1535 sizeof (response->identity.id));
1536 response->identity.id_length = responseInfo->info.identity.id_length;
1537 response->result = OC_STACK_OK;
1539 OIC_LOG(DEBUG, TAG, "This is response of observer cancel or observer request fail");
1541 cbNode->callBack(cbNode->context,
1544 FindAndDeleteClientCB(cbNode);
1549 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1550 OIC_LOG(INFO, TAG, "Calling into application address space");
1552 OCClientResponse *response = NULL;
1553 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1555 response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1558 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1562 response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1563 response->sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1564 CopyEndpointToDevAddr(endPoint, &response->devAddr);
1565 FixUpClientResponse(response);
1566 response->resourceUri = responseInfo->info.resourceUri;
1567 memcpy(response->identity.id, responseInfo->info.identity.id,
1568 sizeof (response->identity.id));
1569 response->identity.id_length = responseInfo->info.identity.id_length;
1571 response->result = CAResponseToOCStackResult(responseInfo->result);
1573 if(responseInfo->info.payload &&
1574 responseInfo->info.payloadSize)
1576 // check the security resource
1577 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1579 type = PAYLOAD_TYPE_SECURITY;
1581 else if (cbNode->method == OC_REST_DISCOVER)
1583 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1584 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1586 type = PAYLOAD_TYPE_DISCOVERY;
1589 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1591 type = PAYLOAD_TYPE_DISCOVERY;
1594 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1596 type = PAYLOAD_TYPE_REPRESENTATION;
1598 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1600 type = PAYLOAD_TYPE_REPRESENTATION;
1602 else if (strcmp(cbNode->requestUri, OC_RSRVD_INTROSPECTION_URI) == 0)
1604 type = PAYLOAD_TYPE_REPRESENTATION;
1606 else if (strcmp(cbNode->requestUri, OC_RSRVD_INTROSPECTION_PAYLOAD_URI) == 0)
1608 type = PAYLOAD_TYPE_REPRESENTATION;
1610 #ifdef ROUTING_GATEWAY
1611 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1613 type = PAYLOAD_TYPE_REPRESENTATION;
1616 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1618 type = PAYLOAD_TYPE_REPRESENTATION;
1621 else if (strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1623 type = PAYLOAD_TYPE_REPRESENTATION;
1628 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1629 cbNode->method, cbNode->requestUri);
1633 else if (cbNode->method == OC_REST_GET ||
1634 cbNode->method == OC_REST_PUT ||
1635 cbNode->method == OC_REST_POST ||
1636 cbNode->method == OC_REST_OBSERVE ||
1637 cbNode->method == OC_REST_OBSERVE_ALL ||
1638 cbNode->method == OC_REST_DELETE)
1640 if (cbNode->requestUri)
1642 if (0 == strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri))
1644 type = PAYLOAD_TYPE_REPRESENTATION;
1646 else if (0 == strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri))
1648 type = PAYLOAD_TYPE_REPRESENTATION;
1650 if (type == PAYLOAD_TYPE_INVALID)
1652 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1653 cbNode->method, cbNode->requestUri);
1654 type = PAYLOAD_TYPE_REPRESENTATION;
1659 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1660 type = PAYLOAD_TYPE_REPRESENTATION;
1665 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1666 cbNode->method, cbNode->requestUri);
1671 // In case of error, still want application to receive the error message.
1672 if (OCResultToSuccess(response->result) || PAYLOAD_TYPE_REPRESENTATION == type)
1674 if (OC_STACK_OK != OCParsePayload(&response->payload,
1676 responseInfo->info.payload,
1677 responseInfo->info.payloadSize))
1679 OIC_LOG(ERROR, TAG, "Error converting payload");
1680 OCPayloadDestroy(response->payload);
1684 // Check endpoints has link-local ipv6 address.
1685 // if there is, map zone-id which parsed from ifindex
1686 #ifndef WITH_ARDUINO
1687 if (PAYLOAD_TYPE_DISCOVERY == response->payload->type)
1689 OCDiscoveryPayload *disPayload = (OCDiscoveryPayload*)(response->payload);
1691 OCMapZoneIdToLinkLocalEndpoint(disPayload, response->devAddr.ifindex))
1693 OIC_LOG(ERROR, TAG, "failed at map zone-id for link-local address");
1694 OCPayloadDestroy(response->payload);
1702 response->resourceUri = OICStrdup(cbNode->requestUri);
1706 response->numRcvdVendorSpecificHeaderOptions = 0;
1707 if((responseInfo->info.numOptions > 0) && (responseInfo->info.options != NULL))
1710 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1711 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1714 uint32_t observationOption;
1715 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1716 for (observationOption=0, i=0;
1717 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1721 (observationOption << 8) | optionData[i];
1723 response->sequenceNumber = observationOption;
1724 response->numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1729 response->numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1732 if(response->numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1734 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1735 OCPayloadDestroy(response->payload);
1740 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1742 memcpy (&(response->rcvdVendorSpecificHeaderOptions[i-start]),
1743 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1747 if (cbNode->method == OC_REST_OBSERVE &&
1748 response->sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1749 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1750 response->sequenceNumber <= cbNode->sequenceNumber)
1752 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1753 response->sequenceNumber);
1758 if (cbNode->requestUri)
1760 // if request uri is '/oic/rd', update ins value of resource.
1761 char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
1764 OCUpdateResourceInsWithResponse(cbNode->requestUri, response);
1768 // set remoteID(device ID) into OCClientResponse callback parameter
1769 if (OC_REST_DISCOVER == cbNode->method && PAYLOAD_TYPE_DISCOVERY == type)
1771 OCDiscoveryPayload *payload = (OCDiscoveryPayload*) response->payload;
1772 // Payload can be empty in case of error message.
1773 if (payload && payload->sid)
1775 OICStrcpy(response->devAddr.remoteId, sizeof(response->devAddr.remoteId),
1777 OIC_LOG_V(INFO, TAG, "Device ID of response : %s",
1778 response->devAddr.remoteId);
1780 #if defined(TCP_ADAPTER) && defined(WITH_CLOUD)
1781 CAConnectUserPref_t connPrefer = CA_USER_PREF_CLOUD;
1782 CAResult_t ret = CAUtilCMGetConnectionUserConfig(&connPrefer);
1783 if (ret == CA_STATUS_OK && connPrefer != CA_USER_PREF_CLOUD)
1785 OCCMDiscoveryResource(response);
1790 if (response->payload && response->payload->type == PAYLOAD_TYPE_REPRESENTATION)
1792 HandleBatchResponse(cbNode->requestUri, (OCRepPayload **)&response->payload);
1795 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1798 cbNode->sequenceNumber = response->sequenceNumber;
1800 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1802 FindAndDeleteClientCB(cbNode);
1806 // To keep discovery callbacks active.
1807 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1808 MILLISECONDS_PER_SECOND);
1812 //Need to send ACK when the response is CON
1813 if(responseInfo->info.type == CA_MSG_CONFIRM)
1815 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1816 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1819 OCPayloadDestroy(response->payload);
1827 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1828 if(responseInfo->result == CA_EMPTY)
1830 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1831 if(responseInfo->info.type == CA_MSG_RESET)
1833 OIC_LOG(INFO, TAG, "This is a RESET");
1834 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1835 OC_OBSERVER_NOT_INTERESTED);
1837 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1839 OIC_LOG(INFO, TAG, "This is a pure ACK");
1840 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1841 OC_OBSERVER_STILL_INTERESTED);
1844 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1846 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1847 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1848 OC_OBSERVER_FAILED_COMM);
1853 if(!cbNode && !observer)
1855 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1856 || myStackMode == OC_GATEWAY)
1858 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1859 if(responseInfo->result == CA_EMPTY)
1861 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1865 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1866 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1867 CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1871 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1872 || myStackMode == OC_GATEWAY)
1874 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1875 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1877 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1878 responseInfo->info.messageId);
1880 if (responseInfo->info.type == CA_MSG_RESET)
1882 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1883 responseInfo->info.messageId);
1891 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1893 VERIFY_NON_NULL_NR(endPoint, FATAL);
1894 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1896 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1897 OIC_TRACE_BEGIN(%s:HandleCAResponses, TAG);
1898 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1899 #ifdef ROUTING_GATEWAY
1900 bool needRIHandling = false;
1902 * Routing manager is going to update either of endpoint or response or both.
1903 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1904 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1907 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1909 if(ret != OC_STACK_OK || !needRIHandling)
1911 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1918 * Put source in sender endpoint so that the next packet from application can be routed to
1919 * proper destination and remove "RM" coap header option before passing request / response to
1920 * RI as this option will make no sense to either RI or application.
1922 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1923 (uint8_t *) &(responseInfo->info.numOptions),
1924 (CAEndpoint_t *) endPoint);
1927 OCHandleResponse(endPoint, responseInfo);
1929 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1934 * This function handles error response from CA
1935 * code shall be added to handle the errors
1937 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1939 VERIFY_NON_NULL_NR(endPoint, FATAL);
1940 VERIFY_NON_NULL_NR(errorInfo, FATAL);
1942 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1943 OIC_TRACE_BEGIN(%s:HandleCAErrorResponse, TAG);
1945 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1946 errorInfo->info.tokenLength, NULL, NULL);
1949 OCClientResponse *response = NULL;
1951 response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1954 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1958 response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1959 CopyEndpointToDevAddr(endPoint, &response->devAddr);
1960 FixUpClientResponse(response);
1961 response->resourceUri = errorInfo->info.resourceUri;
1962 memcpy(response->identity.id, errorInfo->info.identity.id,
1963 sizeof (response->identity.id));
1964 response->identity.id_length = errorInfo->info.identity.id_length;
1965 response->result = CAResultToOCResult(errorInfo->result);
1967 cbNode->callBack(cbNode->context, cbNode->handle, response);
1971 ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1972 errorInfo->info.tokenLength);
1975 OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1976 OCStackResult result = CAResultToOCResult(errorInfo->result);
1977 if (OC_STACK_COMM_ERROR == result)
1979 OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1980 OC_OBSERVER_FAILED_COMM);
1984 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1989 * This function sends out Direct Stack Responses. These are responses that are not coming
1990 * from the application entity handler. These responses have no payload and are usually ACKs,
1991 * RESETs or some error conditions that were caught by the stack.
1993 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1994 const CAResponseResult_t responseResult, const CAMessageType_t type,
1995 const uint8_t numOptions, const CAHeaderOption_t *options,
1996 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1997 CADataType_t dataType)
1999 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
2000 CAResponseInfo_t respInfo = {
2001 .result = responseResult
2003 respInfo.info.messageId = coapID;
2004 respInfo.info.numOptions = numOptions;
2006 if (respInfo.info.numOptions)
2008 respInfo.info.options =
2009 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
2010 memcpy (respInfo.info.options, options,
2011 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
2015 respInfo.info.payload = NULL;
2016 respInfo.info.token = token;
2017 respInfo.info.tokenLength = tokenLength;
2018 respInfo.info.type = type;
2019 respInfo.info.resourceUri = OICStrdup (resourceUri);
2020 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
2021 respInfo.info.dataType = dataType;
2023 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2024 // Add the destination to route option from the endpoint->routeData.
2025 bool doPost = false;
2026 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
2027 if(OC_STACK_OK != result)
2029 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
2030 OICFree (respInfo.info.resourceUri);
2031 OICFree (respInfo.info.options);
2036 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
2037 CARequestInfo_t reqInfo = {.method = CA_POST };
2038 /* The following initialization is not done in a single initializer block as in
2039 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
2040 * does not have designated initalizers. This is a work-around for now.
2042 reqInfo.info.type = CA_MSG_NONCONFIRM;
2043 reqInfo.info.messageId = coapID;
2044 reqInfo.info.tokenLength = tokenLength;
2045 reqInfo.info.token = token;
2046 reqInfo.info.numOptions = respInfo.info.numOptions;
2047 reqInfo.info.payload = NULL;
2048 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
2049 if (reqInfo.info.numOptions)
2051 reqInfo.info.options =
2052 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
2053 if (NULL == reqInfo.info.options)
2055 OIC_LOG(ERROR, TAG, "Calloc failed");
2056 OICFree (reqInfo.info.resourceUri);
2057 OICFree (respInfo.info.resourceUri);
2058 OICFree (respInfo.info.options);
2059 return OC_STACK_NO_MEMORY;
2061 memcpy (reqInfo.info.options, respInfo.info.options,
2062 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
2065 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
2066 OICFree (reqInfo.info.resourceUri);
2067 OICFree (reqInfo.info.options);
2068 OICFree (respInfo.info.resourceUri);
2069 OICFree (respInfo.info.options);
2070 if (CA_STATUS_OK != caResult)
2072 OIC_LOG(ERROR, TAG, "CASendRequest error");
2073 return CAResultToOCResult(caResult);
2079 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
2081 // resourceUri in the info field is cloned in the CA layer and
2082 // thus ownership is still here.
2083 OICFree (respInfo.info.resourceUri);
2084 OICFree (respInfo.info.options);
2085 if(CA_STATUS_OK != caResult)
2087 OIC_LOG(ERROR, TAG, "CASendResponse error");
2088 return CAResultToOCResult(caResult);
2091 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
2095 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
2097 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
2098 OCStackResult result = OC_STACK_ERROR;
2099 if (!protocolRequest)
2101 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
2102 return OC_STACK_INVALID_PARAM;
2105 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
2106 protocolRequest->tokenLength);
2109 OIC_LOG(INFO, TAG, "This is a new Server Request");
2110 result = AddServerRequest(&request, protocolRequest->coapID,
2111 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
2112 protocolRequest->numRcvdVendorSpecificHeaderOptions,
2113 protocolRequest->observationOption, protocolRequest->qos,
2114 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
2115 protocolRequest->payload, protocolRequest->requestToken,
2116 protocolRequest->tokenLength, protocolRequest->resourceUrl,
2117 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
2118 protocolRequest->acceptVersion, &protocolRequest->devAddr);
2119 if (OC_STACK_OK != result)
2121 OIC_LOG(ERROR, TAG, "Error adding server request");
2127 OIC_LOG(ERROR, TAG, "Out of Memory");
2128 return OC_STACK_NO_MEMORY;
2131 if(!protocolRequest->reqMorePacket)
2133 request->requestComplete = 1;
2138 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
2141 if (request->requestComplete)
2143 OIC_LOG(INFO, TAG, "This Server Request is complete");
2144 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2145 OCResource *resource = NULL;
2146 result = DetermineResourceHandling (request, &resHandling, &resource);
2147 if (result == OC_STACK_OK)
2149 result = ProcessRequest(resHandling, resource, request);
2154 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2155 result = OC_STACK_CONTINUE;
2160 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2162 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2163 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2165 if (myStackMode == OC_CLIENT)
2167 //TODO: should the client be responding to requests?
2171 // If the request message is Confirmable,
2172 // then the response SHOULD be returned in an Acknowledgement message.
2173 CAMessageType_t directResponseType = requestInfo->info.type;
2174 directResponseType = (directResponseType == CA_MSG_CONFIRM)
2175 ? CA_MSG_ACKNOWLEDGE : CA_MSG_NONCONFIRM;
2177 char * uriWithoutQuery = NULL;
2178 char * query = NULL;
2179 OCStackResult requestResult = OC_STACK_ERROR;
2181 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2183 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2185 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2188 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2189 OIC_LOG_V(INFO, TAG, "Query : %s", query);
2191 OCServerProtocolRequest serverRequest = { 0 };
2192 if (strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2194 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2195 OICFree(uriWithoutQuery);
2199 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2200 OICFree(uriWithoutQuery);
2207 if (strlen(query) < MAX_QUERY_LENGTH)
2209 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2214 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2220 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2222 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2223 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2224 if (!serverRequest.payload)
2226 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2229 memcpy (serverRequest.payload, requestInfo->info.payload,
2230 requestInfo->info.payloadSize);
2234 serverRequest.reqTotalSize = 0;
2237 switch (requestInfo->method)
2240 serverRequest.method = OC_REST_GET;
2243 serverRequest.method = OC_REST_PUT;
2246 serverRequest.method = OC_REST_POST;
2249 serverRequest.method = OC_REST_DELETE;
2252 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2253 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2254 directResponseType, requestInfo->info.numOptions,
2255 requestInfo->info.options, requestInfo->info.token,
2256 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2258 OICFree(serverRequest.payload);
2262 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2263 requestInfo->info.tokenLength);
2265 serverRequest.tokenLength = requestInfo->info.tokenLength;
2266 if (serverRequest.tokenLength)
2269 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2271 if (!serverRequest.requestToken)
2273 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2274 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2275 directResponseType, requestInfo->info.numOptions,
2276 requestInfo->info.options, requestInfo->info.token,
2277 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2279 OICFree(serverRequest.payload);
2282 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2285 switch (requestInfo->info.acceptFormat)
2287 case CA_FORMAT_APPLICATION_CBOR:
2288 serverRequest.acceptFormat = OC_FORMAT_CBOR;
2290 case CA_FORMAT_APPLICATION_VND_OCF_CBOR:
2291 serverRequest.acceptFormat = OC_FORMAT_VND_OCF_CBOR;
2293 case CA_FORMAT_UNDEFINED:
2294 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2297 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2300 if (requestInfo->info.type == CA_MSG_CONFIRM)
2302 serverRequest.qos = OC_HIGH_QOS;
2306 serverRequest.qos = OC_LOW_QOS;
2308 // CA does not need the following field
2309 // Are we sure CA does not need them? how is it responding to multicast
2310 serverRequest.delayedResNeeded = 0;
2312 serverRequest.coapID = requestInfo->info.messageId;
2314 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2316 // copy vendor specific header options
2317 uint8_t tempNum = (requestInfo->info.numOptions);
2319 // Assume no observation requested and it is a pure GET.
2320 // If obs registration/de-registration requested it'll be fetched from the
2321 // options in GetObserveHeaderOption()
2322 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2324 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2325 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2328 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2329 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2330 directResponseType, requestInfo->info.numOptions,
2331 requestInfo->info.options, requestInfo->info.token,
2332 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2334 OICFree(serverRequest.payload);
2335 OICFree(serverRequest.requestToken);
2338 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2339 if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2341 memcpy(&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
2342 sizeof(CAHeaderOption_t) * tempNum);
2345 requestResult = HandleStackRequests (&serverRequest);
2347 if (requestResult == OC_STACK_SLOW_RESOURCE)
2349 // Send ACK to client as precursor to slow response
2350 if (requestInfo->info.type == CA_MSG_CONFIRM)
2352 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2353 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2357 if (requestResult == OC_STACK_RESOURCE_ERROR
2358 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2360 OIC_LOG(ERROR, TAG, "Observe Registration failed due to resource error");
2362 else if (!OCResultToSuccess(requestResult))
2364 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2366 CAResponseResult_t stackResponse = OCToCAStackResult(requestResult, serverRequest.method);
2368 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2369 directResponseType, requestInfo->info.numOptions,
2370 requestInfo->info.options, requestInfo->info.token,
2371 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2374 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2375 // The token is copied in there, and is thus still owned by this function.
2376 OICFree(serverRequest.payload);
2377 OICFree(serverRequest.requestToken);
2378 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2381 //This function will be called back by CA layer when a request is received
2382 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2384 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2385 OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2388 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2395 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2400 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2401 #ifdef ROUTING_GATEWAY
2402 bool needRIHandling = false;
2403 bool isEmptyMsg = false;
2405 * Routing manager is going to update either of endpoint or request or both.
2406 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2407 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2408 * destination. It can also remove "RM" coap header option before passing request / response to
2409 * RI as this option will make no sense to either RI or application.
2411 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2412 &needRIHandling, &isEmptyMsg);
2413 if (OC_STACK_OK != ret || !needRIHandling)
2415 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2422 * Put source in sender endpoint so that the next packet from application can be routed to
2423 * proper destination and remove RM header option.
2425 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2426 (uint8_t *) &(requestInfo->info.numOptions),
2427 (CAEndpoint_t *) endPoint);
2429 #ifdef ROUTING_GATEWAY
2433 * In Gateways, the MSGType in route option is used to check if the actual
2434 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2435 * EMPTY response is sent in the form of POST request which need to be changed
2436 * to a EMPTY response by RM. This translation is done in this part of the code.
2438 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2439 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2440 .info.messageId = requestInfo->info.messageId,
2441 .info.type = CA_MSG_ACKNOWLEDGE};
2442 OCHandleResponse(endPoint, &respInfo);
2448 // Normal handling of the packet
2449 OCHandleRequests(endPoint, requestInfo);
2451 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2455 //-----------------------------------------------------------------------------
2457 //-----------------------------------------------------------------------------
2459 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2462 !raInfo->username ||
2463 !raInfo->hostname ||
2464 !raInfo->xmpp_domain)
2467 return OC_STACK_INVALID_PARAM;
2469 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2470 gRASetInfo = (result == OC_STACK_OK)? true : false;
2476 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2480 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2483 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2485 OIC_LOG(DEBUG, TAG, "call OCInit1");
2486 return OCInit2(mode, serverFlags, clientFlags, OC_DEFAULT_ADAPTER);
2489 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2490 OCTransportAdapter transportType)
2492 OIC_LOG(INFO, TAG, "Entering OCInit2");
2494 // Serialize calls to start and stop the stack.
2495 OCEnterInitializer();
2497 OCStackResult result = OC_STACK_OK;
2499 if (g_ocStackStartCount == 0)
2501 // This is the first call to initialize the stack so it gets to do the real work.
2502 result = OCInitializeInternal(mode, serverFlags, clientFlags, transportType);
2505 if (result == OC_STACK_OK)
2507 // Increment the start count since we're about to return success.
2508 assert(g_ocStackStartCount != UINT_MAX);
2509 assert(stackState == OC_STACK_INITIALIZED);
2510 g_ocStackStartCount++;
2513 OCLeaveInitializer();
2517 OCStackResult OCInitializeInternal(OCMode mode, OCTransportFlags serverFlags,
2518 OCTransportFlags clientFlags, OCTransportAdapter transportType)
2520 if (stackState == OC_STACK_INITIALIZED)
2522 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2523 OCStop() between them are ignored.");
2527 #ifndef ROUTING_GATEWAY
2528 if (OC_GATEWAY == mode)
2530 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2531 return OC_STACK_INVALID_PARAM;
2538 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2539 return OC_STACK_ERROR;
2543 OIC_LOG_V(INFO, TAG, "IoTivity version is v%s", IOTIVITY_VERSION);
2544 OCStackResult result = OC_STACK_ERROR;
2547 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2548 || (mode == OC_GATEWAY)))
2550 OIC_LOG(ERROR, TAG, "Invalid mode");
2551 return OC_STACK_ERROR;
2555 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2557 caglobals.client = true;
2559 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2561 caglobals.server = true;
2564 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2565 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2567 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2569 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2570 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2572 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2575 defaultDeviceHandler = NULL;
2576 defaultDeviceHandlerCallbackParameter = NULL;
2578 result = InitializeScheduleResourceList();
2579 VERIFY_SUCCESS(result, OC_STACK_OK);
2581 result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2582 VERIFY_SUCCESS(result, OC_STACK_OK);
2584 result = CAResultToOCResult(OCSelectNetwork(transportType));
2585 VERIFY_SUCCESS(result, OC_STACK_OK);
2587 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2588 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2589 VERIFY_SUCCESS(result, OC_STACK_OK);
2591 switch (myStackMode)
2594 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2595 result = CAResultToOCResult(CAStartDiscoveryServer());
2596 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2599 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2600 result = CAResultToOCResult(CAStartListeningServer());
2601 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2603 case OC_CLIENT_SERVER:
2605 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2606 result = CAResultToOCResult(CAStartListeningServer());
2607 if(result == OC_STACK_OK)
2609 result = CAResultToOCResult(CAStartDiscoveryServer());
2613 VERIFY_SUCCESS(result, OC_STACK_OK);
2616 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2619 #ifdef WITH_PRESENCE
2620 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2621 #endif // WITH_PRESENCE
2623 //Update Stack state to initialized
2624 stackState = OC_STACK_INITIALIZED;
2626 // Initialize resource
2627 if(myStackMode != OC_CLIENT)
2629 result = initResources();
2632 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2633 RMSetStackMode(mode);
2634 #ifdef ROUTING_GATEWAY
2635 if (OC_GATEWAY == myStackMode)
2637 result = RMInitialize();
2643 if (result == OC_STACK_OK)
2645 result = InitializeKeepAlive(myStackMode);
2649 #if defined(TCP_ADAPTER) && defined(WITH_CLOUD)
2650 // Initialize the Connection Manager
2651 if (result == OC_STACK_OK)
2653 result = OCCMInitialize();
2658 if(result != OC_STACK_OK)
2660 OIC_LOG(ERROR, TAG, "Stack initialization error");
2661 TerminateScheduleResourceList();
2662 deleteAllResources();
2664 stackState = OC_STACK_UNINITIALIZED;
2669 OCStackResult OCStop()
2671 OIC_LOG(INFO, TAG, "Entering OCStop");
2673 // Serialize calls to start and stop the stack.
2674 OCEnterInitializer();
2676 OCStackResult result = OC_STACK_OK;
2678 if (g_ocStackStartCount == 1)
2680 // This is the last call to stop the stack, do the real work.
2681 result = OCDeInitializeInternal();
2683 else if (g_ocStackStartCount == 0)
2685 OIC_LOG(ERROR, TAG, "Too many calls to OCStop");
2686 assert(!"Too many calls to OCStop");
2687 result = OC_STACK_ERROR;
2690 if (result == OC_STACK_OK)
2692 g_ocStackStartCount--;
2695 OCLeaveInitializer();
2699 OCStackResult OCDeInitializeInternal()
2701 assert(stackState == OC_STACK_INITIALIZED);
2703 #ifdef WITH_PRESENCE
2704 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2705 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2706 presenceResource.presenceTTL = 0;
2707 presenceState = OC_PRESENCE_UNINITIALIZED;
2708 #endif // WITH_PRESENCE
2710 #ifdef ROUTING_GATEWAY
2711 if (OC_GATEWAY == myStackMode)
2718 TerminateKeepAlive(myStackMode);
2721 OCStackResult result = CAResultToOCResult(
2722 CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2723 OCDefaultConnectionStateChangedHandler));
2724 if (OC_STACK_OK != result)
2726 OIC_LOG(ERROR, TAG, "CAUnregisterNetworkMonitorHandler has failed");
2729 TerminateScheduleResourceList();
2730 // Remove all observers
2731 DeleteObserverList();
2732 // Free memory dynamically allocated for resources
2733 deleteAllResources();
2734 // Remove all the client callbacks
2735 DeleteClientCBList();
2736 // Terminate connectivity-abstraction layer.
2739 #if defined(TCP_ADAPTER) && defined(WITH_CLOUD)
2740 // Terminate the Connection Manager
2744 // Unset cautil config
2745 CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2746 CAUtilSetBTConfigure(configs);
2748 stackState = OC_STACK_UNINITIALIZED;
2752 OCStackResult OCStartMulticastServer()
2754 if(stackState != OC_STACK_INITIALIZED)
2756 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2757 return OC_STACK_ERROR;
2759 CAResult_t ret = CAStartListeningServer();
2760 if (CA_STATUS_OK != ret)
2762 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2763 return OC_STACK_ERROR;
2768 OCStackResult OCStopMulticastServer()
2770 CAResult_t ret = CAStopListeningServer();
2771 if (CA_STATUS_OK != ret)
2773 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2774 return OC_STACK_ERROR;
2779 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2784 return CA_MSG_CONFIRM;
2789 return CA_MSG_NONCONFIRM;
2794 * A request uri consists of the following components in order:
2797 * CoAP over UDP prefix "coap://"
2798 * CoAP over TCP prefix "coap+tcp://"
2799 * CoAP over DTLS prefix "coaps://"
2800 * CoAP over TLS prefix "coaps+tcp://"
2802 * IPv6 address "[1234::5678]"
2803 * IPv4 address "192.168.1.1"
2804 * optional port ":5683"
2805 * resource uri "/oc/core..."
2807 * for PRESENCE requests, extract resource type.
2809 static OCStackResult ParseRequestUri(const char *fullUri,
2810 OCTransportAdapter adapter,
2811 OCTransportFlags flags,
2812 OCDevAddr **devAddr,
2814 char **resourceType)
2816 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2818 OCStackResult result = OC_STACK_OK;
2819 OCDevAddr *da = NULL;
2823 // provide defaults for all returned values
2830 *resourceUri = NULL;
2834 *resourceType = NULL;
2837 // delimit url prefix, if any
2838 const char *start = fullUri;
2839 char *slash2 = strstr(start, "//");
2844 char *slash = strchr(start, '/');
2847 return OC_STACK_INVALID_URI;
2850 // process url scheme
2851 size_t prefixLen = slash2 - fullUri;
2855 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2856 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2862 // TODO: this logic should come in with unit tests exercising the various strings
2863 // processs url prefix, if any
2864 size_t urlLen = slash - start;
2868 if (urlLen && devAddr)
2869 { // construct OCDevAddr
2870 if (start[0] == '[')
2872 char *close = strchr(++start, ']');
2873 if (!close || close > slash)
2875 return OC_STACK_INVALID_URI;
2878 if (close[1] == ':')
2885 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2889 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2891 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2895 char *dot = strchr(start, '.');
2896 if (dot && dot < slash)
2898 colon = strchr(start, ':');
2899 end = (colon && colon < slash) ? colon : slash;
2904 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2908 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2910 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2918 if (len >= sizeof(da->addr))
2920 return OC_STACK_INVALID_URI;
2922 // collect port, if any
2923 if (colon && colon < slash)
2925 for (colon++; colon < slash; colon++)
2928 if (c < '0' || c > '9')
2930 return OC_STACK_INVALID_URI;
2932 port = 10 * port + c - '0';
2937 if (len >= sizeof(da->addr))
2939 return OC_STACK_INVALID_URI;
2942 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2945 return OC_STACK_NO_MEMORY;
2948 // Decode address per RFC 6874.
2949 result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2950 if (result != OC_STACK_OK)
2957 da->adapter = adapter;
2959 if (!strncmp(fullUri, "coaps", 5))
2961 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2966 // process resource uri, if any
2968 { // request uri and query
2969 size_t ulen = strlen(slash); // resource uri length
2970 size_t tlen = 0; // resource type length
2973 static const char strPresence[] = "/oic/ad?rt=";
2974 static const size_t lenPresence = sizeof(strPresence) - 1;
2975 if (!strncmp(slash, strPresence, lenPresence))
2977 type = slash + lenPresence;
2978 tlen = ulen - lenPresence;
2983 *resourceUri = (char *)OICMalloc(ulen + 1);
2986 result = OC_STACK_NO_MEMORY;
2989 strcpy(*resourceUri, slash);
2992 if (type && resourceType)
2994 *resourceType = (char *)OICMalloc(tlen + 1);
2997 result = OC_STACK_NO_MEMORY;
3001 OICStrcpy(*resourceType, (tlen+1), type);
3008 // free all returned values
3015 OICFree(*resourceUri);
3019 OICFree(*resourceType);
3024 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
3028 char uri[CA_MAX_URI_LENGTH];
3030 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
3032 *requestUri = OICStrdup(uri);
3035 return OC_STACK_NO_MEMORY;
3042 * Discover or Perform requests on a specified resource
3044 OCStackResult OCDoResource(OCDoHandle *handle,
3046 const char *requestUri,
3047 const OCDevAddr *destination,
3049 OCConnectivityType connectivityType,
3050 OCQualityOfService qos,
3051 OCCallbackData *cbData,
3052 OCHeaderOption *options,
3055 OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
3056 connectivityType, qos, cbData, options, numOptions);
3058 // This is the owner of the payload object, so we free it
3059 OCPayloadDestroy(payload);
3064 * Discover or Perform requests on a specified resource
3066 OCStackResult OCDoRequest(OCDoHandle *handle,
3068 const char *requestUri,
3069 const OCDevAddr *destination,
3071 OCConnectivityType connectivityType,
3072 OCQualityOfService qos,
3073 OCCallbackData *cbData,
3074 OCHeaderOption *options,
3077 OIC_LOG(INFO, TAG, "Entering OCDoResource");
3079 // Validate input parameters
3080 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
3081 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
3083 OCStackResult result = OC_STACK_ERROR;
3084 CAResult_t caResult;
3085 CAToken_t token = NULL;
3086 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3087 ClientCB *clientCB = NULL;
3088 OCDoHandle resHandle = NULL;
3089 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3090 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
3092 OCTransportAdapter adapter;
3093 OCTransportFlags flags;
3094 // the request contents are put here
3095 CARequestInfo_t requestInfo = {.method = CA_GET};
3096 // requestUri will be parsed into the following three variables
3097 OCDevAddr *devAddr = NULL;
3098 char *resourceUri = NULL;
3099 char *resourceType = NULL;
3102 * Support original behavior with address on resourceUri argument.
3104 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
3105 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
3109 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
3110 if (result != OC_STACK_OK)
3112 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
3116 else if (!checkProxyUri(options, numOptions))
3118 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
3125 case OC_REST_OBSERVE:
3126 case OC_REST_OBSERVE_ALL:
3127 requestInfo.method = CA_GET;
3130 requestInfo.method = CA_PUT;
3133 requestInfo.method = CA_POST;
3135 case OC_REST_DELETE:
3136 requestInfo.method = CA_DELETE;
3138 case OC_REST_DISCOVER:
3139 // intentional fall through don't add break
3140 #ifdef WITH_PRESENCE
3141 case OC_REST_PRESENCE:
3143 if (destination || devAddr)
3145 requestInfo.isMulticast = false;
3149 tmpDevAddr.adapter = adapter;
3150 tmpDevAddr.flags = flags;
3151 destination = &tmpDevAddr;
3152 requestInfo.isMulticast = true;
3155 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
3156 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
3157 // replacing method type with GET.
3158 requestInfo.method = CA_GET;
3161 result = OC_STACK_INVALID_METHOD;
3165 if (!devAddr && !destination)
3167 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
3168 result = OC_STACK_INVALID_PARAM;
3172 /* If not original behavior, use destination argument */
3173 if (destination && !devAddr)
3175 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
3178 result = OC_STACK_NO_MEMORY;
3181 OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
3182 *devAddr = *destination;
3187 OIC_LOG_V(DEBUG, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
3190 resHandle = GenerateInvocationHandle();
3193 result = OC_STACK_NO_MEMORY;
3197 caResult = CAGenerateToken(&token, tokenLength);
3198 if (caResult != CA_STATUS_OK)
3200 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3201 result= OC_STACK_ERROR;
3205 // fill in request data
3206 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3207 requestInfo.info.token = token;
3208 requestInfo.info.tokenLength = tokenLength;
3210 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3212 result = CreateObserveHeaderOption (&(requestInfo.info.options),
3213 options, numOptions, OC_OBSERVE_REGISTER);
3214 if (result != OC_STACK_OK)
3218 requestInfo.info.numOptions = numOptions + 1;
3222 requestInfo.info.numOptions = numOptions;
3223 requestInfo.info.options =
3224 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3225 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3226 numOptions * sizeof(CAHeaderOption_t));
3229 CopyDevAddrToEndpoint(devAddr, &endpoint);
3234 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3237 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3241 uint16_t payloadVersion = OC_SPEC_VERSION_VALUE;
3242 // From OCF onwards, check version option settings
3243 if (DEFAULT_CONTENT_VERSION_VALUE <= payloadVersion)
3245 if (numOptions > 0 && options)
3247 for (uint8_t i = 0; i < numOptions; i++)
3249 if (COAP_OPTION_CONTENT_VERSION == options[i].optionID)
3251 payloadVersion = options[i].optionData[0];
3254 else if (COAP_OPTION_ACCEPT_VERSION == options[i].optionID)
3256 payloadVersion = options[i].optionData[0];
3263 if (DEFAULT_CONTENT_VERSION_VALUE <= payloadVersion)
3265 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_VND_OCF_CBOR;
3266 requestInfo.info.payloadVersion = payloadVersion;
3270 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3275 requestInfo.info.payload = NULL;
3276 requestInfo.info.payloadSize = 0;
3277 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3280 // prepare for response
3281 #ifdef WITH_PRESENCE
3282 if (method == OC_REST_PRESENCE)
3284 char *presenceUri = NULL;
3285 result = OCPreparePresence(&endpoint, &presenceUri,
3286 requestInfo.isMulticast);
3287 if (OC_STACK_OK != result)
3292 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3293 // Presence notification will form a canonical uri to
3294 // look for callbacks into the application.
3297 OICFree(resourceUri);
3299 resourceUri = presenceUri;
3303 // update resourceUri onto requestInfo after check presence uri
3304 requestInfo.info.resourceUri = resourceUri;
3306 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3307 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3308 method, devAddr, resourceUri, resourceType, ttl);
3309 if (OC_STACK_OK != result)
3314 devAddr = NULL; // Client CB list entry now owns it
3315 resourceUri = NULL; // Client CB list entry now owns it
3316 resourceType = NULL; // Client CB list entry now owns it
3318 #ifdef WITH_PRESENCE
3319 if (method == OC_REST_PRESENCE)
3321 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3325 *handle = resHandle;
3333 result = OCSendRequest(&endpoint, &requestInfo);
3334 if (OC_STACK_OK != result)
3341 *handle = resHandle;
3345 if (result != OC_STACK_OK)
3347 OIC_LOG(ERROR, TAG, "OCDoResource error");
3348 FindAndDeleteClientCB(clientCB);
3349 CADestroyToken(token);
3357 OICFree(requestInfo.info.payload);
3359 OICFree(resourceUri);
3360 OICFree(resourceType);
3361 OICFree(requestInfo.info.options);
3365 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3369 * This ftn is implemented one of two ways in the case of observation:
3371 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3372 * Remove the callback associated on client side.
3373 * When the next notification comes in from server,
3374 * reply with RESET message to server.
3375 * Keep in mind that the server will react to RESET only
3376 * if the last notification was sent as CON
3378 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3379 * and it is associated with an observe request
3380 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3381 * Send CON Observe request to server with
3382 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3383 * Remove the callback associated on client side.
3385 OCStackResult ret = OC_STACK_OK;
3386 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3387 CARequestInfo_t requestInfo = {.method = CA_GET};
3391 return OC_STACK_INVALID_PARAM;
3394 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3397 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3398 return OC_STACK_ERROR;
3401 switch (clientCB->method)
3403 case OC_REST_OBSERVE:
3404 case OC_REST_OBSERVE_ALL:
3406 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3408 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3410 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
3412 FindAndDeleteClientCB(clientCB);
3416 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3418 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3419 requestInfo.info.token = clientCB->token;
3420 requestInfo.info.tokenLength = clientCB->tokenLength;
3422 if (CreateObserveHeaderOption (&(requestInfo.info.options),
3423 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3425 return OC_STACK_ERROR;
3427 requestInfo.info.numOptions = numOptions + 1;
3428 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3431 ret = OCSendRequest(&endpoint, &requestInfo);
3433 if (requestInfo.info.options)
3435 OICFree (requestInfo.info.options);
3437 if (requestInfo.info.resourceUri)
3439 OICFree (requestInfo.info.resourceUri);
3444 case OC_REST_DISCOVER:
3445 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3446 clientCB->requestUri);
3447 FindAndDeleteClientCB(clientCB);
3450 #ifdef WITH_PRESENCE
3451 case OC_REST_PRESENCE:
3452 FindAndDeleteClientCB(clientCB);
3457 ret = OC_STACK_INVALID_METHOD;
3465 * @brief Register Persistent storage callback.
3466 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3468 * OC_STACK_OK - No errors; Success
3469 * OC_STACK_INVALID_PARAM - Invalid parameter
3471 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3473 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3474 if(persistentStorageHandler)
3476 if( !persistentStorageHandler->open ||
3477 !persistentStorageHandler->close ||
3478 !persistentStorageHandler->read ||
3479 !persistentStorageHandler->unlink ||
3480 !persistentStorageHandler->write)
3482 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3483 return OC_STACK_INVALID_PARAM;
3486 g_PersistentStorageHandler = persistentStorageHandler;
3490 OCPersistentStorage *OCGetPersistentStorageHandler()
3492 return g_PersistentStorageHandler;
3495 #ifdef WITH_PRESENCE
3497 OCStackResult OCProcessPresence()
3499 OCStackResult result = OC_STACK_OK;
3501 // the following line floods the log with messages that are irrelevant
3502 // to most purposes. Uncomment as needed.
3503 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3504 ClientCB* cbNode = NULL;
3505 ClientCB* cbTemp = NULL;
3506 OCClientResponse clientResponse;
3507 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3509 LL_FOREACH_SAFE(cbList, cbNode, cbTemp)
3511 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3516 uint32_t now = GetTicks(0);
3517 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3518 cbNode->presence->TTLlevel);
3519 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3521 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3526 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3528 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3529 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3531 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3533 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3535 clientResponse.sequenceNumber = 0;
3536 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3537 clientResponse.devAddr = *cbNode->devAddr;
3538 FixUpClientResponse(&clientResponse);
3539 clientResponse.payload = NULL;
3541 // Increment the TTLLevel (going to a next state), so we don't keep
3542 // sending presence notification to client.
3543 cbNode->presence->TTLlevel++;
3544 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3545 cbNode->presence->TTLlevel);
3547 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3548 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3550 FindAndDeleteClientCB(cbNode);
3554 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3559 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3560 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3561 CARequestInfo_t requestInfo = {.method = CA_GET};
3563 OIC_LOG(DEBUG, TAG, "time to test server presence");
3565 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3567 requestData.type = CA_MSG_NONCONFIRM;
3568 requestData.token = cbNode->token;
3569 requestData.tokenLength = cbNode->tokenLength;
3570 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3571 requestInfo.method = CA_GET;
3572 requestInfo.info = requestData;
3574 result = OCSendRequest(&endpoint, &requestInfo);
3575 if (OC_STACK_OK != result)
3580 cbNode->presence->TTLlevel++;
3581 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3584 if (result != OC_STACK_OK)
3586 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3591 #endif // WITH_PRESENCE
3593 OCStackResult OCProcess()
3595 if (stackState == OC_STACK_UNINITIALIZED)
3597 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
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);
4878 // Initialize Device Properties
4879 if (OC_STACK_OK == result)
4881 result = InitializeDeviceProperties();
4887 void insertResource(OCResource *resource)
4891 headResource = resource;
4892 tailResource = resource;
4896 tailResource->next = resource;
4897 tailResource = resource;
4899 resource->next = NULL;
4902 OCResource *findResource(OCResource *resource)
4904 OCResource *pointer = headResource;
4908 if (pointer == resource)
4912 pointer = pointer->next;
4917 void deleteAllResources()
4919 OCResource *pointer = headResource;
4920 OCResource *temp = NULL;
4924 temp = pointer->next;
4925 #ifdef WITH_PRESENCE
4926 if (pointer != (OCResource *) presenceResource.handle)
4928 #endif // WITH_PRESENCE
4929 deleteResource(pointer);
4930 #ifdef WITH_PRESENCE
4932 #endif // WITH_PRESENCE
4935 memset(&platformResource, 0, sizeof(platformResource));
4936 memset(&deviceResource, 0, sizeof(deviceResource));
4937 memset(&wellKnownResource, 0, sizeof(wellKnownResource));
4939 memset(&brokerResource, 0, sizeof(brokerResource));
4942 SRMDeInitSecureResources();
4944 #ifdef WITH_PRESENCE
4945 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4946 // presence notification attributed to their deletion to be processed.
4947 deleteResource((OCResource *) presenceResource.handle);
4948 memset(&presenceResource, 0, sizeof(presenceResource));
4949 #endif // WITH_PRESENCE
4952 OCStackResult deleteResource(OCResource *resource)
4954 OCResource *prev = NULL;
4955 OCResource *temp = NULL;
4958 OIC_LOG(DEBUG,TAG,"resource is NULL");
4959 return OC_STACK_INVALID_PARAM;
4962 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4964 temp = headResource;
4967 if (temp == resource)
4969 // Invalidate all Resource Properties.
4970 resource->resourceProperties = (OCResourceProperty) 0;
4971 #ifdef WITH_PRESENCE
4972 if(resource != (OCResource *) presenceResource.handle)
4974 #endif // WITH_PRESENCE
4975 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4976 #ifdef WITH_PRESENCE
4979 if(presenceResource.handle)
4981 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4982 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4985 // Only resource in list.
4986 if (temp == headResource && temp == tailResource)
4988 headResource = NULL;
4989 tailResource = NULL;
4992 else if (temp == headResource)
4994 headResource = temp->next;
4997 else if (temp == tailResource && prev)
4999 tailResource = prev;
5000 tailResource->next = NULL;
5004 prev->next = temp->next;
5007 deleteResourceElements(temp);
5019 return OC_STACK_ERROR;
5022 void deleteResourceElements(OCResource *resource)
5031 OICFree(resource->uri);
5033 if (resource->rsrcType)
5035 deleteResourceType(resource->rsrcType);
5037 if (resource->rsrcInterface)
5039 deleteResourceInterface(resource->rsrcInterface);
5041 if (resource->rsrcChildResourcesHead)
5043 OICFree(resource->rsrcChildResourcesHead);
5045 if (resource->rsrcAttributes)
5047 OCDeleteResourceAttributes(resource->rsrcAttributes);
5051 void deleteResourceType(OCResourceType *resourceType)
5053 OCResourceType *next = NULL;
5055 for (OCResourceType *pointer = resourceType; pointer; pointer = next)
5057 next = pointer->next;
5058 if (pointer->resourcetypename)
5060 OICFree(pointer->resourcetypename);
5066 void deleteResourceInterface(OCResourceInterface *resourceInterface)
5068 OCResourceInterface *next = NULL;
5069 for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
5071 next = pointer->next;
5074 OICFree(pointer->name);
5080 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
5082 OCAttribute *next = NULL;
5083 for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
5085 next = pointer->next;
5086 if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
5088 OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
5090 else if (pointer->attrValue)
5092 OICFree(pointer->attrValue);
5094 if (pointer->attrName)
5096 OICFree(pointer->attrName);
5102 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
5104 OCResourceType *pointer = NULL;
5105 OCResourceType *previous = NULL;
5106 if (!resource || !resourceType)
5110 // resource type list is empty.
5111 else if (!resource->rsrcType)
5113 resource->rsrcType = resourceType;
5117 pointer = resource->rsrcType;
5121 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
5123 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
5124 OICFree(resourceType->resourcetypename);
5125 OICFree(resourceType);
5129 pointer = pointer->next;
5134 previous->next = resourceType;
5137 resourceType->next = NULL;
5139 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
5142 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
5144 OCResource *resource = NULL;
5145 OCResourceType *pointer = NULL;
5147 // Find the specified resource
5148 resource = findResource((OCResource *) handle);
5154 // Make sure a resource has a resourcetype
5155 if (!resource->rsrcType)
5160 // Iterate through the list
5161 pointer = resource->rsrcType;
5162 for(uint8_t i = 0; i< index && pointer; ++i)
5164 pointer = pointer->next;
5169 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
5171 if(resourceTypeList && resourceTypeName)
5173 OCResourceType * rtPointer = resourceTypeList;
5174 while(resourceTypeName && rtPointer)
5176 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
5177 if(rtPointer->resourcetypename &&
5178 strcmp(resourceTypeName, (const char *)
5179 (rtPointer->resourcetypename)) == 0)
5183 rtPointer = rtPointer->next;
5191 * Insert a new interface into interface linked list only if not already present.
5192 * If alredy present, 2nd arg is free'd.
5193 * Default interface will always be first if present.
5195 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
5197 OCResourceInterface *pointer = NULL;
5198 OCResourceInterface *previous = NULL;
5200 newInterface->next = NULL;
5202 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
5204 if (!*firstInterface)
5206 // If first interface is not oic.if.baseline, by default add it as first interface type.
5207 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
5209 *firstInterface = newInterface;
5213 OCStackResult result = BindResourceInterfaceToResource(resource,
5214 OC_RSRVD_INTERFACE_DEFAULT);
5215 if (result != OC_STACK_OK)
5217 OICFree(newInterface->name);
5218 OICFree(newInterface);
5221 if (*firstInterface)
5223 (*firstInterface)->next = newInterface;
5227 // If once add oic.if.baseline, later too below code take care of freeing memory.
5228 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5230 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5232 OICFree(newInterface->name);
5233 OICFree(newInterface);
5236 // This code will not hit anymore, keeping
5239 newInterface->next = *firstInterface;
5240 *firstInterface = newInterface;
5245 pointer = *firstInterface;
5248 if (strcmp(newInterface->name, pointer->name) == 0)
5250 OICFree(newInterface->name);
5251 OICFree(newInterface);
5255 pointer = pointer->next;
5260 previous->next = newInterface;
5265 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
5268 OCResource *resource = NULL;
5269 OCResourceInterface *pointer = NULL;
5271 // Find the specified resource
5272 resource = findResource((OCResource *) handle);
5278 // Make sure a resource has a resourceinterface
5279 if (!resource->rsrcInterface)
5284 // Iterate through the list
5285 pointer = resource->rsrcInterface;
5287 for (uint8_t i = 0; i < index && pointer; ++i)
5289 pointer = pointer->next;
5295 * This function splits the uri using the '?' delimiter.
5296 * "uriWithoutQuery" is the block of characters between the beginning
5297 * till the delimiter or '\0' which ever comes first.
5298 * "query" is whatever is to the right of the delimiter if present.
5299 * No delimiter sets the query to NULL.
5300 * If either are present, they will be malloc'ed into the params 2, 3.
5301 * The first param, *uri is left untouched.
5303 * NOTE: This function does not account for whitespace at the end of the uri NOR
5304 * malformed uri's with '??'. Whitespace at the end will be assumed to be
5305 * part of the query.
5307 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
5311 return OC_STACK_INVALID_URI;
5313 if(!query || !uriWithoutQuery)
5315 return OC_STACK_INVALID_PARAM;
5319 *uriWithoutQuery = NULL;
5321 size_t uriWithoutQueryLen = 0;
5322 size_t queryLen = 0;
5323 size_t uriLen = strlen(uri);
5325 char *pointerToDelimiter = strstr(uri, "?");
5327 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
5328 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
5330 if (uriWithoutQueryLen)
5332 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
5333 if (!*uriWithoutQuery)
5337 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
5341 *query = (char *) OICCalloc(queryLen + 1, 1);
5344 OICFree(*uriWithoutQuery);
5345 *uriWithoutQuery = NULL;
5348 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5354 return OC_STACK_NO_MEMORY;
5357 static const OicUuid_t* OCGetServerInstanceID(void)
5359 static bool generated = false;
5360 static OicUuid_t sid;
5366 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5368 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
5375 const char* OCGetServerInstanceIDString(void)
5377 static bool generated = false;
5378 static char sidStr[UUID_STRING_SIZE];
5385 const OicUuid_t *sid = OCGetServerInstanceID();
5386 if(sid && !OCConvertUuidToString(sid->id, sidStr))
5388 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5396 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5398 OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5399 CAResult_t retResult = CA_STATUS_FAILED;
5400 CAResult_t caResult = CA_STATUS_OK;
5402 CATransportAdapter_t connTypes[] = {
5404 CA_ADAPTER_RFCOMM_BTEDR,
5405 CA_ADAPTER_GATT_BTLE,
5408 ,CA_ADAPTER_REMOTE_ACCESS
5415 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5417 for(int i = 0; i < numConnTypes; i++)
5419 // If CA status is not initialized, CASelectNetwork() will not be called.
5420 if (caResult != CA_STATUS_NOT_INITIALIZED)
5422 if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5424 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5425 caResult = CASelectNetwork(connTypes[i]);
5426 if (caResult == CA_STATUS_OK)
5428 retResult = CA_STATUS_OK;
5433 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5438 if (retResult != CA_STATUS_OK)
5440 return caResult; // Returns error of appropriate transport that failed fatally.
5446 OCStackResult CAResultToOCResult(CAResult_t caResult)
5452 case CA_STATUS_INVALID_PARAM:
5453 return OC_STACK_INVALID_PARAM;
5454 case CA_ADAPTER_NOT_ENABLED:
5455 return OC_STACK_ADAPTER_NOT_ENABLED;
5456 case CA_SERVER_STARTED_ALREADY:
5458 case CA_SERVER_NOT_STARTED:
5459 return OC_STACK_ERROR;
5460 case CA_DESTINATION_NOT_REACHABLE:
5461 return OC_STACK_COMM_ERROR;
5462 case CA_SOCKET_OPERATION_FAILED:
5463 return OC_STACK_COMM_ERROR;
5464 case CA_SEND_FAILED:
5465 return OC_STACK_COMM_ERROR;
5466 case CA_RECEIVE_FAILED:
5467 return OC_STACK_COMM_ERROR;
5468 case CA_MEMORY_ALLOC_FAILED:
5469 return OC_STACK_NO_MEMORY;
5470 case CA_REQUEST_TIMEOUT:
5471 return OC_STACK_TIMEOUT;
5472 case CA_DESTINATION_DISCONNECTED:
5473 return OC_STACK_COMM_ERROR;
5474 case CA_STATUS_FAILED:
5475 return OC_STACK_ERROR;
5476 case CA_NOT_SUPPORTED:
5477 return OC_STACK_NOTIMPL;
5479 return OC_STACK_ERROR;
5483 bool OCResultToSuccess(OCStackResult ocResult)
5488 case OC_STACK_RESOURCE_CREATED:
5489 case OC_STACK_RESOURCE_DELETED:
5490 case OC_STACK_CONTINUE:
5491 case OC_STACK_RESOURCE_CHANGED:
5492 case OC_STACK_SLOW_RESOURCE:
5499 OCStackResult OCSetProxyURI(const char *uri)
5501 return CAResultToOCResult(CASetProxyUri(uri));
5504 #if defined(RD_CLIENT) || defined(RD_SERVER)
5505 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5507 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5509 OCResource *resource = NULL;
5511 resource = findResource((OCResource *) handle);
5514 OIC_LOG(ERROR, TAG, "Resource not found");
5515 return OC_STACK_ERROR;
5518 resource->ins = ins;
5523 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5524 const OCClientResponse *response)
5526 // Validate input parameters
5527 VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5528 VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5530 char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5533 return OC_STACK_NO_MEMORY;
5535 strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5537 if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5539 OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5541 char rdPubUri[MAX_URI_LENGTH] = { 0 };
5542 snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5543 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5545 if (strcmp(rdPubUri, targetUri) == 0)
5547 // Update resource unique id in stack.
5550 if (response->payload)
5552 OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5553 OCRepPayload **links = NULL;
5554 size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5555 if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5556 &links, dimensions))
5559 for (; i < dimensions[0]; i++)
5562 if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5564 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5566 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5568 OCBindResourceInsToResource(handle, ins);
5577 else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5579 OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5581 uint8_t numResources = 0;
5582 OCGetNumberOfResources(&numResources);
5584 char *ins = strstr(targetUri, OC_RSRVD_INS);
5587 for (uint8_t i = 0; i < numResources; i++)
5589 OCResourceHandle resHandle = OCGetResourceHandle(i);
5592 OCBindResourceInsToResource(resHandle, 0);
5598 const char *token = "&";
5599 char *iterTokenPtr = NULL;
5600 char *start = strtok_r(targetUri, token, &iterTokenPtr);
5602 while (start != NULL)
5604 char *query = start;
5605 query = strstr(query, OC_RSRVD_INS);
5608 // Arduino's AVR-GCC doesn't support strtoll().
5610 int matchedItems = sscanf(query + 4, "%lld", &queryIns);
5612 if (0 == matchedItems)
5615 return OC_STACK_INVALID_QUERY;
5618 for (uint8_t i = 0; i < numResources; i++)
5620 OCResourceHandle resHandle = OCGetResourceHandle(i);
5624 OCGetResourceIns(resHandle, &resIns);
5625 if (queryIns && queryIns == resIns)
5627 OCBindResourceInsToResource(resHandle, 0);
5633 start = strtok_r(NULL, token, &iterTokenPtr);
5642 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t* ins)
5644 OCResource *resource = NULL;
5646 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5647 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5649 resource = findResource((OCResource *) handle);
5652 *ins = resource->ins;
5655 return OC_STACK_ERROR;
5657 #endif // RD_CLIENT || RD_SERVER
5659 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5663 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5667 OCResource *pointer = headResource;
5671 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5673 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5676 pointer = pointer->next;
5681 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5682 void* optionData, size_t optionDataLength)
5686 OIC_LOG (INFO, TAG, "Header options are NULL");
5687 return OC_STACK_INVALID_PARAM;
5692 OIC_LOG (INFO, TAG, "optionData are NULL");
5693 return OC_STACK_INVALID_PARAM;
5698 OIC_LOG (INFO, TAG, "numOptions is NULL");
5699 return OC_STACK_INVALID_PARAM;
5702 if (*numOptions >= MAX_HEADER_OPTIONS)
5704 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5705 return OC_STACK_NO_MEMORY;
5708 ocHdrOpt += *numOptions;
5709 ocHdrOpt->protocolID = OC_COAP_ID;
5710 ocHdrOpt->optionID = optionID;
5711 ocHdrOpt->optionLength =
5712 (optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH) ?
5713 (uint16_t)optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5714 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5720 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions,
5721 uint16_t optionID, void* optionData, size_t optionDataLength,
5722 uint16_t* receivedDataLength)
5724 if (!ocHdrOpt || !numOptions)
5726 OIC_LOG (INFO, TAG, "No options present");
5732 OIC_LOG (INFO, TAG, "optionData are NULL");
5733 return OC_STACK_INVALID_PARAM;
5736 if (!receivedDataLength)
5738 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5739 return OC_STACK_INVALID_PARAM;
5742 for (uint8_t i = 0; i < numOptions; i++)
5744 if (ocHdrOpt[i].optionID == optionID)
5746 if (optionDataLength >= ocHdrOpt->optionLength)
5748 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5749 *receivedDataLength = ocHdrOpt->optionLength;
5754 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5755 return OC_STACK_ERROR;
5762 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5764 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5765 if (g_adapterHandler)
5767 g_adapterHandler(adapter, enabled);
5771 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5773 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5774 if (g_connectionHandler)
5776 g_connectionHandler(info, isConnected);
5780 * If the client observes one or more resources over a reliable connection,
5781 * then the CoAP server (or intermediary in the role of the CoAP server)
5782 * MUST remove all entries associated with the client endpoint from the lists
5783 * of observers when the connection is either closed or times out.
5787 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5788 CopyEndpointToDevAddr(info, &devAddr);
5790 // remove observer list with remote device address.
5791 DeleteObserverUsingDevAddr(&devAddr);
5795 void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
5796 CAConnectionStateChangedCB connectionHandler)
5798 OIC_LOG(DEBUG, TAG, "OCSetNetworkMonitorHandler");
5799 g_adapterHandler = adapterHandler;
5800 g_connectionHandler = connectionHandler;
5803 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5806 OCStackResult ret = OC_STACK_ERROR;
5808 ret = GetDoxmDeviceID(&oicUuid);
5809 if (OC_STACK_OK == ret)
5811 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5815 OIC_LOG(ERROR, TAG, "Device ID Get error");
5820 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5823 OCStackResult ret = OC_STACK_ERROR;
5825 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5826 for (int i = 0; i < UUID_LENGTH; i++)
5828 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5830 ret = SetDoxmDeviceID(&oicUuid);
5834 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5836 bool isDeviceOwned = true;
5837 OCStackResult ret = OC_STACK_ERROR;
5839 ret = GetDoxmIsOwned(&isDeviceOwned);
5840 if (OC_STACK_OK == ret)
5842 *isOwned = isDeviceOwned;
5846 OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5851 OCStackResult OCGetLinkLocalZoneId(uint32_t ifindex, char **zoneId)
5853 return CAResultToOCResult(CAGetLinkLocalZoneId(ifindex, zoneId));