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 bool g_multicastServerStopped = false;
172 //-----------------------------------------------------------------------------
174 //-----------------------------------------------------------------------------
175 #define TAG "OIC_RI_STACK"
176 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
177 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
178 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
179 TAG, #arg " is NULL"); return (retVal); } }
180 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
181 TAG, #arg " is NULL"); return; } }
182 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
185 //TODO: we should allow the server to define this
186 #define MAX_OBSERVE_AGE (0x2FFFFUL)
188 #define MILLISECONDS_PER_SECOND (1000)
190 //-----------------------------------------------------------------------------
191 // Private internal function prototypes
192 //-----------------------------------------------------------------------------
195 * Generate handle of OCDoResource invocation for callback management.
197 * @return Generated OCDoResource handle.
199 static OCDoHandle GenerateInvocationHandle();
202 * Initialize resource data structures, variables, etc.
204 * @return ::OC_STACK_OK on success, some other value upon failure.
206 static OCStackResult initResources();
209 * Add a resource to the end of the linked list of resources.
211 * @param resource Resource to be added
213 static void insertResource(OCResource *resource);
216 * Find a resource in the linked list of resources.
218 * @param resource Resource to be found.
219 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
222 static OCResource *findResource(OCResource *resource);
225 * Insert a resource type into a resource's resource type linked list.
226 * If resource type already exists, it will not be inserted and the
227 * resourceType will be free'd.
228 * resourceType->next should be null to avoid memory leaks.
229 * Function returns silently for null args.
231 * @param resource Resource where resource type is to be inserted.
232 * @param resourceType Resource type to be inserted.
234 static void insertResourceType(OCResource *resource,
235 OCResourceType *resourceType);
238 * Get a resource type at the specified index within a resource.
240 * @param handle Handle of resource.
241 * @param index Index of resource type.
243 * @return Pointer to resource type if found, NULL otherwise.
245 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
249 * Insert a resource interface into a resource's resource interface linked list.
250 * If resource interface already exists, it will not be inserted and the
251 * resourceInterface will be free'd.
252 * resourceInterface->next should be null to avoid memory leaks.
254 * @param resource Resource where resource interface is to be inserted.
255 * @param resourceInterface Resource interface to be inserted.
257 static void insertResourceInterface(OCResource *resource,
258 OCResourceInterface *resourceInterface);
261 * Get a resource interface at the specified index within a resource.
263 * @param handle Handle of resource.
264 * @param index Index of resource interface.
266 * @return Pointer to resource interface if found, NULL otherwise.
268 static OCResourceInterface *findResourceInterfaceAtIndex(
269 OCResourceHandle handle, uint8_t index);
272 * Delete all of the dynamically allocated elements that were created for the resource type.
274 * @param resourceType Specified resource type.
276 static void deleteResourceType(OCResourceType *resourceType);
279 * Delete all of the dynamically allocated elements that were created for the resource interface.
281 * @param resourceInterface Specified resource interface.
283 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
286 * Delete all of the dynamically allocated elements that were created for the resource.
288 * @param resource Specified resource.
290 static void deleteResourceElements(OCResource *resource);
293 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
296 * @param handle Handle of resource to be deleted.
298 * @return ::OC_STACK_OK on success, some other value upon failure.
300 static OCStackResult deleteResource(OCResource *resource);
303 * Delete all of the resources in the resource list.
305 static void deleteAllResources();
308 * Increment resource sequence number. Handles rollover.
310 * @param resPtr Pointer to resource.
312 static void incrementSequenceNumber(OCResource * resPtr);
315 * Attempts to initialize every network interface that the CA Layer might have compiled in.
317 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
318 * return something other than @ref CA_STATUS_OK, then this function fails.
319 * @param transportType OCTransportAdapter value to select.
320 * @return ::CA_STATUS_OK on success, some other value upon failure.
322 static CAResult_t OCSelectNetwork(OCTransportAdapter transportType);
325 * Convert CAResponseResult_t to OCStackResult.
327 * @param caCode CAResponseResult_t code.
328 * @return ::OC_STACK_OK on success, some other value upon failure.
330 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
333 * Convert OCTransportFlags_t to CATransportModifiers_t.
335 * @param ocConType OCTransportFlags_t input.
336 * @return CATransportFlags
338 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
341 * Convert CATransportFlags_t to OCTransportModifiers_t.
343 * @param caConType CATransportFlags_t input.
344 * @return OCTransportFlags
346 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
349 * Handle response from presence request.
351 * @param endPoint CA remote endpoint.
352 * @param responseInfo CA response info.
353 * @return ::OC_STACK_OK on success, some other value upon failure.
355 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
356 const CAResponseInfo_t *responseInfo);
359 * This function will be called back by CA layer when a response is received.
361 * @param endPoint CA remote endpoint.
362 * @param responseInfo CA response info.
364 static void HandleCAResponses(const CAEndpoint_t* endPoint,
365 const CAResponseInfo_t* responseInfo);
368 * This function will be called back by CA layer when a request is received.
370 * @param endPoint CA remote endpoint.
371 * @param requestInfo CA request info.
373 static void HandleCARequests(const CAEndpoint_t* endPoint,
374 const CARequestInfo_t* requestInfo);
377 * Extract query from a URI.
379 * @param uri Full URI with query.
380 * @param query Pointer to string that will contain query.
381 * @param newURI Pointer to string that will contain URI.
382 * @return ::OC_STACK_OK on success, some other value upon failure.
384 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
387 * Finds a resource type in an OCResourceType link-list.
389 * @param resourceTypeList The link-list to be searched through.
390 * @param resourceTypeName The key to search for.
392 * @return Resource type that matches the key (ie. resourceTypeName) or
393 * NULL if there is either an invalid parameter or this function was unable to find the key.
395 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
396 const char * resourceTypeName);
399 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
400 * TTL will be set to maxAge.
402 * @param cbNode Callback Node for which presence ttl is to be reset.
403 * @param maxAge New value of ttl in seconds.
405 * @return ::OC_STACK_OK on success, some other value upon failure.
407 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
410 * Ensure the accept header option is set appropriatly before sending the requests and routing
411 * header option is updated with destination.
413 * @param object CA remote endpoint.
414 * @param requestInfo CA request info.
416 * @return ::OC_STACK_OK on success, some other value upon failure.
418 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
421 * default adapter state change callback method
423 * @param adapter CA network adapter type.
424 * @param enabled current adapter state.
426 static void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled);
429 * default connection state change callback method
431 * @param info CAEndpoint which has address, port and etc.
432 * @param isConnected current connection state.
434 static void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected);
437 * Register network monitoring callback.
438 * Network status changes are delivered these callback.
439 * @param adapterHandler Adapter state monitoring callback.
440 * @param connectionHandler Connection state monitoring callback.
442 static void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
443 CAConnectionStateChangedCB connectionHandler);
445 * Map zoneId to endpoint address which scope is ipv6 link-local.
446 * @param payload Discovery payload which has Endpoint information.
447 * @param ifindex index which indicate network interface.
450 static OCStackResult OCMapZoneIdToLinkLocalEndpoint(OCDiscoveryPayload *payload, uint32_t ifindex);
454 * Initialize the stack.
455 * Caller of this function must serialize calls to this function and the stop counterpart.
456 * @param mode Mode of operation.
457 * @param serverFlags The server flag used when the mode of operation is a server mode.
458 * @param clientFlags The client flag used when the mode of operation is a client mode.
459 * @param transportType The transport type.
461 * @return ::OC_STACK_OK on success, some other value upon failure.
463 static OCStackResult OCInitializeInternal(OCMode mode, OCTransportFlags serverFlags,
464 OCTransportFlags clientFlags, OCTransportAdapter transportType);
467 * DeInitialize the stack.
468 * Caller of this function must serialize calls to this function and the init counterpart.
470 * @return ::OC_STACK_OK on success, some other value upon failure.
472 static OCStackResult OCDeInitializeInternal();
474 //-----------------------------------------------------------------------------
475 // Internal functions
476 //-----------------------------------------------------------------------------
477 static void OCEnterInitializer()
481 int32_t initCount = oc_atomic_increment(&g_ocStackStartStopThreadCount);
482 assert(initCount > 0);
487 OC_VERIFY(oc_atomic_decrement(&g_ocStackStartStopThreadCount) >= 0);
488 #if !defined(ARDUINO)
489 // Yield execution to the thread that is holding the lock.
492 assert(!"Not expecting initCount to go above 1 on Arduino");
498 static void OCLeaveInitializer()
500 OC_VERIFY(oc_atomic_decrement(&g_ocStackStartStopThreadCount) >= 0);
503 bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
505 if (!options || 0 == numOptions)
507 OIC_LOG (INFO, TAG, "No options present");
511 for (uint8_t i = 0; i < numOptions; i++)
513 if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
515 OIC_LOG(DEBUG, TAG, "Proxy URI is present");
522 uint32_t GetTicks(uint32_t milliSeconds)
527 // Guard against overflow of uint32_t
528 if (milliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
529 COAP_TICKS_PER_SECOND)
531 return now + (milliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
539 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
541 VERIFY_NON_NULL_NR(in, FATAL);
542 VERIFY_NON_NULL_NR(out, FATAL);
544 out->adapter = (OCTransportAdapter)in->adapter;
545 out->flags = CAToOCTransportFlags(in->flags);
546 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
547 out->port = in->port;
548 out->ifindex = in->ifindex;
549 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
550 /* This assert is to prevent accidental mismatch between address size macros defined in
551 * RI and CA and cause crash here. */
552 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
553 "Address size mismatch between RI and CA");
554 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
558 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
560 VERIFY_NON_NULL_NR(in, FATAL);
561 VERIFY_NON_NULL_NR(out, FATAL);
563 out->adapter = (CATransportAdapter_t)in->adapter;
564 out->flags = OCToCATransportFlags(in->flags);
565 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
566 OICStrcpy(out->remoteId, sizeof(out->remoteId), in->remoteId);
567 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
568 /* This assert is to prevent accidental mismatch between address size macros defined in
569 * RI and CA and cause crash here. */
570 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
571 "Address size mismatch between RI and CA");
572 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
574 out->port = in->port;
575 out->ifindex = in->ifindex;
578 void FixUpClientResponse(OCClientResponse *cr)
580 VERIFY_NON_NULL_NR(cr, FATAL);
582 cr->addr = &cr->devAddr;
583 cr->connType = (OCConnectivityType)
584 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
587 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
589 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
590 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
592 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
593 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
594 if (OC_STACK_OK != rmResult)
596 OIC_LOG(ERROR, TAG, "Add destination option failed");
601 uint16_t acceptVersion = OC_SPEC_VERSION_VALUE;
602 // From OCF onwards, check settings of version option.
603 if (DEFAULT_ACCEPT_VERSION_VALUE <= acceptVersion)
605 if (requestInfo->info.numOptions > 0 && requestInfo->info.options)
607 for (uint8_t i = 0; i < requestInfo->info.numOptions; i++)
609 if (COAP_OPTION_ACCEPT_VERSION == requestInfo->info.options[i].protocolID)
611 acceptVersion = requestInfo->info.options[i].optionData[0];
614 else if (COAP_OPTION_CONTENT_VERSION == requestInfo->info.options[i].protocolID)
616 acceptVersion = requestInfo->info.options[i].optionData[0];
623 if (DEFAULT_CONTENT_VERSION_VALUE <= acceptVersion)
625 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_VND_OCF_CBOR;
626 requestInfo->info.acceptVersion = acceptVersion;
630 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
633 CAResult_t result = CASendRequest(object, requestInfo);
634 if(CA_STATUS_OK != result)
636 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
637 return CAResultToOCResult(result);
641 //-----------------------------------------------------------------------------
642 // Internal API function
643 //-----------------------------------------------------------------------------
645 // This internal function is called to update the stack with the status of
646 // observers and communication failures
647 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
649 OCStackResult result = OC_STACK_ERROR;
650 ResourceObserver * observer = NULL;
651 OCEntityHandlerRequest ehRequest = {0};
655 case OC_OBSERVER_NOT_INTERESTED:
656 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
657 observer = GetObserverUsingToken(token, tokenLength);
660 result = FormOCEntityHandlerRequest(&ehRequest,
661 (OCRequestHandle)NULL,
664 (OCResourceHandle)NULL,
665 NULL, PAYLOAD_TYPE_REPRESENTATION,
667 OC_OBSERVE_DEREGISTER,
670 if (result != OC_STACK_OK)
675 if (observer->resource && observer->resource->entityHandler)
677 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
678 observer->resource->entityHandlerCallbackParam);
682 result = DeleteObserverUsingToken(token, tokenLength);
683 if (result == OC_STACK_OK)
685 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
689 result = OC_STACK_OK;
690 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
694 case OC_OBSERVER_STILL_INTERESTED:
695 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
696 observer = GetObserverUsingToken(token, tokenLength);
699 observer->forceHighQos = 0;
700 observer->failedCommCount = 0;
701 result = OC_STACK_OK;
705 result = OC_STACK_OBSERVER_NOT_FOUND;
709 case OC_OBSERVER_FAILED_COMM:
710 OIC_LOG(DEBUG, TAG, "observer is unreachable");
711 observer = GetObserverUsingToken (token, tokenLength);
714 if (observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
716 result = FormOCEntityHandlerRequest(&ehRequest,
717 (OCRequestHandle)NULL,
720 (OCResourceHandle)NULL,
721 NULL, PAYLOAD_TYPE_REPRESENTATION,
723 OC_OBSERVE_DEREGISTER,
726 if (result != OC_STACK_OK)
728 return OC_STACK_ERROR;
731 if (observer->resource && observer->resource->entityHandler)
733 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
734 observer->resource->entityHandlerCallbackParam);
737 result = DeleteObserverUsingToken(token, tokenLength);
738 if (result == OC_STACK_OK)
740 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
744 result = OC_STACK_OK;
745 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
750 observer->failedCommCount++;
751 observer->forceHighQos = 1;
752 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",
753 observer->failedCommCount);
754 result = OC_STACK_CONTINUE;
759 OIC_LOG(ERROR, TAG, "Unknown status");
760 result = OC_STACK_ERROR;
766 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
768 OCStackResult ret = OC_STACK_ERROR;
772 ret = OC_STACK_RESOURCE_CREATED;
775 ret = OC_STACK_RESOURCE_DELETED;
778 ret = OC_STACK_RESOURCE_CHANGED;
785 ret = OC_STACK_INVALID_QUERY;
787 case CA_UNAUTHORIZED_REQ:
788 ret = OC_STACK_UNAUTHORIZED_REQ;
791 ret = OC_STACK_INVALID_OPTION;
794 ret = OC_STACK_NO_RESOURCE;
796 case CA_RETRANSMIT_TIMEOUT:
797 ret = OC_STACK_GATEWAY_TIMEOUT;
799 case CA_REQUEST_ENTITY_TOO_LARGE:
800 ret = OC_STACK_TOO_LARGE_REQ;
802 case CA_NOT_ACCEPTABLE:
803 ret = OC_STACK_NOT_ACCEPTABLE;
805 case CA_FORBIDDEN_REQ:
806 ret = OC_STACK_FORBIDDEN_REQ;
808 case CA_INTERNAL_SERVER_ERROR:
809 ret = OC_STACK_INTERNAL_SERVER_ERROR;
817 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
819 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
828 // This Response Code is like HTTP 204 "No Content" but only used in
829 // response to POST and PUT requests.
833 // This Response Code is like HTTP 200 "OK" but only used in response to
838 // This should not happen but,
839 // give it a value just in case but output an error
841 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
845 case OC_STACK_RESOURCE_CREATED:
848 case OC_STACK_RESOURCE_DELETED:
851 case OC_STACK_RESOURCE_CHANGED:
854 case OC_STACK_INVALID_QUERY:
857 case OC_STACK_INVALID_OPTION:
860 case OC_STACK_NO_RESOURCE:
863 case OC_STACK_COMM_ERROR:
864 ret = CA_RETRANSMIT_TIMEOUT;
866 case OC_STACK_GATEWAY_TIMEOUT:
867 ret = CA_RETRANSMIT_TIMEOUT;
869 case OC_STACK_NOT_ACCEPTABLE:
870 ret = CA_NOT_ACCEPTABLE;
872 case OC_STACK_UNAUTHORIZED_REQ:
873 ret = CA_UNAUTHORIZED_REQ;
875 case OC_STACK_FORBIDDEN_REQ:
876 ret = CA_FORBIDDEN_REQ;
878 case OC_STACK_INTERNAL_SERVER_ERROR:
879 ret = CA_INTERNAL_SERVER_ERROR;
881 case OC_STACK_BAD_ENDPOINT:
889 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
891 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
893 // supply default behavior.
894 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
896 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
898 if ((caFlags & OC_MASK_SCOPE) == 0)
900 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
905 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
907 return (OCTransportFlags)caFlags;
910 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
912 uint32_t lowerBound = 0;
913 uint32_t higherBound = 0;
915 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
917 return OC_STACK_INVALID_PARAM;
920 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
922 cbNode->presence->TTL = maxAgeSeconds;
924 for (int index = 0; index < PresenceTimeOutSize; index++)
926 // Guard against overflow
927 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
930 lowerBound = GetTicks((PresenceTimeOut[index] *
931 cbNode->presence->TTL *
932 MILLISECONDS_PER_SECOND)/100);
936 lowerBound = GetTicks(UINT32_MAX);
939 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
942 higherBound = GetTicks((PresenceTimeOut[index + 1] *
943 cbNode->presence->TTL *
944 MILLISECONDS_PER_SECOND)/100);
948 higherBound = GetTicks(UINT32_MAX);
951 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
953 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
954 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
955 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
958 cbNode->presence->TTLlevel = 0;
960 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
964 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
966 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
968 return OC_RSRVD_TRIGGER_CREATE;
970 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
972 return OC_RSRVD_TRIGGER_CHANGE;
976 return OC_RSRVD_TRIGGER_DELETE;
980 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
984 return OC_PRESENCE_TRIGGER_CREATE;
986 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
988 return OC_PRESENCE_TRIGGER_CREATE;
990 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
992 return OC_PRESENCE_TRIGGER_CHANGE;
996 return OC_PRESENCE_TRIGGER_DELETE;
1000 OCStackResult OCEncodeAddressForRFC6874(char *outputAddress,
1002 const char *inputAddress)
1004 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
1005 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
1007 size_t inputLength = strnlen(inputAddress, outputSize);
1009 // inputSize includes the null terminator
1010 size_t inputSize = inputLength + 1;
1012 if (inputSize > outputSize)
1014 OIC_LOG_V(ERROR, TAG,
1015 "OCEncodeAddressForRFC6874 failed: "
1016 "outputSize (%zu) < inputSize (%zu)",
1017 outputSize, inputSize);
1019 return OC_STACK_ERROR;
1022 char* percentChar = strchr(inputAddress, '%');
1024 // If there is no '%' character, then no change is required to the string.
1025 if (NULL == percentChar)
1027 OICStrcpy(outputAddress, outputSize, inputAddress);
1031 const char* addressPart = &inputAddress[0];
1032 const char* scopeIdPart = percentChar + 1;
1034 // Sanity check to make sure this string doesn't have more '%' characters
1035 if (NULL != strchr(scopeIdPart, '%'))
1037 return OC_STACK_ERROR;
1040 // If no string follows the first '%', then the input was invalid.
1041 if (scopeIdPart[0] == '\0')
1043 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
1044 return OC_STACK_ERROR;
1047 // Check to see if the string is already encoded
1048 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
1050 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Input string is already encoded");
1051 return OC_STACK_ERROR;
1054 // Fail if we don't have room for encoded string's two additional chars
1055 if (outputSize < (inputSize + 2))
1057 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: encoded output will not fit!");
1058 return OC_STACK_ERROR;
1061 // Restore the null terminator with an escaped '%' character, per RFC 6874
1062 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
1063 strcat(outputAddress, "%25");
1064 strcat(outputAddress, scopeIdPart);
1069 OCStackResult OCDecodeAddressForRFC6874(char *outputAddress,
1071 const char *inputAddress,
1074 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
1075 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
1079 end = inputAddress + strlen(inputAddress);
1081 size_t inputLength = end - inputAddress;
1083 const char *percent = strchr(inputAddress, '%');
1084 if (!percent || (percent > end))
1086 OICStrcpyPartial(outputAddress, outputSize, inputAddress, inputLength);
1090 if (percent[1] != '2' || percent[2] != '5')
1092 return OC_STACK_INVALID_URI;
1095 size_t addrlen = percent - inputAddress + 1;
1096 OICStrcpyPartial(outputAddress, outputSize, inputAddress, addrlen);
1097 OICStrcpyPartial(outputAddress + addrlen, outputSize - addrlen,
1098 percent + 3, end - percent - 3);
1105 * The cononical presence allows constructed URIs to be string compared.
1107 * requestUri must be a char array of size CA_MAX_URI_LENGTH
1109 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
1110 char *presenceUri, bool isMulticast)
1112 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
1113 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1117 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1118 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1121 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1122 if (ep->adapter == CA_ADAPTER_IP)
1124 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1126 if ('\0' == ep->addr[0]) // multicast
1128 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1132 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1134 OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1135 sizeof(addressEncoded),
1138 if (OC_STACK_OK != result)
1143 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1144 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1149 if ('\0' == ep->addr[0]) // multicast
1151 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1152 ep->port = OC_MULTICAST_PORT;
1154 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1155 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1159 // might work for other adapters (untested, but better than nothing)
1160 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1161 OC_RSRVD_PRESENCE_URI);
1165 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1166 const CAResponseInfo_t *responseInfo)
1168 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1169 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1171 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1172 ClientCB * cbNode = NULL;
1173 char *resourceTypeName = NULL;
1174 OCClientResponse *response = NULL;
1175 OCStackResult result = OC_STACK_ERROR;
1176 uint32_t maxAge = 0;
1178 char presenceUri[CA_MAX_URI_LENGTH];
1180 int presenceSubscribe = 0;
1181 int multicastPresenceSubscribe = 0;
1183 if (responseInfo->result != CA_CONTENT)
1185 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1186 return OC_STACK_ERROR;
1189 response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1192 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1193 return OC_STACK_ERROR;
1195 response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1197 response->payload = NULL;
1198 response->result = OC_STACK_OK;
1200 CopyEndpointToDevAddr(endpoint, &response->devAddr);
1201 FixUpClientResponse(response);
1203 if (responseInfo->info.payload)
1205 result = OCParsePayload(&response->payload,
1206 PAYLOAD_TYPE_PRESENCE,
1207 responseInfo->info.payload,
1208 responseInfo->info.payloadSize);
1210 if(result != OC_STACK_OK)
1212 OIC_LOG(ERROR, TAG, "Presence parse failed");
1215 if(!response->payload || response->payload->type != PAYLOAD_TYPE_PRESENCE)
1217 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1218 result = OC_STACK_ERROR;
1221 response->sequenceNumber = ((OCPresencePayload*)response->payload)->sequenceNumber;
1222 resourceTypeName = ((OCPresencePayload*)response->payload)->resourceType;
1223 maxAge = ((OCPresencePayload*)response->payload)->maxAge;
1226 // check for unicast presence
1227 uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1228 responseInfo->isMulticast);
1229 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1231 result = OC_STACK_INVALID_URI;
1234 OIC_LOG(INFO, TAG, "check for unicast presence");
1235 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1238 presenceSubscribe = 1;
1242 // check for multicast presence
1243 OIC_LOG(INFO, TAG, "check for multicast presence");
1244 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1247 multicastPresenceSubscribe = 1;
1251 if (!presenceSubscribe && !multicastPresenceSubscribe)
1253 OIC_LOG(INFO, TAG, "Received a presence notification, "
1254 "but need to register presence callback, ignoring");
1258 if (presenceSubscribe)
1260 if(cbNode->sequenceNumber == response->sequenceNumber)
1262 OIC_LOG(INFO, TAG, "No presence change");
1263 ResetPresenceTTL(cbNode, maxAge);
1264 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1270 OIC_LOG(INFO, TAG, "Stopping presence");
1271 response->result = OC_STACK_PRESENCE_STOPPED;
1272 if(cbNode->presence)
1274 OICFree(cbNode->presence->timeOut);
1275 OICFree(cbNode->presence);
1276 cbNode->presence = NULL;
1281 if(!cbNode->presence)
1283 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1285 if(!(cbNode->presence))
1287 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1288 result = OC_STACK_NO_MEMORY;
1292 VERIFY_NON_NULL_V(cbNode->presence);
1293 cbNode->presence->timeOut = NULL;
1294 cbNode->presence->timeOut = (uint32_t *)
1295 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1296 if(!(cbNode->presence->timeOut)){
1298 "Could not allocate memory for cbNode->presence->timeOut");
1299 OICFree(cbNode->presence);
1300 result = OC_STACK_NO_MEMORY;
1305 ResetPresenceTTL(cbNode, maxAge);
1307 cbNode->sequenceNumber = response->sequenceNumber;
1312 // This is the multicast case
1313 OIC_LOG(INFO, TAG, "this is the multicast presence");
1316 OIC_LOG(INFO, TAG, "Stopping presence");
1317 response->result = OC_STACK_PRESENCE_STOPPED;
1321 // Ensure that a filter is actually applied.
1322 if (resourceTypeName && cbNode->filterResourceType)
1324 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1325 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1331 OIC_LOG(INFO, TAG, "Callback for presence");
1333 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response);
1335 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1337 FindAndDeleteClientCB(cbNode);
1341 OCPayloadDestroy(response->payload);
1346 OCStackResult HandleBatchResponse(char *requestUri, OCRepPayload **payload)
1348 if (requestUri && *payload)
1350 char *interfaceName = NULL;
1351 char *rtTypeName = NULL;
1352 char *uriQuery = NULL;
1353 char *uriWithoutQuery = NULL;
1354 if (OC_STACK_OK == getQueryFromUri(requestUri, &uriQuery, &uriWithoutQuery))
1356 if (OC_STACK_OK == ExtractFiltersFromQuery(uriQuery, &interfaceName, &rtTypeName))
1358 if (0 == strcmp(OC_RSRVD_INTERFACE_BATCH, interfaceName))
1360 char *uri = (*payload)->uri;
1361 if (uri && 0 != strcmp(uriWithoutQuery, uri))
1363 OCRepPayload *newPayload = OCRepPayloadCreate();
1366 OCRepPayloadSetUri(newPayload, uri);
1367 newPayload->next = *payload;
1368 *payload = newPayload;
1374 OICFree(interfaceName);
1375 OICFree(rtTypeName);
1377 OICFree(uriWithoutQuery);
1380 return OC_STACK_INVALID_PARAM;
1383 #ifndef WITH_ARDUINO
1384 OCStackResult OCMapZoneIdToLinkLocalEndpoint(OCDiscoveryPayload *payload, uint32_t ifindex)
1388 OIC_LOG(ERROR, TAG, "Given argument payload is NULL!!");
1389 return OC_STACK_INVALID_PARAM;
1392 OCResourcePayload *curRes = payload->resources;
1394 while (curRes != NULL)
1396 OCEndpointPayload* eps = curRes->eps;
1400 if (eps->family & OC_IP_USE_V6)
1402 CATransportFlags_t scopeLevel;
1403 if (CA_STATUS_OK == CAGetIpv6AddrScope(eps->addr, &scopeLevel))
1405 if (CA_SCOPE_LINK == scopeLevel)
1407 char *zoneId = NULL;
1408 if (OC_STACK_OK == OCGetLinkLocalZoneId(ifindex, &zoneId))
1410 assert(zoneId != NULL);
1411 // put zoneId to end of addr
1412 OICStrcat(eps->addr, OC_MAX_ADDR_STR_SIZE, "%");
1413 OICStrcat(eps->addr, OC_MAX_ADDR_STR_SIZE, zoneId);
1418 OIC_LOG(ERROR, TAG, "failed at parse zone-id for link-local address");
1419 return OC_STACK_ERROR;
1425 OIC_LOG(ERROR, TAG, "failed at parse ipv6 scope level");
1426 return OC_STACK_ERROR;
1431 curRes = curRes->next;
1438 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1440 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1442 if(responseInfo->info.resourceUri &&
1443 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1445 HandlePresenceResponse(endPoint, responseInfo);
1449 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1450 responseInfo->info.tokenLength, NULL, NULL);
1452 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1453 responseInfo->info.tokenLength);
1457 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1459 // check obs header option
1460 bool obsHeaderOpt = false;
1461 CAHeaderOption_t *options = responseInfo->info.options;
1462 for (uint8_t i = 0; i< responseInfo->info.numOptions; i++)
1464 if (options && (options[i].optionID == COAP_OPTION_OBSERVE))
1466 obsHeaderOpt = true;
1471 if(responseInfo->result == CA_EMPTY)
1473 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1474 // We do not have a case for the client to receive a RESET
1475 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1477 //This is the case of receiving an ACK on a request to a slow resource!
1478 OIC_LOG(INFO, TAG, "This is a pure ACK");
1479 //TODO: should we inform the client
1480 // app that at least the request was received at the server?
1483 else if (CA_RETRANSMIT_TIMEOUT == responseInfo->result
1484 || CA_NOT_ACCEPTABLE == responseInfo->result)
1486 if (CA_RETRANSMIT_TIMEOUT == responseInfo->result)
1488 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1489 OIC_LOG(INFO, TAG, "Calling into application address space");
1493 OIC_LOG(INFO, TAG, "Server doesn't support the requested payload format");
1494 OIC_LOG(INFO, TAG, "Calling into application address space");
1497 OCClientResponse *response = NULL;
1499 response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1502 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1506 response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1507 CopyEndpointToDevAddr(endPoint, &response->devAddr);
1508 FixUpClientResponse(response);
1509 response->resourceUri = responseInfo->info.resourceUri;
1510 memcpy(response->identity.id, responseInfo->info.identity.id,
1511 sizeof (response->identity.id));
1512 response->identity.id_length = responseInfo->info.identity.id_length;
1514 response->result = CAResponseToOCStackResult(responseInfo->result);
1515 cbNode->callBack(cbNode->context,
1516 cbNode->handle, response);
1517 FindAndDeleteClientCB(cbNode);
1520 else if ((cbNode->method == OC_REST_OBSERVE || cbNode->method == OC_REST_OBSERVE_ALL)
1521 && (responseInfo->result == CA_CONTENT) && !obsHeaderOpt)
1523 OCClientResponse *response = NULL;
1525 response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1528 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1532 response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1533 CopyEndpointToDevAddr(endPoint, &response->devAddr);
1534 FixUpClientResponse(response);
1535 response->resourceUri = responseInfo->info.resourceUri;
1536 memcpy(response->identity.id, responseInfo->info.identity.id,
1537 sizeof (response->identity.id));
1538 response->identity.id_length = responseInfo->info.identity.id_length;
1539 response->result = OC_STACK_OK;
1541 OIC_LOG(DEBUG, TAG, "This is response of observer cancel or observer request fail");
1543 cbNode->callBack(cbNode->context,
1546 FindAndDeleteClientCB(cbNode);
1551 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1552 OIC_LOG(INFO, TAG, "Calling into application address space");
1554 OCClientResponse *response = NULL;
1555 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1557 response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1560 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1564 response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1565 response->sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1566 CopyEndpointToDevAddr(endPoint, &response->devAddr);
1567 FixUpClientResponse(response);
1568 response->resourceUri = responseInfo->info.resourceUri;
1569 memcpy(response->identity.id, responseInfo->info.identity.id,
1570 sizeof (response->identity.id));
1571 response->identity.id_length = responseInfo->info.identity.id_length;
1573 response->result = CAResponseToOCStackResult(responseInfo->result);
1575 if(responseInfo->info.payload &&
1576 responseInfo->info.payloadSize)
1578 // check the security resource
1579 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1581 type = PAYLOAD_TYPE_SECURITY;
1583 else if (cbNode->method == OC_REST_DISCOVER)
1585 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1586 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1588 type = PAYLOAD_TYPE_DISCOVERY;
1591 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1593 type = PAYLOAD_TYPE_DISCOVERY;
1596 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1598 type = PAYLOAD_TYPE_REPRESENTATION;
1600 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1602 type = PAYLOAD_TYPE_REPRESENTATION;
1604 else if (strcmp(cbNode->requestUri, OC_RSRVD_INTROSPECTION_URI) == 0)
1606 type = PAYLOAD_TYPE_REPRESENTATION;
1608 else if (strcmp(cbNode->requestUri, OC_RSRVD_INTROSPECTION_PAYLOAD_URI) == 0)
1610 type = PAYLOAD_TYPE_REPRESENTATION;
1612 #ifdef ROUTING_GATEWAY
1613 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1615 type = PAYLOAD_TYPE_REPRESENTATION;
1618 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1620 type = PAYLOAD_TYPE_REPRESENTATION;
1623 else if (strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1625 type = PAYLOAD_TYPE_REPRESENTATION;
1630 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1631 cbNode->method, cbNode->requestUri);
1635 else if (cbNode->method == OC_REST_GET ||
1636 cbNode->method == OC_REST_PUT ||
1637 cbNode->method == OC_REST_POST ||
1638 cbNode->method == OC_REST_OBSERVE ||
1639 cbNode->method == OC_REST_OBSERVE_ALL ||
1640 cbNode->method == OC_REST_DELETE)
1642 if (cbNode->requestUri)
1644 if (0 == strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri))
1646 type = PAYLOAD_TYPE_REPRESENTATION;
1648 else if (0 == strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri))
1650 type = PAYLOAD_TYPE_REPRESENTATION;
1652 if (type == PAYLOAD_TYPE_INVALID)
1654 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1655 cbNode->method, cbNode->requestUri);
1656 type = PAYLOAD_TYPE_REPRESENTATION;
1661 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1662 type = PAYLOAD_TYPE_REPRESENTATION;
1667 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1668 cbNode->method, cbNode->requestUri);
1673 // In case of error, still want application to receive the error message.
1674 if (OCResultToSuccess(response->result) || PAYLOAD_TYPE_REPRESENTATION == type)
1676 if (OC_STACK_OK != OCParsePayload(&response->payload,
1678 responseInfo->info.payload,
1679 responseInfo->info.payloadSize))
1681 OIC_LOG(ERROR, TAG, "Error converting payload");
1682 OCPayloadDestroy(response->payload);
1686 // Check endpoints has link-local ipv6 address.
1687 // if there is, map zone-id which parsed from ifindex
1688 #ifndef WITH_ARDUINO
1689 if (PAYLOAD_TYPE_DISCOVERY == response->payload->type)
1691 OCDiscoveryPayload *disPayload = (OCDiscoveryPayload*)(response->payload);
1693 OCMapZoneIdToLinkLocalEndpoint(disPayload, response->devAddr.ifindex))
1695 OIC_LOG(ERROR, TAG, "failed at map zone-id for link-local address");
1696 OCPayloadDestroy(response->payload);
1704 response->resourceUri = OICStrdup(cbNode->requestUri);
1708 response->numRcvdVendorSpecificHeaderOptions = 0;
1709 if((responseInfo->info.numOptions > 0) && (responseInfo->info.options != NULL))
1712 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1713 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1716 uint32_t observationOption;
1717 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1718 for (observationOption=0, i=0;
1719 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1723 (observationOption << 8) | optionData[i];
1725 response->sequenceNumber = observationOption;
1726 response->numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1731 response->numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1734 if(response->numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1736 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1737 OCPayloadDestroy(response->payload);
1742 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1744 memcpy (&(response->rcvdVendorSpecificHeaderOptions[i-start]),
1745 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1749 if (cbNode->method == OC_REST_OBSERVE &&
1750 response->sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1751 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1752 response->sequenceNumber <= cbNode->sequenceNumber)
1754 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1755 response->sequenceNumber);
1760 if (cbNode->requestUri)
1762 // if request uri is '/oic/rd', update ins value of resource.
1763 char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
1766 OCUpdateResourceInsWithResponse(cbNode->requestUri, response);
1770 // set remoteID(device ID) into OCClientResponse callback parameter
1771 if (OC_REST_DISCOVER == cbNode->method && PAYLOAD_TYPE_DISCOVERY == type)
1773 OCDiscoveryPayload *payload = (OCDiscoveryPayload*) response->payload;
1774 // Payload can be empty in case of error message.
1775 if (payload && payload->sid)
1777 OICStrcpy(response->devAddr.remoteId, sizeof(response->devAddr.remoteId),
1779 OIC_LOG_V(INFO, TAG, "Device ID of response : %s",
1780 response->devAddr.remoteId);
1782 #if defined(TCP_ADAPTER) && defined(WITH_CLOUD)
1783 CAConnectUserPref_t connPrefer = CA_USER_PREF_CLOUD;
1784 CAResult_t ret = CAUtilCMGetConnectionUserConfig(&connPrefer);
1785 if (ret == CA_STATUS_OK && connPrefer != CA_USER_PREF_CLOUD)
1787 OCCMDiscoveryResource(response);
1792 if (response->payload && response->payload->type == PAYLOAD_TYPE_REPRESENTATION)
1794 HandleBatchResponse(cbNode->requestUri, (OCRepPayload **)&response->payload);
1797 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1800 cbNode->sequenceNumber = response->sequenceNumber;
1802 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1804 FindAndDeleteClientCB(cbNode);
1808 // To keep discovery callbacks active.
1809 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1810 MILLISECONDS_PER_SECOND);
1814 //Need to send ACK when the response is CON
1815 if(responseInfo->info.type == CA_MSG_CONFIRM)
1817 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1818 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1821 OCPayloadDestroy(response->payload);
1829 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1830 if(responseInfo->result == CA_EMPTY)
1832 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1833 if(responseInfo->info.type == CA_MSG_RESET)
1835 OIC_LOG(INFO, TAG, "This is a RESET");
1836 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1837 OC_OBSERVER_NOT_INTERESTED);
1839 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1841 OIC_LOG(INFO, TAG, "This is a pure ACK");
1842 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1843 OC_OBSERVER_STILL_INTERESTED);
1846 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1848 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1849 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1850 OC_OBSERVER_FAILED_COMM);
1855 if(!cbNode && !observer)
1857 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1858 || myStackMode == OC_GATEWAY)
1860 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1861 if(responseInfo->result == CA_EMPTY)
1863 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1867 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1868 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1869 CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1873 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1874 || myStackMode == OC_GATEWAY)
1876 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1877 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1879 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1880 responseInfo->info.messageId);
1882 if (responseInfo->info.type == CA_MSG_RESET)
1884 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1885 responseInfo->info.messageId);
1893 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1895 VERIFY_NON_NULL_NR(endPoint, FATAL);
1896 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1898 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1899 OIC_TRACE_BEGIN(%s:HandleCAResponses, TAG);
1900 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1901 #ifdef ROUTING_GATEWAY
1902 bool needRIHandling = false;
1904 * Routing manager is going to update either of endpoint or response or both.
1905 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1906 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1909 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1911 if(ret != OC_STACK_OK || !needRIHandling)
1913 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1920 * Put source in sender endpoint so that the next packet from application can be routed to
1921 * proper destination and remove "RM" coap header option before passing request / response to
1922 * RI as this option will make no sense to either RI or application.
1924 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1925 (uint8_t *) &(responseInfo->info.numOptions),
1926 (CAEndpoint_t *) endPoint);
1929 OCHandleResponse(endPoint, responseInfo);
1931 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1936 * This function handles error response from CA
1937 * code shall be added to handle the errors
1939 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1941 VERIFY_NON_NULL_NR(endPoint, FATAL);
1942 VERIFY_NON_NULL_NR(errorInfo, FATAL);
1944 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1945 OIC_TRACE_BEGIN(%s:HandleCAErrorResponse, TAG);
1947 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1948 errorInfo->info.tokenLength, NULL, NULL);
1951 OCClientResponse *response = NULL;
1953 response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1956 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1960 response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1961 CopyEndpointToDevAddr(endPoint, &response->devAddr);
1962 FixUpClientResponse(response);
1963 response->resourceUri = errorInfo->info.resourceUri;
1964 memcpy(response->identity.id, errorInfo->info.identity.id,
1965 sizeof (response->identity.id));
1966 response->identity.id_length = errorInfo->info.identity.id_length;
1967 response->result = CAResultToOCResult(errorInfo->result);
1969 cbNode->callBack(cbNode->context, cbNode->handle, response);
1973 ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1974 errorInfo->info.tokenLength);
1977 OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1978 OCStackResult result = CAResultToOCResult(errorInfo->result);
1979 if (OC_STACK_COMM_ERROR == result)
1981 OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1982 OC_OBSERVER_FAILED_COMM);
1986 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1991 * This function sends out Direct Stack Responses. These are responses that are not coming
1992 * from the application entity handler. These responses have no payload and are usually ACKs,
1993 * RESETs or some error conditions that were caught by the stack.
1995 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1996 const CAResponseResult_t responseResult, const CAMessageType_t type,
1997 const uint8_t numOptions, const CAHeaderOption_t *options,
1998 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1999 CADataType_t dataType)
2001 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
2002 CAResponseInfo_t respInfo = {
2003 .result = responseResult
2005 respInfo.info.messageId = coapID;
2006 respInfo.info.numOptions = numOptions;
2008 if (respInfo.info.numOptions)
2010 respInfo.info.options =
2011 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
2012 memcpy (respInfo.info.options, options,
2013 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
2017 respInfo.info.payload = NULL;
2018 respInfo.info.token = token;
2019 respInfo.info.tokenLength = tokenLength;
2020 respInfo.info.type = type;
2021 respInfo.info.resourceUri = OICStrdup (resourceUri);
2022 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
2023 respInfo.info.dataType = dataType;
2025 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2026 // Add the destination to route option from the endpoint->routeData.
2027 bool doPost = false;
2028 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
2029 if(OC_STACK_OK != result)
2031 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
2032 OICFree (respInfo.info.resourceUri);
2033 OICFree (respInfo.info.options);
2038 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
2039 CARequestInfo_t reqInfo = {.method = CA_POST };
2040 /* The following initialization is not done in a single initializer block as in
2041 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
2042 * does not have designated initalizers. This is a work-around for now.
2044 reqInfo.info.type = CA_MSG_NONCONFIRM;
2045 reqInfo.info.messageId = coapID;
2046 reqInfo.info.tokenLength = tokenLength;
2047 reqInfo.info.token = token;
2048 reqInfo.info.numOptions = respInfo.info.numOptions;
2049 reqInfo.info.payload = NULL;
2050 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
2051 if (reqInfo.info.numOptions)
2053 reqInfo.info.options =
2054 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
2055 if (NULL == reqInfo.info.options)
2057 OIC_LOG(ERROR, TAG, "Calloc failed");
2058 OICFree (reqInfo.info.resourceUri);
2059 OICFree (respInfo.info.resourceUri);
2060 OICFree (respInfo.info.options);
2061 return OC_STACK_NO_MEMORY;
2063 memcpy (reqInfo.info.options, respInfo.info.options,
2064 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
2067 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
2068 OICFree (reqInfo.info.resourceUri);
2069 OICFree (reqInfo.info.options);
2070 OICFree (respInfo.info.resourceUri);
2071 OICFree (respInfo.info.options);
2072 if (CA_STATUS_OK != caResult)
2074 OIC_LOG(ERROR, TAG, "CASendRequest error");
2075 return CAResultToOCResult(caResult);
2081 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
2083 // resourceUri in the info field is cloned in the CA layer and
2084 // thus ownership is still here.
2085 OICFree (respInfo.info.resourceUri);
2086 OICFree (respInfo.info.options);
2087 if(CA_STATUS_OK != caResult)
2089 OIC_LOG(ERROR, TAG, "CASendResponse error");
2090 return CAResultToOCResult(caResult);
2093 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
2097 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
2099 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
2100 OCStackResult result = OC_STACK_ERROR;
2101 if (!protocolRequest)
2103 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
2104 return OC_STACK_INVALID_PARAM;
2107 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
2108 protocolRequest->tokenLength);
2111 OIC_LOG(INFO, TAG, "This is a new Server Request");
2112 result = AddServerRequest(&request, protocolRequest->coapID,
2113 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
2114 protocolRequest->numRcvdVendorSpecificHeaderOptions,
2115 protocolRequest->observationOption, protocolRequest->qos,
2116 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
2117 protocolRequest->payload, protocolRequest->requestToken,
2118 protocolRequest->tokenLength, protocolRequest->resourceUrl,
2119 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
2120 protocolRequest->acceptVersion, &protocolRequest->devAddr);
2121 if (OC_STACK_OK != result)
2123 OIC_LOG(ERROR, TAG, "Error adding server request");
2129 OIC_LOG(ERROR, TAG, "Out of Memory");
2130 return OC_STACK_NO_MEMORY;
2133 if(!protocolRequest->reqMorePacket)
2135 request->requestComplete = 1;
2140 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
2143 if (request->requestComplete)
2145 OIC_LOG(INFO, TAG, "This Server Request is complete");
2146 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2147 OCResource *resource = NULL;
2148 result = DetermineResourceHandling (request, &resHandling, &resource);
2149 if (result == OC_STACK_OK)
2151 result = ProcessRequest(resHandling, resource, request);
2156 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2157 result = OC_STACK_CONTINUE;
2162 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2164 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2165 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2167 if (myStackMode == OC_CLIENT)
2169 //TODO: should the client be responding to requests?
2173 // If the request message is Confirmable,
2174 // then the response SHOULD be returned in an Acknowledgement message.
2175 CAMessageType_t directResponseType = requestInfo->info.type;
2176 directResponseType = (directResponseType == CA_MSG_CONFIRM)
2177 ? CA_MSG_ACKNOWLEDGE : CA_MSG_NONCONFIRM;
2179 char * uriWithoutQuery = NULL;
2180 char * query = NULL;
2181 OCStackResult requestResult = OC_STACK_ERROR;
2183 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2185 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2187 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2190 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2191 OIC_LOG_V(INFO, TAG, "Query : %s", query);
2193 OCServerProtocolRequest serverRequest = { 0 };
2194 if (strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2196 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2197 OICFree(uriWithoutQuery);
2201 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2202 OICFree(uriWithoutQuery);
2209 if (strlen(query) < MAX_QUERY_LENGTH)
2211 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2216 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2222 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2224 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2225 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2226 if (!serverRequest.payload)
2228 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2231 memcpy (serverRequest.payload, requestInfo->info.payload,
2232 requestInfo->info.payloadSize);
2236 serverRequest.reqTotalSize = 0;
2239 switch (requestInfo->method)
2242 serverRequest.method = OC_REST_GET;
2245 serverRequest.method = OC_REST_PUT;
2248 serverRequest.method = OC_REST_POST;
2251 serverRequest.method = OC_REST_DELETE;
2254 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2255 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2256 directResponseType, requestInfo->info.numOptions,
2257 requestInfo->info.options, requestInfo->info.token,
2258 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2260 OICFree(serverRequest.payload);
2264 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2265 requestInfo->info.tokenLength);
2267 serverRequest.tokenLength = requestInfo->info.tokenLength;
2268 if (serverRequest.tokenLength)
2271 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2273 if (!serverRequest.requestToken)
2275 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2276 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2277 directResponseType, requestInfo->info.numOptions,
2278 requestInfo->info.options, requestInfo->info.token,
2279 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2281 OICFree(serverRequest.payload);
2284 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2287 switch (requestInfo->info.acceptFormat)
2289 case CA_FORMAT_APPLICATION_CBOR:
2290 serverRequest.acceptFormat = OC_FORMAT_CBOR;
2292 case CA_FORMAT_APPLICATION_VND_OCF_CBOR:
2293 serverRequest.acceptFormat = OC_FORMAT_VND_OCF_CBOR;
2295 case CA_FORMAT_UNDEFINED:
2296 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2299 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2302 if (requestInfo->info.type == CA_MSG_CONFIRM)
2304 serverRequest.qos = OC_HIGH_QOS;
2308 serverRequest.qos = OC_LOW_QOS;
2310 // CA does not need the following field
2311 // Are we sure CA does not need them? how is it responding to multicast
2312 serverRequest.delayedResNeeded = 0;
2314 serverRequest.coapID = requestInfo->info.messageId;
2316 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2318 // copy vendor specific header options
2319 uint8_t tempNum = (requestInfo->info.numOptions);
2321 // Assume no observation requested and it is a pure GET.
2322 // If obs registration/de-registration requested it'll be fetched from the
2323 // options in GetObserveHeaderOption()
2324 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2326 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2327 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2330 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2331 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2332 directResponseType, requestInfo->info.numOptions,
2333 requestInfo->info.options, requestInfo->info.token,
2334 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2336 OICFree(serverRequest.payload);
2337 OICFree(serverRequest.requestToken);
2340 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2341 if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2343 memcpy(&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
2344 sizeof(CAHeaderOption_t) * tempNum);
2347 requestResult = HandleStackRequests (&serverRequest);
2349 if (requestResult == OC_STACK_SLOW_RESOURCE)
2351 // Send ACK to client as precursor to slow response
2352 if (requestInfo->info.type == CA_MSG_CONFIRM)
2354 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2355 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2359 if (requestResult == OC_STACK_RESOURCE_ERROR
2360 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2362 OIC_LOG(ERROR, TAG, "Observe Registration failed due to resource error");
2364 else if (!OCResultToSuccess(requestResult))
2366 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2368 CAResponseResult_t stackResponse = OCToCAStackResult(requestResult, serverRequest.method);
2370 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2371 directResponseType, requestInfo->info.numOptions,
2372 requestInfo->info.options, requestInfo->info.token,
2373 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2376 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2377 // The token is copied in there, and is thus still owned by this function.
2378 OICFree(serverRequest.payload);
2379 OICFree(serverRequest.requestToken);
2380 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2383 //This function will be called back by CA layer when a request is received
2384 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2386 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2387 OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2390 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2397 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2402 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2403 #ifdef ROUTING_GATEWAY
2404 bool needRIHandling = false;
2405 bool isEmptyMsg = false;
2407 * Routing manager is going to update either of endpoint or request or both.
2408 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2409 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2410 * destination. It can also remove "RM" coap header option before passing request / response to
2411 * RI as this option will make no sense to either RI or application.
2413 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2414 &needRIHandling, &isEmptyMsg);
2415 if (OC_STACK_OK != ret || !needRIHandling)
2417 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2424 * Put source in sender endpoint so that the next packet from application can be routed to
2425 * proper destination and remove RM header option.
2427 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2428 (uint8_t *) &(requestInfo->info.numOptions),
2429 (CAEndpoint_t *) endPoint);
2431 #ifdef ROUTING_GATEWAY
2435 * In Gateways, the MSGType in route option is used to check if the actual
2436 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2437 * EMPTY response is sent in the form of POST request which need to be changed
2438 * to a EMPTY response by RM. This translation is done in this part of the code.
2440 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2441 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2442 .info.messageId = requestInfo->info.messageId,
2443 .info.type = CA_MSG_ACKNOWLEDGE};
2444 OCHandleResponse(endPoint, &respInfo);
2450 // Normal handling of the packet
2451 OCHandleRequests(endPoint, requestInfo);
2453 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2457 //-----------------------------------------------------------------------------
2459 //-----------------------------------------------------------------------------
2461 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2464 !raInfo->username ||
2465 !raInfo->hostname ||
2466 !raInfo->xmpp_domain)
2469 return OC_STACK_INVALID_PARAM;
2471 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2472 gRASetInfo = (result == OC_STACK_OK)? true : false;
2478 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2482 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2485 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2487 OIC_LOG(DEBUG, TAG, "call OCInit1");
2488 return OCInit2(mode, serverFlags, clientFlags, OC_DEFAULT_ADAPTER);
2491 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2492 OCTransportAdapter transportType)
2494 OIC_LOG(INFO, TAG, "Entering OCInit2");
2496 // Serialize calls to start and stop the stack.
2497 OCEnterInitializer();
2499 OCStackResult result = OC_STACK_OK;
2501 if (g_ocStackStartCount == 0)
2503 // This is the first call to initialize the stack so it gets to do the real work.
2504 result = OCInitializeInternal(mode, serverFlags, clientFlags, transportType);
2507 if (result == OC_STACK_OK)
2509 // Increment the start count since we're about to return success.
2510 assert(g_ocStackStartCount != UINT_MAX);
2511 assert(stackState == OC_STACK_INITIALIZED);
2512 g_ocStackStartCount++;
2515 OCLeaveInitializer();
2519 OCStackResult OCInitializeInternal(OCMode mode, OCTransportFlags serverFlags,
2520 OCTransportFlags clientFlags, OCTransportAdapter transportType)
2522 if (stackState == OC_STACK_INITIALIZED)
2524 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2525 OCStop() between them are ignored.");
2529 #ifndef ROUTING_GATEWAY
2530 if (OC_GATEWAY == mode)
2532 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2533 return OC_STACK_INVALID_PARAM;
2540 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2541 return OC_STACK_ERROR;
2545 OIC_LOG_V(INFO, TAG, "IoTivity version is v%s", IOTIVITY_VERSION);
2546 OCStackResult result = OC_STACK_ERROR;
2549 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2550 || (mode == OC_GATEWAY)))
2552 OIC_LOG(ERROR, TAG, "Invalid mode");
2553 return OC_STACK_ERROR;
2557 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2559 caglobals.client = true;
2561 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2563 caglobals.server = true;
2566 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2567 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2569 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2571 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2572 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2574 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2577 defaultDeviceHandler = NULL;
2578 defaultDeviceHandlerCallbackParameter = NULL;
2580 result = InitializeScheduleResourceList();
2581 VERIFY_SUCCESS(result, OC_STACK_OK);
2583 result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2584 VERIFY_SUCCESS(result, OC_STACK_OK);
2586 result = CAResultToOCResult(OCSelectNetwork(transportType));
2587 VERIFY_SUCCESS(result, OC_STACK_OK);
2589 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2590 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2591 VERIFY_SUCCESS(result, OC_STACK_OK);
2593 switch (myStackMode)
2596 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2597 result = CAResultToOCResult(CAStartDiscoveryServer());
2598 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2601 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2602 result = CAResultToOCResult(CAStartListeningServer());
2603 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2605 case OC_CLIENT_SERVER:
2607 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2608 result = CAResultToOCResult(CAStartListeningServer());
2609 if(result == OC_STACK_OK)
2611 result = CAResultToOCResult(CAStartDiscoveryServer());
2615 VERIFY_SUCCESS(result, OC_STACK_OK);
2618 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2621 #ifdef WITH_PRESENCE
2622 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2623 #endif // WITH_PRESENCE
2625 //Update Stack state to initialized
2626 stackState = OC_STACK_INITIALIZED;
2628 // Initialize resource
2629 if(myStackMode != OC_CLIENT)
2631 result = initResources();
2634 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2635 RMSetStackMode(mode);
2636 #ifdef ROUTING_GATEWAY
2637 if (OC_GATEWAY == myStackMode)
2639 result = RMInitialize();
2645 if (result == OC_STACK_OK)
2647 result = InitializeKeepAlive(myStackMode);
2651 #if defined(TCP_ADAPTER) && defined(WITH_CLOUD)
2652 // Initialize the Connection Manager
2653 if (result == OC_STACK_OK)
2655 result = OCCMInitialize();
2660 if(result != OC_STACK_OK)
2662 OIC_LOG(ERROR, TAG, "Stack initialization error");
2663 TerminateScheduleResourceList();
2664 deleteAllResources();
2666 stackState = OC_STACK_UNINITIALIZED;
2671 OCStackResult OCStop()
2673 OIC_LOG(INFO, TAG, "Entering OCStop");
2675 // Serialize calls to start and stop the stack.
2676 OCEnterInitializer();
2678 OCStackResult result = OC_STACK_OK;
2680 if (g_ocStackStartCount == 1)
2682 // This is the last call to stop the stack, do the real work.
2683 result = OCDeInitializeInternal();
2685 else if (g_ocStackStartCount == 0)
2687 OIC_LOG(ERROR, TAG, "Too many calls to OCStop");
2688 assert(!"Too many calls to OCStop");
2689 result = OC_STACK_ERROR;
2692 if (result == OC_STACK_OK)
2694 g_ocStackStartCount--;
2697 OCLeaveInitializer();
2701 OCStackResult OCDeInitializeInternal()
2703 assert(stackState == OC_STACK_INITIALIZED);
2705 #ifdef WITH_PRESENCE
2706 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2707 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2708 presenceResource.presenceTTL = 0;
2709 presenceState = OC_PRESENCE_UNINITIALIZED;
2710 #endif // WITH_PRESENCE
2712 #ifdef ROUTING_GATEWAY
2713 if (OC_GATEWAY == myStackMode)
2720 TerminateKeepAlive(myStackMode);
2723 OCStackResult result = CAResultToOCResult(
2724 CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2725 OCDefaultConnectionStateChangedHandler));
2726 if (OC_STACK_OK != result)
2728 OIC_LOG(ERROR, TAG, "CAUnregisterNetworkMonitorHandler has failed");
2731 TerminateScheduleResourceList();
2732 // Remove all observers
2733 DeleteObserverList();
2734 // Free memory dynamically allocated for resources
2735 deleteAllResources();
2736 // Remove all the client callbacks
2737 DeleteClientCBList();
2738 // Terminate connectivity-abstraction layer.
2741 #if defined(TCP_ADAPTER) && defined(WITH_CLOUD)
2742 // Terminate the Connection Manager
2746 // Unset cautil config
2747 CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2748 CAUtilSetBTConfigure(configs);
2750 stackState = OC_STACK_UNINITIALIZED;
2754 OCStackResult OCStartMulticastServer()
2756 if(stackState != OC_STACK_INITIALIZED)
2758 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2759 return OC_STACK_ERROR;
2761 g_multicastServerStopped = false;
2765 OCStackResult OCStopMulticastServer()
2767 g_multicastServerStopped = true;
2771 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2776 return CA_MSG_CONFIRM;
2781 return CA_MSG_NONCONFIRM;
2786 * A request uri consists of the following components in order:
2789 * CoAP over UDP prefix "coap://"
2790 * CoAP over TCP prefix "coap+tcp://"
2791 * CoAP over DTLS prefix "coaps://"
2792 * CoAP over TLS prefix "coaps+tcp://"
2794 * IPv6 address "[1234::5678]"
2795 * IPv4 address "192.168.1.1"
2796 * optional port ":5683"
2797 * resource uri "/oc/core..."
2799 * for PRESENCE requests, extract resource type.
2801 static OCStackResult ParseRequestUri(const char *fullUri,
2802 OCTransportAdapter adapter,
2803 OCTransportFlags flags,
2804 OCDevAddr **devAddr,
2806 char **resourceType)
2808 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2810 OCStackResult result = OC_STACK_OK;
2811 OCDevAddr *da = NULL;
2815 // provide defaults for all returned values
2822 *resourceUri = NULL;
2826 *resourceType = NULL;
2829 // delimit url prefix, if any
2830 const char *start = fullUri;
2831 char *slash2 = strstr(start, "//");
2836 char *slash = strchr(start, '/');
2839 return OC_STACK_INVALID_URI;
2842 // process url scheme
2843 size_t prefixLen = slash2 - fullUri;
2847 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2848 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2854 // TODO: this logic should come in with unit tests exercising the various strings
2855 // processs url prefix, if any
2856 size_t urlLen = slash - start;
2860 if (urlLen && devAddr)
2861 { // construct OCDevAddr
2862 if (start[0] == '[')
2864 char *close = strchr(++start, ']');
2865 if (!close || close > slash)
2867 return OC_STACK_INVALID_URI;
2870 if (close[1] == ':')
2877 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2881 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2883 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2887 char *dot = strchr(start, '.');
2888 if (dot && dot < slash)
2890 colon = strchr(start, ':');
2891 end = (colon && colon < slash) ? colon : slash;
2896 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2900 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2902 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2910 if (len >= sizeof(da->addr))
2912 return OC_STACK_INVALID_URI;
2914 // collect port, if any
2915 if (colon && colon < slash)
2917 for (colon++; colon < slash; colon++)
2920 if (c < '0' || c > '9')
2922 return OC_STACK_INVALID_URI;
2924 port = 10 * port + c - '0';
2929 if (len >= sizeof(da->addr))
2931 return OC_STACK_INVALID_URI;
2934 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2937 return OC_STACK_NO_MEMORY;
2940 // Decode address per RFC 6874.
2941 result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2942 if (result != OC_STACK_OK)
2949 da->adapter = adapter;
2951 if (!strncmp(fullUri, "coaps", 5))
2953 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2958 // process resource uri, if any
2960 { // request uri and query
2961 size_t ulen = strlen(slash); // resource uri length
2962 size_t tlen = 0; // resource type length
2965 static const char strPresence[] = "/oic/ad?rt=";
2966 static const size_t lenPresence = sizeof(strPresence) - 1;
2967 if (!strncmp(slash, strPresence, lenPresence))
2969 type = slash + lenPresence;
2970 tlen = ulen - lenPresence;
2975 *resourceUri = (char *)OICMalloc(ulen + 1);
2978 result = OC_STACK_NO_MEMORY;
2981 strcpy(*resourceUri, slash);
2984 if (type && resourceType)
2986 *resourceType = (char *)OICMalloc(tlen + 1);
2989 result = OC_STACK_NO_MEMORY;
2993 OICStrcpy(*resourceType, (tlen+1), type);
3000 // free all returned values
3007 OICFree(*resourceUri);
3011 OICFree(*resourceType);
3016 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
3020 char uri[CA_MAX_URI_LENGTH];
3022 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
3024 *requestUri = OICStrdup(uri);
3027 return OC_STACK_NO_MEMORY;
3034 * Discover or Perform requests on a specified resource
3036 OCStackResult OCDoResource(OCDoHandle *handle,
3038 const char *requestUri,
3039 const OCDevAddr *destination,
3041 OCConnectivityType connectivityType,
3042 OCQualityOfService qos,
3043 OCCallbackData *cbData,
3044 OCHeaderOption *options,
3047 OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
3048 connectivityType, qos, cbData, options, numOptions);
3050 // This is the owner of the payload object, so we free it
3051 OCPayloadDestroy(payload);
3056 * Discover or Perform requests on a specified resource
3058 OCStackResult OCDoRequest(OCDoHandle *handle,
3060 const char *requestUri,
3061 const OCDevAddr *destination,
3063 OCConnectivityType connectivityType,
3064 OCQualityOfService qos,
3065 OCCallbackData *cbData,
3066 OCHeaderOption *options,
3069 OIC_LOG(INFO, TAG, "Entering OCDoResource");
3071 // Validate input parameters
3072 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
3073 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
3075 OCStackResult result = OC_STACK_ERROR;
3076 CAResult_t caResult;
3077 CAToken_t token = NULL;
3078 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3079 ClientCB *clientCB = NULL;
3080 OCDoHandle resHandle = NULL;
3081 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3082 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
3084 OCTransportAdapter adapter;
3085 OCTransportFlags flags;
3086 // the request contents are put here
3087 CARequestInfo_t requestInfo = {.method = CA_GET};
3088 // requestUri will be parsed into the following three variables
3089 OCDevAddr *devAddr = NULL;
3090 char *resourceUri = NULL;
3091 char *resourceType = NULL;
3094 * Support original behavior with address on resourceUri argument.
3096 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
3097 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
3101 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
3102 if (result != OC_STACK_OK)
3104 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
3108 else if (!checkProxyUri(options, numOptions))
3110 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
3117 case OC_REST_OBSERVE:
3118 case OC_REST_OBSERVE_ALL:
3119 requestInfo.method = CA_GET;
3122 requestInfo.method = CA_PUT;
3125 requestInfo.method = CA_POST;
3127 case OC_REST_DELETE:
3128 requestInfo.method = CA_DELETE;
3130 case OC_REST_DISCOVER:
3131 // intentional fall through don't add break
3132 #ifdef WITH_PRESENCE
3133 case OC_REST_PRESENCE:
3135 if (destination || devAddr)
3137 requestInfo.isMulticast = false;
3141 tmpDevAddr.adapter = adapter;
3142 tmpDevAddr.flags = flags;
3143 destination = &tmpDevAddr;
3144 requestInfo.isMulticast = true;
3147 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
3148 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
3149 // replacing method type with GET.
3150 requestInfo.method = CA_GET;
3153 result = OC_STACK_INVALID_METHOD;
3157 if (!devAddr && !destination)
3159 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
3160 result = OC_STACK_INVALID_PARAM;
3164 /* If not original behavior, use destination argument */
3165 if (destination && !devAddr)
3167 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
3170 result = OC_STACK_NO_MEMORY;
3173 OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
3174 *devAddr = *destination;
3179 OIC_LOG_V(DEBUG, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
3182 resHandle = GenerateInvocationHandle();
3185 result = OC_STACK_NO_MEMORY;
3189 caResult = CAGenerateToken(&token, tokenLength);
3190 if (caResult != CA_STATUS_OK)
3192 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3193 result= OC_STACK_ERROR;
3197 // fill in request data
3198 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3199 requestInfo.info.token = token;
3200 requestInfo.info.tokenLength = tokenLength;
3202 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3204 result = CreateObserveHeaderOption (&(requestInfo.info.options),
3205 options, numOptions, OC_OBSERVE_REGISTER);
3206 if (result != OC_STACK_OK)
3210 requestInfo.info.numOptions = numOptions + 1;
3214 requestInfo.info.numOptions = numOptions;
3215 requestInfo.info.options =
3216 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3217 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3218 numOptions * sizeof(CAHeaderOption_t));
3221 CopyDevAddrToEndpoint(devAddr, &endpoint);
3226 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3229 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3233 uint16_t payloadVersion = OC_SPEC_VERSION_VALUE;
3234 // From OCF onwards, check version option settings
3235 if (DEFAULT_CONTENT_VERSION_VALUE <= payloadVersion)
3237 if (numOptions > 0 && options)
3239 for (uint8_t i = 0; i < numOptions; i++)
3241 if (COAP_OPTION_CONTENT_VERSION == options[i].optionID)
3243 payloadVersion = options[i].optionData[0];
3246 else if (COAP_OPTION_ACCEPT_VERSION == options[i].optionID)
3248 payloadVersion = options[i].optionData[0];
3255 if (DEFAULT_CONTENT_VERSION_VALUE <= payloadVersion)
3257 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_VND_OCF_CBOR;
3258 requestInfo.info.payloadVersion = payloadVersion;
3262 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3267 requestInfo.info.payload = NULL;
3268 requestInfo.info.payloadSize = 0;
3269 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3272 // prepare for response
3273 #ifdef WITH_PRESENCE
3274 if (method == OC_REST_PRESENCE)
3276 char *presenceUri = NULL;
3277 result = OCPreparePresence(&endpoint, &presenceUri,
3278 requestInfo.isMulticast);
3279 if (OC_STACK_OK != result)
3284 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3285 // Presence notification will form a canonical uri to
3286 // look for callbacks into the application.
3289 OICFree(resourceUri);
3291 resourceUri = presenceUri;
3295 // update resourceUri onto requestInfo after check presence uri
3296 requestInfo.info.resourceUri = resourceUri;
3298 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3299 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3300 method, devAddr, resourceUri, resourceType, ttl);
3301 if (OC_STACK_OK != result)
3306 devAddr = NULL; // Client CB list entry now owns it
3307 resourceUri = NULL; // Client CB list entry now owns it
3308 resourceType = NULL; // Client CB list entry now owns it
3310 #ifdef WITH_PRESENCE
3311 if (method == OC_REST_PRESENCE)
3313 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3317 *handle = resHandle;
3325 result = OCSendRequest(&endpoint, &requestInfo);
3326 if (OC_STACK_OK != result)
3333 *handle = resHandle;
3337 if (result != OC_STACK_OK)
3339 OIC_LOG(ERROR, TAG, "OCDoResource error");
3340 FindAndDeleteClientCB(clientCB);
3341 CADestroyToken(token);
3349 OICFree(requestInfo.info.payload);
3351 OICFree(resourceUri);
3352 OICFree(resourceType);
3353 OICFree(requestInfo.info.options);
3357 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3361 * This ftn is implemented one of two ways in the case of observation:
3363 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3364 * Remove the callback associated on client side.
3365 * When the next notification comes in from server,
3366 * reply with RESET message to server.
3367 * Keep in mind that the server will react to RESET only
3368 * if the last notification was sent as CON
3370 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3371 * and it is associated with an observe request
3372 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3373 * Send CON Observe request to server with
3374 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3375 * Remove the callback associated on client side.
3377 OCStackResult ret = OC_STACK_OK;
3378 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3379 CARequestInfo_t requestInfo = {.method = CA_GET};
3383 return OC_STACK_INVALID_PARAM;
3386 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3389 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3390 return OC_STACK_ERROR;
3393 switch (clientCB->method)
3395 case OC_REST_OBSERVE:
3396 case OC_REST_OBSERVE_ALL:
3398 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3400 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3402 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
3404 FindAndDeleteClientCB(clientCB);
3408 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3410 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3411 requestInfo.info.token = clientCB->token;
3412 requestInfo.info.tokenLength = clientCB->tokenLength;
3414 if (CreateObserveHeaderOption (&(requestInfo.info.options),
3415 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3417 return OC_STACK_ERROR;
3419 requestInfo.info.numOptions = numOptions + 1;
3420 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3423 ret = OCSendRequest(&endpoint, &requestInfo);
3425 if (requestInfo.info.options)
3427 OICFree (requestInfo.info.options);
3429 if (requestInfo.info.resourceUri)
3431 OICFree (requestInfo.info.resourceUri);
3436 case OC_REST_DISCOVER:
3437 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3438 clientCB->requestUri);
3439 FindAndDeleteClientCB(clientCB);
3442 #ifdef WITH_PRESENCE
3443 case OC_REST_PRESENCE:
3444 FindAndDeleteClientCB(clientCB);
3449 ret = OC_STACK_INVALID_METHOD;
3457 * @brief Register Persistent storage callback.
3458 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3460 * OC_STACK_OK - No errors; Success
3461 * OC_STACK_INVALID_PARAM - Invalid parameter
3463 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3465 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3466 if(persistentStorageHandler)
3468 if( !persistentStorageHandler->open ||
3469 !persistentStorageHandler->close ||
3470 !persistentStorageHandler->read ||
3471 !persistentStorageHandler->unlink ||
3472 !persistentStorageHandler->write)
3474 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3475 return OC_STACK_INVALID_PARAM;
3478 g_PersistentStorageHandler = persistentStorageHandler;
3482 OCPersistentStorage *OCGetPersistentStorageHandler()
3484 return g_PersistentStorageHandler;
3487 #ifdef WITH_PRESENCE
3489 OCStackResult OCProcessPresence()
3491 OCStackResult result = OC_STACK_OK;
3493 // the following line floods the log with messages that are irrelevant
3494 // to most purposes. Uncomment as needed.
3495 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3496 ClientCB* cbNode = NULL;
3497 ClientCB* cbTemp = NULL;
3498 OCClientResponse clientResponse;
3499 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3501 LL_FOREACH_SAFE(cbList, cbNode, cbTemp)
3503 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3508 uint32_t now = GetTicks(0);
3509 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3510 cbNode->presence->TTLlevel);
3511 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3513 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3518 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3520 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3521 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3523 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3525 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3527 clientResponse.sequenceNumber = 0;
3528 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3529 clientResponse.devAddr = *cbNode->devAddr;
3530 FixUpClientResponse(&clientResponse);
3531 clientResponse.payload = NULL;
3533 // Increment the TTLLevel (going to a next state), so we don't keep
3534 // sending presence notification to client.
3535 cbNode->presence->TTLlevel++;
3536 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3537 cbNode->presence->TTLlevel);
3539 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3540 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3542 FindAndDeleteClientCB(cbNode);
3546 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3551 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3552 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3553 CARequestInfo_t requestInfo = {.method = CA_GET};
3555 OIC_LOG(DEBUG, TAG, "time to test server presence");
3557 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3559 requestData.type = CA_MSG_NONCONFIRM;
3560 requestData.token = cbNode->token;
3561 requestData.tokenLength = cbNode->tokenLength;
3562 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3563 requestInfo.method = CA_GET;
3564 requestInfo.info = requestData;
3566 result = OCSendRequest(&endpoint, &requestInfo);
3567 if (OC_STACK_OK != result)
3572 cbNode->presence->TTLlevel++;
3573 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3576 if (result != OC_STACK_OK)
3578 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3583 #endif // WITH_PRESENCE
3585 OCStackResult OCProcess()
3587 if (stackState == OC_STACK_UNINITIALIZED)
3589 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3590 return OC_STACK_ERROR;
3592 #ifdef WITH_PRESENCE
3593 OCProcessPresence();
3595 CAHandleRequestResponse();
3597 #ifdef ROUTING_GATEWAY
3607 #ifdef WITH_PRESENCE
3608 OCStackResult OCStartPresence(const uint32_t ttl)
3610 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3611 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3612 OCChangeResourceProperty(
3613 &(((OCResource *)presenceResource.handle)->resourceProperties),
3616 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3618 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3619 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3623 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3624 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3628 presenceResource.presenceTTL = ttl;
3630 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3632 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3634 presenceState = OC_PRESENCE_INITIALIZED;
3636 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3638 CAToken_t caToken = NULL;
3639 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3640 if (caResult != CA_STATUS_OK)
3642 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3643 CADestroyToken(caToken);
3644 return OC_STACK_ERROR;
3647 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3648 (OCResource *) presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED,
3649 OC_SPEC_VERSION_VALUE, &devAddr);
3650 CADestroyToken(caToken);
3653 // Each time OCStartPresence is called
3654 // a different random 32-bit integer number is used
3655 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3657 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3658 OC_PRESENCE_TRIGGER_CREATE);
3661 OCStackResult OCStopPresence()
3663 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3664 OCStackResult result = OC_STACK_ERROR;
3666 if(presenceResource.handle)
3668 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3670 // make resource inactive
3671 result = OCChangeResourceProperty(
3672 &(((OCResource *) presenceResource.handle)->resourceProperties),
3676 if(result != OC_STACK_OK)
3679 "Changing the presence resource properties to ACTIVE not successful");
3683 return SendStopNotification();
3687 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3688 void* callbackParameter)
3690 defaultDeviceHandler = entityHandler;
3691 defaultDeviceHandlerCallbackParameter = callbackParameter;
3696 OCTpsSchemeFlags OCGetSupportedEndpointTpsFlags()
3698 return OCGetSupportedTpsFlags();
3701 OCStackResult OCCreateResource(OCResourceHandle *handle,
3702 const char *resourceTypeName,
3703 const char *resourceInterfaceName,
3704 const char *uri, OCEntityHandler entityHandler,
3705 void *callbackParam,
3706 uint8_t resourceProperties)
3708 return OCCreateResourceWithEp(handle,
3710 resourceInterfaceName,
3717 OCStackResult OCCreateResourceWithEp(OCResourceHandle *handle,
3718 const char *resourceTypeName,
3719 const char *resourceInterfaceName,
3720 const char *uri, OCEntityHandler entityHandler,
3721 void *callbackParam,
3722 uint8_t resourceProperties,
3723 OCTpsSchemeFlags resourceTpsTypes)
3726 OCResource *pointer = NULL;
3727 OCStackResult result = OC_STACK_ERROR;
3729 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3731 if(myStackMode == OC_CLIENT)
3733 return OC_STACK_INVALID_PARAM;
3735 // Validate parameters
3736 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3738 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3739 return OC_STACK_INVALID_URI;
3741 // Is it presented during resource discovery?
3742 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3744 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3745 return OC_STACK_INVALID_PARAM;
3748 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3750 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3754 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3756 // Make sure resourceProperties bitmask has allowed properties specified
3757 if (resourceProperties
3758 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3759 OC_EXPLICIT_DISCOVERABLE
3768 OIC_LOG(ERROR, TAG, "Invalid property");
3769 return OC_STACK_INVALID_PARAM;
3772 // Checking resourceTpsTypes param
3773 OCTpsSchemeFlags validTps = OC_NO_TPS;
3774 validTps = (OCTpsSchemeFlags)(validTps | OC_COAP | OC_COAPS);
3776 validTps = (OCTpsSchemeFlags)(validTps | OC_COAP_TCP | OC_COAPS_TCP);
3779 validTps = (OCTpsSchemeFlags)(validTps | OC_HTTP | OC_HTTP);
3782 validTps = (OCTpsSchemeFlags)(validTps | OC_COAP_RFCOMM);
3785 validTps = (OCTpsSchemeFlags)(validTps | OC_COAP_GATT);
3788 validTps = (OCTpsSchemeFlags)(validTps | OC_COAP_NFC);
3791 validTps = (OCTpsSchemeFlags)(validTps | OC_COAP_RA);
3794 if ((resourceTpsTypes < OC_COAP) || ((resourceTpsTypes != OC_ALL) &&
3795 (resourceTpsTypes > validTps)))
3797 OIC_LOG(ERROR, TAG, "Invalid TPS Types OC_ALL");
3798 return OC_STACK_INVALID_PARAM;
3801 // If the headResource is NULL, then no resources have been created...
3802 pointer = headResource;
3805 // At least one resources is in the resource list, so we need to search for
3806 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3809 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3811 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3812 return OC_STACK_INVALID_PARAM;
3814 pointer = pointer->next;
3817 // Create the pointer and insert it into the resource list
3818 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3821 result = OC_STACK_NO_MEMORY;
3824 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3826 insertResource(pointer);
3829 pointer->uri = OICStrdup(uri);
3832 result = OC_STACK_NO_MEMORY;
3836 // Set properties. Set OC_ACTIVE
3837 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3840 // Add the resourcetype to the resource
3841 result = BindResourceTypeToResource(pointer, resourceTypeName);
3842 if (result != OC_STACK_OK)
3844 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3848 // Add the resourceinterface to the resource
3849 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3850 if (result != OC_STACK_OK)
3852 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3856 result = BindTpsTypeToResource(pointer, resourceTpsTypes);
3857 if (result != OC_STACK_OK)
3859 OIC_LOG(ERROR, TAG, "Error adding resource TPS types");
3863 // If an entity handler has been passed, attach it to the newly created
3864 // resource. Otherwise, set the default entity handler.
3867 pointer->entityHandler = entityHandler;
3868 pointer->entityHandlerCallbackParam = callbackParam;
3872 pointer->entityHandler = defaultResourceEHandler;
3873 pointer->entityHandlerCallbackParam = NULL;
3876 // Initialize a pointer indicating child resources in case of collection
3877 pointer->rsrcChildResourcesHead = NULL;
3880 result = OC_STACK_OK;
3882 #ifdef WITH_PRESENCE
3883 if (presenceResource.handle)
3885 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3886 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3890 if (result != OC_STACK_OK)
3892 // Deep delete of resource and other dynamic elements that it contains
3893 deleteResource(pointer);
3898 OCStackResult OCBindResource(
3899 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3901 OCResource *resource = NULL;
3902 OCChildResource *tempChildResource = NULL;
3903 OCChildResource *newChildResource = NULL;
3905 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3907 // Validate parameters
3908 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3909 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3910 // Container cannot contain itself
3911 if (collectionHandle == resourceHandle)
3913 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3914 return OC_STACK_INVALID_PARAM;
3917 // Use the handle to find the resource in the resource linked list
3918 resource = findResource((OCResource *) collectionHandle);
3921 OIC_LOG(ERROR, TAG, "Collection handle not found");
3922 return OC_STACK_INVALID_PARAM;
3925 // Look for an open slot to add add the child resource.
3926 // If found, add it and return success
3928 tempChildResource = resource->rsrcChildResourcesHead;
3930 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3932 // TODO: what if one of child resource was deregistered without unbinding?
3933 tempChildResource = tempChildResource->next;
3936 // Do memory allocation for child resource
3937 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3938 if(!newChildResource)
3940 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3941 return OC_STACK_ERROR;
3944 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3945 newChildResource->next = NULL;
3947 if(!resource->rsrcChildResourcesHead)
3949 resource->rsrcChildResourcesHead = newChildResource;
3952 tempChildResource->next = newChildResource;
3955 OIC_LOG(INFO, TAG, "resource bound");
3957 #ifdef WITH_PRESENCE
3958 if (presenceResource.handle)
3960 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3961 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3962 OC_PRESENCE_TRIGGER_CHANGE);
3969 OCStackResult OCUnBindResource(
3970 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3972 OCResource *resource = NULL;
3973 OCChildResource *tempChildResource = NULL;
3974 OCChildResource *tempLastChildResource = NULL;
3976 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3978 // Validate parameters
3979 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3980 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3981 // Container cannot contain itself
3982 if (collectionHandle == resourceHandle)
3984 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3985 return OC_STACK_INVALID_PARAM;
3988 // Use the handle to find the resource in the resource linked list
3989 resource = findResource((OCResource *) collectionHandle);
3992 OIC_LOG(ERROR, TAG, "Collection handle not found");
3993 return OC_STACK_INVALID_PARAM;
3996 // Look for an open slot to add add the child resource.
3997 // If found, add it and return success
3998 if(!resource->rsrcChildResourcesHead)
4000 OIC_LOG(INFO, TAG, "resource not found in collection");
4002 // Unable to add resourceHandle, so return error
4003 return OC_STACK_ERROR;
4007 tempChildResource = resource->rsrcChildResourcesHead;
4009 while (tempChildResource)
4011 if(tempChildResource->rsrcResource == resourceHandle)
4013 // if resource going to be unbinded is the head one.
4014 if( tempChildResource == resource->rsrcChildResourcesHead )
4016 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
4017 OICFree(resource->rsrcChildResourcesHead);
4018 resource->rsrcChildResourcesHead = temp;
4023 OCChildResource *temp = tempChildResource->next;
4024 OICFree(tempChildResource);
4025 if (tempLastChildResource)
4027 tempLastChildResource->next = temp;
4032 OIC_LOG(INFO, TAG, "resource unbound");
4034 // Send notification when resource is unbounded successfully.
4035 #ifdef WITH_PRESENCE
4036 if (presenceResource.handle)
4038 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4039 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
4040 OC_PRESENCE_TRIGGER_CHANGE);
4043 tempChildResource = NULL;
4044 tempLastChildResource = NULL;
4050 tempLastChildResource = tempChildResource;
4051 tempChildResource = tempChildResource->next;
4054 OIC_LOG(INFO, TAG, "resource not found in collection");
4056 tempChildResource = NULL;
4057 tempLastChildResource = NULL;
4059 // Unable to add resourceHandle, so return error
4060 return OC_STACK_ERROR;
4063 static bool ValidateResourceTypeInterface(const char *resourceItemName)
4065 if (!resourceItemName)
4069 // Per RFC 6690 only registered values must follow the first rule below.
4070 // At this point in time the only values registered begin with "core", and
4071 // all other values are specified as opaque strings where multiple values
4072 // are separated by a space.
4073 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
4075 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
4077 if (resourceItemName[index] != '.'
4078 && resourceItemName[index] != '-'
4079 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
4080 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
4088 for (size_t index = 0; resourceItemName[index]; ++index)
4090 if (resourceItemName[index] == ' '
4091 || resourceItemName[index] == '\t'
4092 || resourceItemName[index] == '\r'
4093 || resourceItemName[index] == '\n')
4103 OCStackResult BindResourceTypeToResource(OCResource* resource,
4104 const char *resourceTypeName)
4106 OCResourceType *pointer = NULL;
4108 OCStackResult result = OC_STACK_ERROR;
4110 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
4112 if (!ValidateResourceTypeInterface(resourceTypeName))
4114 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
4115 return OC_STACK_INVALID_PARAM;
4118 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
4121 result = OC_STACK_NO_MEMORY;
4125 str = OICStrdup(resourceTypeName);
4128 result = OC_STACK_NO_MEMORY;
4131 pointer->resourcetypename = str;
4132 pointer->next = NULL;
4134 insertResourceType(resource, pointer);
4135 result = OC_STACK_OK;
4138 if (result != OC_STACK_OK)
4147 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
4148 const char *resourceInterfaceName)
4150 OCResourceInterface *pointer = NULL;
4152 OCStackResult result = OC_STACK_ERROR;
4154 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
4156 if (!ValidateResourceTypeInterface(resourceInterfaceName))
4158 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
4159 return OC_STACK_INVALID_PARAM;
4162 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
4164 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
4167 result = OC_STACK_NO_MEMORY;
4171 str = OICStrdup(resourceInterfaceName);
4174 result = OC_STACK_NO_MEMORY;
4177 pointer->name = str;
4179 // Bind the resourceinterface to the resource
4180 insertResourceInterface(resource, pointer);
4182 result = OC_STACK_OK;
4185 if (result != OC_STACK_OK)
4194 OCStackResult BindTpsTypeToResource(OCResource* resource,
4195 OCTpsSchemeFlags resourceTpsTypes)
4199 OIC_LOG(ERROR, TAG, "Resource pointer is NULL!!!");
4200 return OC_STACK_INVALID_PARAM;
4203 OCTpsSchemeFlags supportedTps = OC_NO_TPS;
4204 OCStackResult result = OCGetSupportedEndpointFlags(resourceTpsTypes,
4207 if (result != OC_STACK_OK)
4209 OIC_LOG(ERROR, TAG, "Failed at get supported endpoint flags");
4213 // If there isn`t any enabled flag, return error for notify to user.
4214 if (OC_NO_TPS == supportedTps)
4216 OIC_LOG_V(ERROR, TAG, "There isn`t any enabled flag on resource %s", resource->uri);
4217 return OC_STACK_BAD_ENDPOINT;
4220 OIC_LOG_V(INFO, TAG, "Binding %d TPS flags to %s", supportedTps, resource->uri);
4221 resource->endpointType = supportedTps;
4225 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
4226 const char *resourceTypeName)
4229 OCStackResult result = OC_STACK_ERROR;
4230 OCResource *resource = NULL;
4232 resource = findResource((OCResource *) handle);
4235 OIC_LOG(ERROR, TAG, "Resource not found");
4236 return OC_STACK_ERROR;
4239 result = BindResourceTypeToResource(resource, resourceTypeName);
4241 #ifdef WITH_PRESENCE
4242 if(presenceResource.handle)
4244 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4245 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4252 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
4253 const char *resourceInterfaceName)
4256 OCStackResult result = OC_STACK_ERROR;
4257 OCResource *resource = NULL;
4259 resource = findResource((OCResource *) handle);
4262 OIC_LOG(ERROR, TAG, "Resource not found");
4263 return OC_STACK_ERROR;
4266 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
4268 #ifdef WITH_PRESENCE
4269 if (presenceResource.handle)
4271 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4272 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4279 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
4281 OCResource *pointer = headResource;
4283 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
4287 *numResources = *numResources + 1;
4288 pointer = pointer->next;
4293 OCResourceHandle OCGetResourceHandle(uint8_t index)
4295 OCResource *pointer = headResource;
4297 for( uint8_t i = 0; i < index && pointer; ++i)
4299 pointer = pointer->next;
4301 return (OCResourceHandle) pointer;
4304 OCStackResult OCDeleteResource(OCResourceHandle handle)
4308 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4309 return OC_STACK_INVALID_PARAM;
4312 OCResource *resource = findResource((OCResource *) handle);
4313 if (resource == NULL)
4315 OIC_LOG(ERROR, TAG, "Resource not found");
4316 return OC_STACK_NO_RESOURCE;
4319 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4321 OIC_LOG(ERROR, TAG, "Error deleting resource");
4322 return OC_STACK_ERROR;
4328 const char *OCGetResourceUri(OCResourceHandle handle)
4330 OCResource *resource = NULL;
4332 resource = findResource((OCResource *) handle);
4335 return resource->uri;
4337 return (const char *) NULL;
4340 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4342 OCResource *resource = NULL;
4344 resource = findResource((OCResource *) handle);
4347 return resource->resourceProperties;
4349 return (OCResourceProperty)-1;
4352 OCStackResult OCSetResourceProperties(OCResourceHandle handle, uint8_t resourceProperties)
4354 OCResource *resource = NULL;
4356 resource = findResource((OCResource *) handle);
4357 if (resource == NULL)
4359 OIC_LOG(ERROR, TAG, "Resource not found");
4360 return OC_STACK_NO_RESOURCE;
4362 resource->resourceProperties = (OCResourceProperty) (resource->resourceProperties | resourceProperties);
4366 OCStackResult OCClearResourceProperties(OCResourceHandle handle, uint8_t resourceProperties)
4368 OCResource *resource = NULL;
4370 resource = findResource((OCResource *) handle);
4371 if (resource == NULL)
4373 OIC_LOG(ERROR, TAG, "Resource not found");
4374 return OC_STACK_NO_RESOURCE;
4376 resource->resourceProperties = (OCResourceProperty) (resource->resourceProperties & ~resourceProperties);
4380 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4381 uint8_t *numResourceTypes)
4383 OCResource *resource = NULL;
4384 OCResourceType *pointer = NULL;
4386 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4387 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4389 *numResourceTypes = 0;
4391 resource = findResource((OCResource *) handle);
4394 pointer = resource->rsrcType;
4397 *numResourceTypes = *numResourceTypes + 1;
4398 pointer = pointer->next;
4404 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4406 OCResourceType *resourceType = NULL;
4408 resourceType = findResourceTypeAtIndex(handle, index);
4411 return resourceType->resourcetypename;
4413 return (const char *) NULL;
4416 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4417 uint8_t *numResourceInterfaces)
4419 OCResourceInterface *pointer = NULL;
4420 OCResource *resource = NULL;
4422 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4423 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4425 *numResourceInterfaces = 0;
4426 resource = findResource((OCResource *) handle);
4429 pointer = resource->rsrcInterface;
4432 *numResourceInterfaces = *numResourceInterfaces + 1;
4433 pointer = pointer->next;
4439 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4441 OCResourceInterface *resourceInterface = NULL;
4443 resourceInterface = findResourceInterfaceAtIndex(handle, index);
4444 if (resourceInterface)
4446 return resourceInterface->name;
4448 return (const char *) NULL;
4451 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4454 OCResource *resource = NULL;
4455 OCChildResource *tempChildResource = NULL;
4458 resource = findResource((OCResource *) collectionHandle);
4464 tempChildResource = resource->rsrcChildResourcesHead;
4466 while(tempChildResource)
4470 return tempChildResource->rsrcResource;
4473 tempChildResource = tempChildResource->next;
4476 // In this case, the number of resource handles in the collection exceeds the index
4477 tempChildResource = NULL;
4481 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4482 OCEntityHandler entityHandler,
4483 void* callbackParam)
4485 OCResource *resource = NULL;
4487 // Validate parameters
4488 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4490 // Use the handle to find the resource in the resource linked list
4491 resource = findResource((OCResource *)handle);
4494 OIC_LOG(ERROR, TAG, "Resource not found");
4495 return OC_STACK_ERROR;
4499 resource->entityHandler = entityHandler;
4500 resource->entityHandlerCallbackParam = callbackParam;
4502 #ifdef WITH_PRESENCE
4503 if (presenceResource.handle)
4505 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4506 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4513 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4515 OCResource *resource = NULL;
4517 resource = findResource((OCResource *)handle);
4520 OIC_LOG(ERROR, TAG, "Resource not found");
4525 return resource->entityHandler;
4528 void incrementSequenceNumber(OCResource * resPtr)
4530 // Increment the sequence number
4531 resPtr->sequenceNum += 1;
4532 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4534 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4539 #ifdef WITH_PRESENCE
4540 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4541 OCPresenceTrigger trigger)
4543 OIC_LOG(INFO, TAG, "SendPresenceNotification");
4544 OCResource *resPtr = NULL;
4545 OCStackResult result = OC_STACK_ERROR;
4546 OCMethod method = OC_REST_PRESENCE;
4547 uint32_t maxAge = 0;
4548 resPtr = findResource((OCResource *) presenceResource.handle);
4551 return OC_STACK_NO_RESOURCE;
4554 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4556 maxAge = presenceResource.presenceTTL;
4558 result = SendAllObserverNotification(method, resPtr, maxAge,
4559 trigger, resourceType, OC_LOW_QOS);
4565 OCStackResult SendStopNotification()
4567 OIC_LOG(INFO, TAG, "SendStopNotification");
4568 OCResource *resPtr = NULL;
4569 OCStackResult result = OC_STACK_ERROR;
4570 OCMethod method = OC_REST_PRESENCE;
4571 resPtr = findResource((OCResource *) presenceResource.handle);
4574 return OC_STACK_NO_RESOURCE;
4577 // maxAge is 0. ResourceType is NULL.
4578 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4584 #endif // WITH_PRESENCE
4585 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4587 OCResource *resPtr = NULL;
4588 OCStackResult result = OC_STACK_ERROR;
4589 OCMethod method = OC_REST_NOMETHOD;
4590 uint32_t maxAge = 0;
4592 OIC_LOG(INFO, TAG, "Notifying all observers");
4593 #ifdef WITH_PRESENCE
4594 if(handle == presenceResource.handle)
4598 #endif // WITH_PRESENCE
4599 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4601 // Verify that the resource exists
4602 resPtr = findResource ((OCResource *) handle);
4605 return OC_STACK_NO_RESOURCE;
4609 //only increment in the case of regular observing (not presence)
4610 incrementSequenceNumber(resPtr);
4611 method = OC_REST_OBSERVE;
4612 maxAge = MAX_OBSERVE_AGE;
4613 #ifdef WITH_PRESENCE
4614 result = SendAllObserverNotification (method, resPtr, maxAge,
4615 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4617 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4624 OCNotifyListOfObservers (OCResourceHandle handle,
4625 OCObservationId *obsIdList,
4626 uint8_t numberOfIds,
4627 const OCRepPayload *payload,
4628 OCQualityOfService qos)
4630 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4632 OCResource *resPtr = NULL;
4633 //TODO: we should allow the server to define this
4634 uint32_t maxAge = MAX_OBSERVE_AGE;
4636 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4637 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4638 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4640 resPtr = findResource ((OCResource *) handle);
4641 if (NULL == resPtr || myStackMode == OC_CLIENT)
4643 return OC_STACK_NO_RESOURCE;
4647 incrementSequenceNumber(resPtr);
4649 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4650 payload, maxAge, qos));
4653 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4655 OCStackResult result = OC_STACK_ERROR;
4656 OCServerRequest *serverRequest = NULL;
4658 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4660 // Validate input parameters
4661 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4662 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4665 // Get pointer to request info
4666 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4669 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4670 result = serverRequest->ehResponseHandler(ehResponse);
4676 //#ifdef DIRECT_PAIRING
4677 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4679 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4680 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4682 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4686 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4689 const OCDPDev_t* OCGetDirectPairedDevices()
4691 return (const OCDPDev_t*)DPGetPairedDevices();
4694 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4695 OCDirectPairingCB resultCallback)
4697 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4698 if(NULL == peer || NULL == pinNumber)
4700 OIC_LOG(ERROR, TAG, "Invalid parameters");
4701 return OC_STACK_INVALID_PARAM;
4703 if (NULL == resultCallback)
4705 OIC_LOG(ERROR, TAG, "Invalid callback");
4706 return OC_STACK_INVALID_CALLBACK;
4709 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4710 pinNumber, (OCDirectPairingResultCB)resultCallback);
4712 //#endif // DIRECT_PAIRING
4714 //-----------------------------------------------------------------------------
4715 // Private internal function definitions
4716 //-----------------------------------------------------------------------------
4717 static OCDoHandle GenerateInvocationHandle()
4719 OCDoHandle handle = NULL;
4720 // Generate token here, it will be deleted when the transaction is deleted
4721 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4724 if (!OCGetRandomBytes((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN])))
4734 #ifdef WITH_PRESENCE
4735 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4736 OCResourceProperty resourceProperties, uint8_t enable)
4740 return OC_STACK_INVALID_PARAM;
4742 if (resourceProperties
4743 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4745 OIC_LOG(ERROR, TAG, "Invalid property");
4746 return OC_STACK_INVALID_PARAM;
4750 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4754 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4760 OCStackResult initResources()
4762 OCStackResult result = OC_STACK_OK;
4764 headResource = NULL;
4765 tailResource = NULL;
4766 // Init Virtual Resources
4767 #ifdef WITH_PRESENCE
4768 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4770 result = OCCreateResource(&presenceResource.handle,
4771 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4773 OC_RSRVD_PRESENCE_URI,
4777 //make resource inactive
4778 result = OCChangeResourceProperty(
4779 &(((OCResource *) presenceResource.handle)->resourceProperties),
4782 #ifndef WITH_ARDUINO
4783 if (result == OC_STACK_OK)
4785 result = SRMInitSecureResources();
4789 if(result == OC_STACK_OK)
4791 result = OCCreateResource(&wellKnownResource,
4792 OC_RSRVD_RESOURCE_TYPE_RES,
4793 OC_RSRVD_INTERFACE_LL,
4794 OC_RSRVD_WELL_KNOWN_URI,
4798 if(result == OC_STACK_OK)
4800 result = BindResourceInterfaceToResource((OCResource *)wellKnownResource,
4801 OC_RSRVD_INTERFACE_DEFAULT);
4805 if(result == OC_STACK_OK)
4807 CreateResetProfile();
4808 result = OCCreateResource(&deviceResource,
4809 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4810 OC_RSRVD_INTERFACE_DEFAULT,
4811 OC_RSRVD_DEVICE_URI,
4815 if(result == OC_STACK_OK)
4817 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4818 OC_RSRVD_INTERFACE_READ);
4822 if(result == OC_STACK_OK)
4824 result = OCCreateResource(&platformResource,
4825 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4826 OC_RSRVD_INTERFACE_DEFAULT,
4827 OC_RSRVD_PLATFORM_URI,
4831 if(result == OC_STACK_OK)
4833 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4834 OC_RSRVD_INTERFACE_READ);
4838 if (result == OC_STACK_OK)
4840 result = OCCreateResource(&introspectionResource,
4841 OC_RSRVD_RESOURCE_TYPE_INTROSPECTION,
4842 OC_RSRVD_INTERFACE_DEFAULT,
4843 OC_RSRVD_INTROSPECTION_URI,
4847 if (result == OC_STACK_OK)
4849 result = BindResourceInterfaceToResource((OCResource *)introspectionResource,
4850 OC_RSRVD_INTERFACE_READ);
4854 if (result == OC_STACK_OK)
4856 result = OCCreateResource(&introspectionPayloadResource,
4857 OC_RSRVD_RESOURCE_TYPE_INTROSPECTION_PAYLOAD,
4858 OC_RSRVD_INTERFACE_DEFAULT,
4859 OC_RSRVD_INTROSPECTION_PAYLOAD_URI,
4863 if (result == OC_STACK_OK)
4865 result = BindResourceInterfaceToResource((OCResource *)introspectionPayloadResource,
4866 OC_RSRVD_INTERFACE_READ);
4870 // Initialize Device Properties
4871 if (OC_STACK_OK == result)
4873 result = InitializeDeviceProperties();
4879 void insertResource(OCResource *resource)
4883 headResource = resource;
4884 tailResource = resource;
4888 tailResource->next = resource;
4889 tailResource = resource;
4891 resource->next = NULL;
4894 OCResource *findResource(OCResource *resource)
4896 OCResource *pointer = headResource;
4900 if (pointer == resource)
4904 pointer = pointer->next;
4909 void deleteAllResources()
4911 OCResource *pointer = headResource;
4912 OCResource *temp = NULL;
4916 temp = pointer->next;
4917 #ifdef WITH_PRESENCE
4918 if (pointer != (OCResource *) presenceResource.handle)
4920 #endif // WITH_PRESENCE
4921 deleteResource(pointer);
4922 #ifdef WITH_PRESENCE
4924 #endif // WITH_PRESENCE
4927 memset(&platformResource, 0, sizeof(platformResource));
4928 memset(&deviceResource, 0, sizeof(deviceResource));
4929 memset(&wellKnownResource, 0, sizeof(wellKnownResource));
4931 memset(&brokerResource, 0, sizeof(brokerResource));
4934 SRMDeInitSecureResources();
4936 #ifdef WITH_PRESENCE
4937 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4938 // presence notification attributed to their deletion to be processed.
4939 deleteResource((OCResource *) presenceResource.handle);
4940 memset(&presenceResource, 0, sizeof(presenceResource));
4941 #endif // WITH_PRESENCE
4944 OCStackResult deleteResource(OCResource *resource)
4946 OCResource *prev = NULL;
4947 OCResource *temp = NULL;
4950 OIC_LOG(DEBUG,TAG,"resource is NULL");
4951 return OC_STACK_INVALID_PARAM;
4954 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4956 temp = headResource;
4959 if (temp == resource)
4961 // Invalidate all Resource Properties.
4962 resource->resourceProperties = (OCResourceProperty) 0;
4963 #ifdef WITH_PRESENCE
4964 if(resource != (OCResource *) presenceResource.handle)
4966 #endif // WITH_PRESENCE
4967 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4968 #ifdef WITH_PRESENCE
4971 if(presenceResource.handle)
4973 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4974 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4977 // Only resource in list.
4978 if (temp == headResource && temp == tailResource)
4980 headResource = NULL;
4981 tailResource = NULL;
4984 else if (temp == headResource)
4986 headResource = temp->next;
4989 else if (temp == tailResource && prev)
4991 tailResource = prev;
4992 tailResource->next = NULL;
4996 prev->next = temp->next;
4999 deleteResourceElements(temp);
5011 return OC_STACK_ERROR;
5014 void deleteResourceElements(OCResource *resource)
5023 OICFree(resource->uri);
5025 if (resource->rsrcType)
5027 deleteResourceType(resource->rsrcType);
5029 if (resource->rsrcInterface)
5031 deleteResourceInterface(resource->rsrcInterface);
5033 if (resource->rsrcChildResourcesHead)
5035 OICFree(resource->rsrcChildResourcesHead);
5037 if (resource->rsrcAttributes)
5039 OCDeleteResourceAttributes(resource->rsrcAttributes);
5043 void deleteResourceType(OCResourceType *resourceType)
5045 OCResourceType *next = NULL;
5047 for (OCResourceType *pointer = resourceType; pointer; pointer = next)
5049 next = pointer->next;
5050 if (pointer->resourcetypename)
5052 OICFree(pointer->resourcetypename);
5058 void deleteResourceInterface(OCResourceInterface *resourceInterface)
5060 OCResourceInterface *next = NULL;
5061 for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
5063 next = pointer->next;
5066 OICFree(pointer->name);
5072 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
5074 OCAttribute *next = NULL;
5075 for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
5077 next = pointer->next;
5078 if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
5080 OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
5082 else if (pointer->attrValue)
5084 OICFree(pointer->attrValue);
5086 if (pointer->attrName)
5088 OICFree(pointer->attrName);
5094 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
5096 OCResourceType *pointer = NULL;
5097 OCResourceType *previous = NULL;
5098 if (!resource || !resourceType)
5102 // resource type list is empty.
5103 else if (!resource->rsrcType)
5105 resource->rsrcType = resourceType;
5109 pointer = resource->rsrcType;
5113 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
5115 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
5116 OICFree(resourceType->resourcetypename);
5117 OICFree(resourceType);
5121 pointer = pointer->next;
5126 previous->next = resourceType;
5129 resourceType->next = NULL;
5131 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
5134 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
5136 OCResource *resource = NULL;
5137 OCResourceType *pointer = NULL;
5139 // Find the specified resource
5140 resource = findResource((OCResource *) handle);
5146 // Make sure a resource has a resourcetype
5147 if (!resource->rsrcType)
5152 // Iterate through the list
5153 pointer = resource->rsrcType;
5154 for(uint8_t i = 0; i< index && pointer; ++i)
5156 pointer = pointer->next;
5161 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
5163 if(resourceTypeList && resourceTypeName)
5165 OCResourceType * rtPointer = resourceTypeList;
5166 while(resourceTypeName && rtPointer)
5168 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
5169 if(rtPointer->resourcetypename &&
5170 strcmp(resourceTypeName, (const char *)
5171 (rtPointer->resourcetypename)) == 0)
5175 rtPointer = rtPointer->next;
5183 * Insert a new interface into interface linked list only if not already present.
5184 * If alredy present, 2nd arg is free'd.
5185 * Default interface will always be first if present.
5187 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
5189 OCResourceInterface *pointer = NULL;
5190 OCResourceInterface *previous = NULL;
5192 newInterface->next = NULL;
5194 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
5196 if (!*firstInterface)
5198 // If first interface is not oic.if.baseline, by default add it as first interface type.
5199 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
5201 *firstInterface = newInterface;
5205 OCStackResult result = BindResourceInterfaceToResource(resource,
5206 OC_RSRVD_INTERFACE_DEFAULT);
5207 if (result != OC_STACK_OK)
5209 OICFree(newInterface->name);
5210 OICFree(newInterface);
5213 if (*firstInterface)
5215 (*firstInterface)->next = newInterface;
5219 // If once add oic.if.baseline, later too below code take care of freeing memory.
5220 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5222 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5224 OICFree(newInterface->name);
5225 OICFree(newInterface);
5228 // This code will not hit anymore, keeping
5231 newInterface->next = *firstInterface;
5232 *firstInterface = newInterface;
5237 pointer = *firstInterface;
5240 if (strcmp(newInterface->name, pointer->name) == 0)
5242 OICFree(newInterface->name);
5243 OICFree(newInterface);
5247 pointer = pointer->next;
5252 previous->next = newInterface;
5257 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
5260 OCResource *resource = NULL;
5261 OCResourceInterface *pointer = NULL;
5263 // Find the specified resource
5264 resource = findResource((OCResource *) handle);
5270 // Make sure a resource has a resourceinterface
5271 if (!resource->rsrcInterface)
5276 // Iterate through the list
5277 pointer = resource->rsrcInterface;
5279 for (uint8_t i = 0; i < index && pointer; ++i)
5281 pointer = pointer->next;
5287 * This function splits the uri using the '?' delimiter.
5288 * "uriWithoutQuery" is the block of characters between the beginning
5289 * till the delimiter or '\0' which ever comes first.
5290 * "query" is whatever is to the right of the delimiter if present.
5291 * No delimiter sets the query to NULL.
5292 * If either are present, they will be malloc'ed into the params 2, 3.
5293 * The first param, *uri is left untouched.
5295 * NOTE: This function does not account for whitespace at the end of the uri NOR
5296 * malformed uri's with '??'. Whitespace at the end will be assumed to be
5297 * part of the query.
5299 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
5303 return OC_STACK_INVALID_URI;
5305 if(!query || !uriWithoutQuery)
5307 return OC_STACK_INVALID_PARAM;
5311 *uriWithoutQuery = NULL;
5313 size_t uriWithoutQueryLen = 0;
5314 size_t queryLen = 0;
5315 size_t uriLen = strlen(uri);
5317 char *pointerToDelimiter = strstr(uri, "?");
5319 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
5320 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
5322 if (uriWithoutQueryLen)
5324 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
5325 if (!*uriWithoutQuery)
5329 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
5333 *query = (char *) OICCalloc(queryLen + 1, 1);
5336 OICFree(*uriWithoutQuery);
5337 *uriWithoutQuery = NULL;
5340 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5346 return OC_STACK_NO_MEMORY;
5349 static const OicUuid_t* OCGetServerInstanceID(void)
5351 static bool generated = false;
5352 static OicUuid_t sid;
5358 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5360 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
5367 const char* OCGetServerInstanceIDString(void)
5369 static bool generated = false;
5370 static char sidStr[UUID_STRING_SIZE];
5377 const OicUuid_t *sid = OCGetServerInstanceID();
5378 if(sid && !OCConvertUuidToString(sid->id, sidStr))
5380 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5388 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5390 OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5391 CAResult_t retResult = CA_STATUS_FAILED;
5392 CAResult_t caResult = CA_STATUS_OK;
5394 CATransportAdapter_t connTypes[] = {
5396 CA_ADAPTER_RFCOMM_BTEDR,
5397 CA_ADAPTER_GATT_BTLE,
5400 ,CA_ADAPTER_REMOTE_ACCESS
5407 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5409 for(int i = 0; i < numConnTypes; i++)
5411 // If CA status is not initialized, CASelectNetwork() will not be called.
5412 if (caResult != CA_STATUS_NOT_INITIALIZED)
5414 if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5416 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5417 caResult = CASelectNetwork(connTypes[i]);
5418 if (caResult == CA_STATUS_OK)
5420 retResult = CA_STATUS_OK;
5425 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5430 if (retResult != CA_STATUS_OK)
5432 return caResult; // Returns error of appropriate transport that failed fatally.
5438 OCStackResult CAResultToOCResult(CAResult_t caResult)
5444 case CA_STATUS_INVALID_PARAM:
5445 return OC_STACK_INVALID_PARAM;
5446 case CA_ADAPTER_NOT_ENABLED:
5447 return OC_STACK_ADAPTER_NOT_ENABLED;
5448 case CA_SERVER_STARTED_ALREADY:
5450 case CA_SERVER_NOT_STARTED:
5451 return OC_STACK_ERROR;
5452 case CA_DESTINATION_NOT_REACHABLE:
5453 return OC_STACK_COMM_ERROR;
5454 case CA_SOCKET_OPERATION_FAILED:
5455 return OC_STACK_COMM_ERROR;
5456 case CA_SEND_FAILED:
5457 return OC_STACK_COMM_ERROR;
5458 case CA_RECEIVE_FAILED:
5459 return OC_STACK_COMM_ERROR;
5460 case CA_MEMORY_ALLOC_FAILED:
5461 return OC_STACK_NO_MEMORY;
5462 case CA_REQUEST_TIMEOUT:
5463 return OC_STACK_TIMEOUT;
5464 case CA_DESTINATION_DISCONNECTED:
5465 return OC_STACK_COMM_ERROR;
5466 case CA_STATUS_FAILED:
5467 return OC_STACK_ERROR;
5468 case CA_NOT_SUPPORTED:
5469 return OC_STACK_NOTIMPL;
5471 return OC_STACK_ERROR;
5475 bool OCResultToSuccess(OCStackResult ocResult)
5480 case OC_STACK_RESOURCE_CREATED:
5481 case OC_STACK_RESOURCE_DELETED:
5482 case OC_STACK_CONTINUE:
5483 case OC_STACK_RESOURCE_CHANGED:
5484 case OC_STACK_SLOW_RESOURCE:
5491 OCStackResult OCSetProxyURI(const char *uri)
5493 return CAResultToOCResult(CASetProxyUri(uri));
5496 #if defined(RD_CLIENT) || defined(RD_SERVER)
5497 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5499 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5501 OCResource *resource = NULL;
5503 resource = findResource((OCResource *) handle);
5506 OIC_LOG(ERROR, TAG, "Resource not found");
5507 return OC_STACK_ERROR;
5510 resource->ins = ins;
5515 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5516 const OCClientResponse *response)
5518 // Validate input parameters
5519 VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5520 VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5522 char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5525 return OC_STACK_NO_MEMORY;
5527 strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5529 if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5531 OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5533 char rdPubUri[MAX_URI_LENGTH] = { 0 };
5534 snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5535 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5537 if (strcmp(rdPubUri, targetUri) == 0)
5539 // Update resource unique id in stack.
5542 if (response->payload)
5544 OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5545 OCRepPayload **links = NULL;
5546 size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5547 if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5548 &links, dimensions))
5551 for (; i < dimensions[0]; i++)
5554 if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5556 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5558 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5560 OCBindResourceInsToResource(handle, ins);
5569 else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5571 OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5573 uint8_t numResources = 0;
5574 OCGetNumberOfResources(&numResources);
5576 char *ins = strstr(targetUri, OC_RSRVD_INS);
5579 for (uint8_t i = 0; i < numResources; i++)
5581 OCResourceHandle resHandle = OCGetResourceHandle(i);
5584 OCBindResourceInsToResource(resHandle, 0);
5590 const char *token = "&";
5591 char *iterTokenPtr = NULL;
5592 char *start = strtok_r(targetUri, token, &iterTokenPtr);
5594 while (start != NULL)
5596 char *query = start;
5597 query = strstr(query, OC_RSRVD_INS);
5600 // Arduino's AVR-GCC doesn't support strtoll().
5602 int matchedItems = sscanf(query + 4, "%lld", &queryIns);
5604 if (0 == matchedItems)
5607 return OC_STACK_INVALID_QUERY;
5610 for (uint8_t i = 0; i < numResources; i++)
5612 OCResourceHandle resHandle = OCGetResourceHandle(i);
5616 OCGetResourceIns(resHandle, &resIns);
5617 if (queryIns && queryIns == resIns)
5619 OCBindResourceInsToResource(resHandle, 0);
5625 start = strtok_r(NULL, token, &iterTokenPtr);
5634 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t* ins)
5636 OCResource *resource = NULL;
5638 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5639 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5641 resource = findResource((OCResource *) handle);
5644 *ins = resource->ins;
5647 return OC_STACK_ERROR;
5649 #endif // RD_CLIENT || RD_SERVER
5651 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5655 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5659 OCResource *pointer = headResource;
5663 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5665 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5668 pointer = pointer->next;
5673 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5674 void* optionData, size_t optionDataLength)
5678 OIC_LOG (INFO, TAG, "Header options are NULL");
5679 return OC_STACK_INVALID_PARAM;
5684 OIC_LOG (INFO, TAG, "optionData are NULL");
5685 return OC_STACK_INVALID_PARAM;
5690 OIC_LOG (INFO, TAG, "numOptions is NULL");
5691 return OC_STACK_INVALID_PARAM;
5694 if (*numOptions >= MAX_HEADER_OPTIONS)
5696 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5697 return OC_STACK_NO_MEMORY;
5700 ocHdrOpt += *numOptions;
5701 ocHdrOpt->protocolID = OC_COAP_ID;
5702 ocHdrOpt->optionID = optionID;
5703 ocHdrOpt->optionLength =
5704 (optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH) ?
5705 (uint16_t)optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5706 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5712 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions,
5713 uint16_t optionID, void* optionData, size_t optionDataLength,
5714 uint16_t* receivedDataLength)
5716 if (!ocHdrOpt || !numOptions)
5718 OIC_LOG (INFO, TAG, "No options present");
5724 OIC_LOG (INFO, TAG, "optionData are NULL");
5725 return OC_STACK_INVALID_PARAM;
5728 if (!receivedDataLength)
5730 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5731 return OC_STACK_INVALID_PARAM;
5734 for (uint8_t i = 0; i < numOptions; i++)
5736 if (ocHdrOpt[i].optionID == optionID)
5738 if (optionDataLength >= ocHdrOpt->optionLength)
5740 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5741 *receivedDataLength = ocHdrOpt->optionLength;
5746 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5747 return OC_STACK_ERROR;
5754 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5756 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5757 if (g_adapterHandler)
5759 g_adapterHandler(adapter, enabled);
5763 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5765 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5766 if (g_connectionHandler)
5768 g_connectionHandler(info, isConnected);
5772 * If the client observes one or more resources over a reliable connection,
5773 * then the CoAP server (or intermediary in the role of the CoAP server)
5774 * MUST remove all entries associated with the client endpoint from the lists
5775 * of observers when the connection is either closed or times out.
5779 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5780 CopyEndpointToDevAddr(info, &devAddr);
5782 // remove observer list with remote device address.
5783 DeleteObserverUsingDevAddr(&devAddr);
5787 void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
5788 CAConnectionStateChangedCB connectionHandler)
5790 OIC_LOG(DEBUG, TAG, "OCSetNetworkMonitorHandler");
5791 g_adapterHandler = adapterHandler;
5792 g_connectionHandler = connectionHandler;
5795 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5798 OCStackResult ret = OC_STACK_ERROR;
5800 ret = GetDoxmDeviceID(&oicUuid);
5801 if (OC_STACK_OK == ret)
5803 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5807 OIC_LOG(ERROR, TAG, "Device ID Get error");
5812 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5815 OCStackResult ret = OC_STACK_ERROR;
5817 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5818 for (int i = 0; i < UUID_LENGTH; i++)
5820 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5822 ret = SetDoxmDeviceID(&oicUuid);
5826 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5828 bool isDeviceOwned = true;
5829 OCStackResult ret = OC_STACK_ERROR;
5831 ret = GetDoxmIsOwned(&isDeviceOwned);
5832 if (OC_STACK_OK == ret)
5834 *isOwned = isDeviceOwned;
5838 OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5843 OCStackResult OCGetLinkLocalZoneId(uint32_t ifindex, char **zoneId)
5845 return CAResultToOCResult(CAGetLinkLocalZoneId(ifindex, zoneId));