1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //-----------------------------------------------------------------------------
24 //-----------------------------------------------------------------------------
26 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
27 // causes header files to expose definitions
28 // corresponding to the POSIX.1-2001 base
29 // specification (excluding the XSI extension).
30 // For POSIX.1-2001 base specification,
31 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
32 #define _POSIX_C_SOURCE 200112L
33 #ifndef __STDC_FORMAT_MACROS
34 #define __STDC_FORMAT_MACROS
36 #ifndef __STDC_LIMIT_MACROS
37 #define __STDC_LIMIT_MACROS
39 #include "iotivity_config.h"
45 #include "ocstackinternal.h"
46 #include "ocresourcehandler.h"
47 #include "occlientcb.h"
48 #include "ocobserve.h"
50 #include "oic_malloc.h"
51 #include "oic_string.h"
53 #include "ocserverrequest.h"
54 #include "secureresourcemanager.h"
55 #include "psinterface.h"
56 #include "doxmresource.h"
58 #include "cainterface.h"
59 #include "ocpayload.h"
60 #include "ocpayloadcbor.h"
61 #include "cautilinterface.h"
64 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
65 #include "routingutility.h"
66 #ifdef ROUTING_GATEWAY
67 #include "routingmanager.h"
72 #include "oickeepalive.h"
75 //#ifdef DIRECT_PAIRING
76 #include "directpairing.h"
79 #ifdef HAVE_ARDUINO_TIME_H
82 #ifdef HAVE_SYS_TIME_H
85 #include <coap/coap.h>
87 #ifdef HAVE_ARPA_INET_H
88 #include <arpa/inet.h>
92 #define UINT32_MAX (0xFFFFFFFFUL)
95 //-----------------------------------------------------------------------------
97 //-----------------------------------------------------------------------------
100 OC_STACK_UNINITIALIZED = 0,
101 OC_STACK_INITIALIZED,
102 OC_STACK_UNINIT_IN_PROGRESS
108 OC_PRESENCE_UNINITIALIZED = 0,
109 OC_PRESENCE_INITIALIZED
113 //-----------------------------------------------------------------------------
115 //-----------------------------------------------------------------------------
116 static OCStackState stackState = OC_STACK_UNINITIALIZED;
118 OCResource *headResource = NULL;
119 static OCResource *tailResource = NULL;
120 static OCResourceHandle platformResource = {0};
121 static OCResourceHandle deviceResource = {0};
123 static OCResourceHandle brokerResource = {0};
127 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
128 static PresenceResource presenceResource = {0};
129 static uint8_t PresenceTimeOutSize = 0;
130 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
133 static OCMode myStackMode;
135 //TODO: revisit this design
136 static bool gRASetInfo = false;
138 OCDeviceEntityHandler defaultDeviceHandler;
139 void* defaultDeviceHandlerCallbackParameter = NULL;
140 static const char COAP_TCP_SCHEME[] = "coap+tcp:";
141 static const char COAPS_TCP_SCHEME[] = "coaps+tcp:";
142 static const char CORESPEC[] = "core";
144 CAAdapterStateChangedCB g_adapterHandler = NULL;
145 CAConnectionStateChangedCB g_connectionHandler = NULL;
147 //-----------------------------------------------------------------------------
149 //-----------------------------------------------------------------------------
150 #define TAG "OIC_RI_STACK"
151 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
152 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
153 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
154 TAG, #arg " is NULL"); return (retVal); } }
155 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
156 TAG, #arg " is NULL"); return; } }
157 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
160 //TODO: we should allow the server to define this
161 #define MAX_OBSERVE_AGE (0x2FFFFUL)
163 #define MILLISECONDS_PER_SECOND (1000)
165 //-----------------------------------------------------------------------------
166 // Private internal function prototypes
167 //-----------------------------------------------------------------------------
170 * Generate handle of OCDoResource invocation for callback management.
172 * @return Generated OCDoResource handle.
174 static OCDoHandle GenerateInvocationHandle();
177 * Initialize resource data structures, variables, etc.
179 * @return ::OC_STACK_OK on success, some other value upon failure.
181 static OCStackResult initResources();
184 * Add a resource to the end of the linked list of resources.
186 * @param resource Resource to be added
188 static void insertResource(OCResource *resource);
191 * Find a resource in the linked list of resources.
193 * @param resource Resource to be found.
194 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
197 static OCResource *findResource(OCResource *resource);
200 * Insert a resource type into a resource's resource type linked list.
201 * If resource type already exists, it will not be inserted and the
202 * resourceType will be free'd.
203 * resourceType->next should be null to avoid memory leaks.
204 * Function returns silently for null args.
206 * @param resource Resource where resource type is to be inserted.
207 * @param resourceType Resource type to be inserted.
209 static void insertResourceType(OCResource *resource,
210 OCResourceType *resourceType);
213 * Get a resource type at the specified index within a resource.
215 * @param handle Handle of resource.
216 * @param index Index of resource type.
218 * @return Pointer to resource type if found, NULL otherwise.
220 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
224 * Insert a resource interface into a resource's resource interface linked list.
225 * If resource interface already exists, it will not be inserted and the
226 * resourceInterface will be free'd.
227 * resourceInterface->next should be null to avoid memory leaks.
229 * @param resource Resource where resource interface is to be inserted.
230 * @param resourceInterface Resource interface to be inserted.
232 static void insertResourceInterface(OCResource *resource,
233 OCResourceInterface *resourceInterface);
236 * Get a resource interface at the specified index within a resource.
238 * @param handle Handle of resource.
239 * @param index Index of resource interface.
241 * @return Pointer to resource interface if found, NULL otherwise.
243 static OCResourceInterface *findResourceInterfaceAtIndex(
244 OCResourceHandle handle, uint8_t index);
247 * Delete all of the dynamically allocated elements that were created for the resource type.
249 * @param resourceType Specified resource type.
251 static void deleteResourceType(OCResourceType *resourceType);
254 * Delete all of the dynamically allocated elements that were created for the resource interface.
256 * @param resourceInterface Specified resource interface.
258 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
261 * Delete all of the dynamically allocated elements that were created for the resource.
263 * @param resource Specified resource.
265 static void deleteResourceElements(OCResource *resource);
268 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
271 * @param handle Handle of resource to be deleted.
273 * @return ::OC_STACK_OK on success, some other value upon failure.
275 static OCStackResult deleteResource(OCResource *resource);
278 * Delete all of the resources in the resource list.
280 static void deleteAllResources();
283 * Increment resource sequence number. Handles rollover.
285 * @param resPtr Pointer to resource.
287 static void incrementSequenceNumber(OCResource * resPtr);
290 * Attempts to initialize every network interface that the CA Layer might have compiled in.
292 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
293 * return something other than @ref CA_STATUS_OK, then this function fails.
295 * @return ::CA_STATUS_OK on success, some other value upon failure.
297 static CAResult_t OCSelectNetwork();
300 * Get the CoAP ticks after the specified number of milli-seconds.
302 * @param afterMilliSeconds Milli-seconds.
306 static uint32_t GetTicks(uint32_t afterMilliSeconds);
309 * Convert CAResult_t to OCStackResult.
311 * @param caResult CAResult_t code.
312 * @return ::OC_STACK_OK on success, some other value upon failure.
314 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
317 * Convert CAResponseResult_t to OCStackResult.
319 * @param caCode CAResponseResult_t code.
320 * @return ::OC_STACK_OK on success, some other value upon failure.
322 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
325 * Convert OCStackResult to CAResponseResult_t.
327 * @param caCode OCStackResult code.
328 * @param method OCMethod method the return code replies to.
329 * @return ::CA_CONTENT on OK, some other value upon failure.
331 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
334 * Convert OCTransportFlags_t to CATransportModifiers_t.
336 * @param ocConType OCTransportFlags_t input.
337 * @return CATransportFlags
339 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
342 * Convert CATransportFlags_t to OCTransportModifiers_t.
344 * @param caConType CATransportFlags_t input.
345 * @return OCTransportFlags
347 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
350 * Handle response from presence request.
352 * @param endPoint CA remote endpoint.
353 * @param responseInfo CA response info.
354 * @return ::OC_STACK_OK on success, some other value upon failure.
356 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
357 const CAResponseInfo_t *responseInfo);
360 * This function will be called back by CA layer when a response is received.
362 * @param endPoint CA remote endpoint.
363 * @param responseInfo CA response info.
365 static void HandleCAResponses(const CAEndpoint_t* endPoint,
366 const CAResponseInfo_t* responseInfo);
369 * This function will be called back by CA layer when a request is received.
371 * @param endPoint CA remote endpoint.
372 * @param requestInfo CA request info.
374 static void HandleCARequests(const CAEndpoint_t* endPoint,
375 const CARequestInfo_t* requestInfo);
378 * Extract query from a URI.
380 * @param uri Full URI with query.
381 * @param query Pointer to string that will contain query.
382 * @param newURI Pointer to string that will contain URI.
383 * @return ::OC_STACK_OK on success, some other value upon failure.
385 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
388 * Finds a resource type in an OCResourceType link-list.
390 * @param resourceTypeList The link-list to be searched through.
391 * @param resourceTypeName The key to search for.
393 * @return Resource type that matches the key (ie. resourceTypeName) or
394 * NULL if there is either an invalid parameter or this function was unable to find the key.
396 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
397 const char * resourceTypeName);
400 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
401 * TTL will be set to maxAge.
403 * @param cbNode Callback Node for which presence ttl is to be reset.
404 * @param maxAge New value of ttl in seconds.
406 * @return ::OC_STACK_OK on success, some other value upon failure.
408 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
411 * Ensure the accept header option is set appropriatly before sending the requests and routing
412 * header option is updated with destination.
414 * @param object CA remote endpoint.
415 * @param requestInfo CA request info.
417 * @return ::OC_STACK_OK on success, some other value upon failure.
419 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
422 * default adapter state change callback method
424 * @param adapter CA network adapter type.
425 * @param enabled current adapter state.
427 static void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled);
430 * default connection state change callback method
432 * @param info CAEndpoint which has address, port and etc.
433 * @param isConnected current connection state.
435 static void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected);
438 * Register network monitoring callback.
439 * Network status changes are delivered these callback.
440 * @param adapterHandler Adapter state monitoring callback.
441 * @param connectionHandler Connection state monitoring callback.
443 static void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
444 CAConnectionStateChangedCB connectionHandler);
446 //-----------------------------------------------------------------------------
447 // Internal functions
448 //-----------------------------------------------------------------------------
450 bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
452 if (!options || 0 == numOptions)
454 OIC_LOG (INFO, TAG, "No options present");
458 for (uint8_t i = 0; i < numOptions; i++)
460 if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
462 OIC_LOG(DEBUG, TAG, "Proxy URI is present");
469 uint32_t GetTicks(uint32_t afterMilliSeconds)
474 // Guard against overflow of uint32_t
475 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
476 COAP_TICKS_PER_SECOND)
478 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
486 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
488 VERIFY_NON_NULL_NR(in, FATAL);
489 VERIFY_NON_NULL_NR(out, FATAL);
491 out->adapter = (OCTransportAdapter)in->adapter;
492 out->flags = CAToOCTransportFlags(in->flags);
493 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
494 out->port = in->port;
495 out->ifindex = in->ifindex;
496 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
497 /* This assert is to prevent accidental mismatch between address size macros defined in
498 * RI and CA and cause crash here. */
499 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
500 "Address size mismatch between RI and CA");
501 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
505 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
507 VERIFY_NON_NULL_NR(in, FATAL);
508 VERIFY_NON_NULL_NR(out, FATAL);
510 out->adapter = (CATransportAdapter_t)in->adapter;
511 out->flags = OCToCATransportFlags(in->flags);
512 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
513 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
514 /* This assert is to prevent accidental mismatch between address size macros defined in
515 * RI and CA and cause crash here. */
516 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
517 "Address size mismatch between RI and CA");
518 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
520 out->port = in->port;
521 out->ifindex = in->ifindex;
524 void FixUpClientResponse(OCClientResponse *cr)
526 VERIFY_NON_NULL_NR(cr, FATAL);
528 cr->addr = &cr->devAddr;
529 cr->connType = (OCConnectivityType)
530 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
533 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
535 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
536 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
538 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
539 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
540 if (OC_STACK_OK != rmResult)
542 OIC_LOG(ERROR, TAG, "Add destination option failed");
547 // OC stack prefer CBOR encoded payloads.
548 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
549 CAResult_t result = CASendRequest(object, requestInfo);
550 if(CA_STATUS_OK != result)
552 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
553 return CAResultToOCResult(result);
557 //-----------------------------------------------------------------------------
558 // Internal API function
559 //-----------------------------------------------------------------------------
561 // This internal function is called to update the stack with the status of
562 // observers and communication failures
563 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
565 OCStackResult result = OC_STACK_ERROR;
566 ResourceObserver * observer = NULL;
567 OCEntityHandlerRequest ehRequest = {0};
571 case OC_OBSERVER_NOT_INTERESTED:
572 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
573 observer = GetObserverUsingToken (token, tokenLength);
576 result = FormOCEntityHandlerRequest(&ehRequest,
577 (OCRequestHandle)NULL,
580 (OCResourceHandle)NULL,
581 NULL, PAYLOAD_TYPE_REPRESENTATION,
583 OC_OBSERVE_DEREGISTER,
586 if(result != OC_STACK_OK)
590 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
591 observer->resource->entityHandlerCallbackParam);
594 result = DeleteObserverUsingToken (token, tokenLength);
595 if(result == OC_STACK_OK)
597 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
601 result = OC_STACK_OK;
602 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
606 case OC_OBSERVER_STILL_INTERESTED:
607 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
608 observer = GetObserverUsingToken (token, tokenLength);
611 observer->forceHighQos = 0;
612 observer->failedCommCount = 0;
613 result = OC_STACK_OK;
617 result = OC_STACK_OBSERVER_NOT_FOUND;
621 case OC_OBSERVER_FAILED_COMM:
622 OIC_LOG(DEBUG, TAG, "observer is unreachable");
623 observer = GetObserverUsingToken (token, tokenLength);
626 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
628 result = FormOCEntityHandlerRequest(&ehRequest,
629 (OCRequestHandle)NULL,
632 (OCResourceHandle)NULL,
633 NULL, PAYLOAD_TYPE_REPRESENTATION,
635 OC_OBSERVE_DEREGISTER,
638 if(result != OC_STACK_OK)
640 return OC_STACK_ERROR;
642 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
643 observer->resource->entityHandlerCallbackParam);
645 result = DeleteObserverUsingToken (token, tokenLength);
646 if(result == OC_STACK_OK)
648 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
652 result = OC_STACK_OK;
653 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
658 observer->failedCommCount++;
659 result = OC_STACK_CONTINUE;
661 observer->forceHighQos = 1;
662 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
666 OIC_LOG(ERROR, TAG, "Unknown status");
667 result = OC_STACK_ERROR;
673 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
675 OCStackResult ret = OC_STACK_ERROR;
679 case CA_ADAPTER_NOT_ENABLED:
680 case CA_SERVER_NOT_STARTED:
681 ret = OC_STACK_ADAPTER_NOT_ENABLED;
683 case CA_MEMORY_ALLOC_FAILED:
684 ret = OC_STACK_NO_MEMORY;
686 case CA_STATUS_INVALID_PARAM:
687 ret = OC_STACK_INVALID_PARAM;
695 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
697 OCStackResult ret = OC_STACK_ERROR;
701 ret = OC_STACK_RESOURCE_CREATED;
704 ret = OC_STACK_RESOURCE_DELETED;
707 ret = OC_STACK_RESOURCE_CHANGED;
714 ret = OC_STACK_INVALID_QUERY;
716 case CA_UNAUTHORIZED_REQ:
717 ret = OC_STACK_UNAUTHORIZED_REQ;
720 ret = OC_STACK_INVALID_OPTION;
723 ret = OC_STACK_NO_RESOURCE;
725 case CA_RETRANSMIT_TIMEOUT:
726 ret = OC_STACK_COMM_ERROR;
728 case CA_REQUEST_ENTITY_TOO_LARGE:
729 ret = OC_STACK_TOO_LARGE_REQ;
737 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
739 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
748 // This Response Code is like HTTP 204 "No Content" but only used in
749 // response to POST and PUT requests.
753 // This Response Code is like HTTP 200 "OK" but only used in response to
758 // This should not happen but,
759 // give it a value just in case but output an error
761 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
765 case OC_STACK_RESOURCE_CREATED:
768 case OC_STACK_RESOURCE_DELETED:
771 case OC_STACK_RESOURCE_CHANGED:
774 case OC_STACK_INVALID_QUERY:
777 case OC_STACK_INVALID_OPTION:
780 case OC_STACK_NO_RESOURCE:
783 case OC_STACK_COMM_ERROR:
784 ret = CA_RETRANSMIT_TIMEOUT;
786 case OC_STACK_UNAUTHORIZED_REQ:
787 ret = CA_UNAUTHORIZED_REQ;
795 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
797 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
799 // supply default behavior.
800 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
802 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
804 if ((caFlags & OC_MASK_SCOPE) == 0)
806 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
811 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
813 return (OCTransportFlags)caFlags;
816 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
818 uint32_t lowerBound = 0;
819 uint32_t higherBound = 0;
821 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
823 return OC_STACK_INVALID_PARAM;
826 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
828 cbNode->presence->TTL = maxAgeSeconds;
830 for (int index = 0; index < PresenceTimeOutSize; index++)
832 // Guard against overflow
833 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
836 lowerBound = GetTicks((PresenceTimeOut[index] *
837 cbNode->presence->TTL *
838 MILLISECONDS_PER_SECOND)/100);
842 lowerBound = GetTicks(UINT32_MAX);
845 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
848 higherBound = GetTicks((PresenceTimeOut[index + 1] *
849 cbNode->presence->TTL *
850 MILLISECONDS_PER_SECOND)/100);
854 higherBound = GetTicks(UINT32_MAX);
857 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
859 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
860 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
861 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
864 cbNode->presence->TTLlevel = 0;
866 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
870 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
872 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
874 return OC_RSRVD_TRIGGER_CREATE;
876 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
878 return OC_RSRVD_TRIGGER_CHANGE;
882 return OC_RSRVD_TRIGGER_DELETE;
886 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
890 return OC_PRESENCE_TRIGGER_CREATE;
892 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
894 return OC_PRESENCE_TRIGGER_CREATE;
896 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
898 return OC_PRESENCE_TRIGGER_CHANGE;
902 return OC_PRESENCE_TRIGGER_DELETE;
907 * Encode an address string to match RFC 6874.
909 * @param outputAddress a char array to be written with the encoded string.
911 * @param outputSize size of outputAddress buffer.
913 * @param inputAddress a char array of size <= CA_MAX_URI_LENGTH
914 * containing a valid IPv6 address string.
916 * @return OC_STACK_OK if encoding succeeded.
917 * Else an error occured.
919 OCStackResult encodeAddressForRFC6874(char *outputAddress,
921 const char *inputAddress)
923 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
924 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
926 size_t inputLength = strnlen(inputAddress, outputSize);
928 // inputSize includes the null terminator
929 size_t inputSize = inputLength + 1;
931 if (inputSize > outputSize)
933 OIC_LOG_V(ERROR, TAG,
934 "encodeAddressForRFC6874 failed: "
935 "outputSize (%zu) < inputSize (%zu)",
936 outputSize, inputSize);
938 return OC_STACK_ERROR;
941 char* percentChar = strchr(inputAddress, '%');
943 // If there is no '%' character, then no change is required to the string.
944 if (NULL == percentChar)
946 OICStrcpy(outputAddress, outputSize, inputAddress);
950 const char* addressPart = &inputAddress[0];
951 const char* scopeIdPart = percentChar + 1;
953 // Sanity check to make sure this string doesn't have more '%' characters
954 if (NULL != strchr(scopeIdPart, '%'))
956 return OC_STACK_ERROR;
959 // If no string follows the first '%', then the input was invalid.
960 if (scopeIdPart[0] == '\0')
962 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
963 return OC_STACK_ERROR;
966 // Check to see if the string is already encoded
967 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
969 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
970 return OC_STACK_ERROR;
973 // Fail if we don't have room for encoded string's two additional chars
974 if (outputSize < (inputSize + 2))
976 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: encoded output will not fit!");
977 return OC_STACK_ERROR;
980 // Restore the null terminator with an escaped '%' character, per RFC 6874
981 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
982 strcat(outputAddress, "%25");
983 strcat(outputAddress, scopeIdPart);
989 * The cononical presence allows constructed URIs to be string compared.
991 * requestUri must be a char array of size CA_MAX_URI_LENGTH
993 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
994 char *presenceUri, bool isMulticast)
996 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
997 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
998 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1002 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1003 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1006 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1007 if (ep->adapter == CA_ADAPTER_IP)
1009 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1011 if ('\0' == ep->addr[0]) // multicast
1013 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1017 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1019 OCStackResult result = encodeAddressForRFC6874(addressEncoded,
1020 sizeof(addressEncoded),
1023 if (OC_STACK_OK != result)
1028 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1029 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1034 if ('\0' == ep->addr[0]) // multicast
1036 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1037 ep->port = OC_MULTICAST_PORT;
1039 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1040 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1044 // might work for other adapters (untested, but better than nothing)
1045 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1046 OC_RSRVD_PRESENCE_URI);
1050 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1051 const CAResponseInfo_t *responseInfo)
1053 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1054 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1056 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1057 ClientCB * cbNode = NULL;
1058 char *resourceTypeName = NULL;
1059 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1060 OCStackResult result = OC_STACK_ERROR;
1061 uint32_t maxAge = 0;
1063 char presenceUri[CA_MAX_URI_LENGTH];
1065 int presenceSubscribe = 0;
1066 int multicastPresenceSubscribe = 0;
1068 if (responseInfo->result != CA_CONTENT)
1070 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1071 return OC_STACK_ERROR;
1074 response.payload = NULL;
1075 response.result = OC_STACK_OK;
1077 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1078 FixUpClientResponse(&response);
1080 if (responseInfo->info.payload)
1082 result = OCParsePayload(&response.payload,
1083 PAYLOAD_TYPE_PRESENCE,
1084 responseInfo->info.payload,
1085 responseInfo->info.payloadSize);
1087 if(result != OC_STACK_OK)
1089 OIC_LOG(ERROR, TAG, "Presence parse failed");
1092 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1094 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1095 result = OC_STACK_ERROR;
1098 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1099 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1100 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1103 // check for unicast presence
1104 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri,
1105 responseInfo->isMulticast);
1106 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1108 return OC_STACK_INVALID_URI;
1110 OIC_LOG(ERROR, TAG, "check for unicast presence");
1111 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1114 presenceSubscribe = 1;
1118 // check for multicast presence
1119 OIC_LOG(ERROR, TAG, "check for multicast presence");
1120 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1123 multicastPresenceSubscribe = 1;
1127 if (!presenceSubscribe && !multicastPresenceSubscribe)
1129 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1133 if (presenceSubscribe)
1135 if(cbNode->sequenceNumber == response.sequenceNumber)
1137 OIC_LOG(INFO, TAG, "No presence change");
1138 ResetPresenceTTL(cbNode, maxAge);
1139 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1145 OIC_LOG(INFO, TAG, "Stopping presence");
1146 response.result = OC_STACK_PRESENCE_STOPPED;
1147 if(cbNode->presence)
1149 OICFree(cbNode->presence->timeOut);
1150 OICFree(cbNode->presence);
1151 cbNode->presence = NULL;
1156 if(!cbNode->presence)
1158 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1160 if(!(cbNode->presence))
1162 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1163 result = OC_STACK_NO_MEMORY;
1167 VERIFY_NON_NULL_V(cbNode->presence);
1168 cbNode->presence->timeOut = NULL;
1169 cbNode->presence->timeOut = (uint32_t *)
1170 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1171 if(!(cbNode->presence->timeOut)){
1173 "Could not allocate memory for cbNode->presence->timeOut");
1174 OICFree(cbNode->presence);
1175 result = OC_STACK_NO_MEMORY;
1180 ResetPresenceTTL(cbNode, maxAge);
1182 cbNode->sequenceNumber = response.sequenceNumber;
1184 // Ensure that a filter is actually applied.
1185 if( resourceTypeName && cbNode->filterResourceType)
1187 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1196 // This is the multicast case
1197 OCMulticastNode* mcNode = NULL;
1198 mcNode = GetMCPresenceNode(presenceUri);
1202 if(mcNode->nonce == response.sequenceNumber)
1204 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1207 mcNode->nonce = response.sequenceNumber;
1211 OIC_LOG(INFO, TAG, "Stopping presence");
1212 response.result = OC_STACK_PRESENCE_STOPPED;
1217 char* uri = OICStrdup(presenceUri);
1221 "No Memory for URI to store in the presence node");
1222 result = OC_STACK_NO_MEMORY;
1226 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1227 if(result == OC_STACK_NO_MEMORY)
1230 "No Memory for Multicast Presence Node");
1234 // presence node now owns uri
1239 // Ensure that a filter is actually applied.
1240 if(resourceTypeName && cbNode->filterResourceType)
1242 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1243 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1249 OIC_LOG(INFO, TAG, "Callback for presence");
1251 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1253 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1255 FindAndDeleteClientCB(cbNode);
1259 OCPayloadDestroy(response.payload);
1263 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1265 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1267 if(responseInfo->info.resourceUri &&
1268 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1270 HandlePresenceResponse(endPoint, responseInfo);
1274 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1275 responseInfo->info.tokenLength, NULL, NULL);
1277 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1278 responseInfo->info.tokenLength);
1282 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1283 if(responseInfo->result == CA_EMPTY)
1285 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1286 // We do not have a case for the client to receive a RESET
1287 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1289 //This is the case of receiving an ACK on a request to a slow resource!
1290 OIC_LOG(INFO, TAG, "This is a pure ACK");
1291 //TODO: should we inform the client
1292 // app that at least the request was received at the server?
1295 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1297 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1298 OIC_LOG(INFO, TAG, "Calling into application address space");
1300 OCClientResponse response =
1301 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1302 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1303 FixUpClientResponse(&response);
1304 response.resourceUri = responseInfo->info.resourceUri;
1305 memcpy(response.identity.id, responseInfo->info.identity.id,
1306 sizeof (response.identity.id));
1307 response.identity.id_length = responseInfo->info.identity.id_length;
1309 response.result = CAResponseToOCStackResult(responseInfo->result);
1310 cbNode->callBack(cbNode->context,
1311 cbNode->handle, &response);
1312 FindAndDeleteClientCB(cbNode);
1316 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1317 OIC_LOG(INFO, TAG, "Calling into application address space");
1319 OCClientResponse response =
1320 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1321 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1322 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1323 FixUpClientResponse(&response);
1324 response.resourceUri = responseInfo->info.resourceUri;
1325 memcpy(response.identity.id, responseInfo->info.identity.id,
1326 sizeof (response.identity.id));
1327 response.identity.id_length = responseInfo->info.identity.id_length;
1329 response.result = CAResponseToOCStackResult(responseInfo->result);
1331 if(responseInfo->info.payload &&
1332 responseInfo->info.payloadSize)
1334 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1335 // check the security resource
1336 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1338 type = PAYLOAD_TYPE_SECURITY;
1340 else if (cbNode->method == OC_REST_DISCOVER)
1342 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1343 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1345 type = PAYLOAD_TYPE_DISCOVERY;
1348 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1350 type = PAYLOAD_TYPE_DISCOVERY;
1353 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1355 type = PAYLOAD_TYPE_DEVICE;
1357 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1359 type = PAYLOAD_TYPE_PLATFORM;
1361 #ifdef ROUTING_GATEWAY
1362 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1364 type = PAYLOAD_TYPE_REPRESENTATION;
1367 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1369 type = PAYLOAD_TYPE_RD;
1372 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1374 type = PAYLOAD_TYPE_REPRESENTATION;
1379 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1380 cbNode->method, cbNode->requestUri);
1384 else if (cbNode->method == OC_REST_GET ||
1385 cbNode->method == OC_REST_PUT ||
1386 cbNode->method == OC_REST_POST ||
1387 cbNode->method == OC_REST_OBSERVE ||
1388 cbNode->method == OC_REST_OBSERVE_ALL ||
1389 cbNode->method == OC_REST_DELETE)
1391 if (cbNode->requestUri)
1393 char targetUri[MAX_URI_LENGTH];
1394 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1395 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1396 if (strcmp(targetUri, cbNode->requestUri) == 0)
1398 type = PAYLOAD_TYPE_RD;
1400 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1402 type = PAYLOAD_TYPE_PLATFORM;
1404 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1406 type = PAYLOAD_TYPE_DEVICE;
1408 if (type == PAYLOAD_TYPE_INVALID)
1410 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1411 cbNode->method, cbNode->requestUri);
1412 type = PAYLOAD_TYPE_REPRESENTATION;
1417 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1418 type = PAYLOAD_TYPE_REPRESENTATION;
1423 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1424 cbNode->method, cbNode->requestUri);
1428 if(OC_STACK_OK != OCParsePayload(&response.payload,
1430 responseInfo->info.payload,
1431 responseInfo->info.payloadSize))
1433 OIC_LOG(ERROR, TAG, "Error converting payload");
1434 OCPayloadDestroy(response.payload);
1439 response.numRcvdVendorSpecificHeaderOptions = 0;
1440 if(responseInfo->info.numOptions > 0)
1443 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1444 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1447 uint32_t observationOption;
1448 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1449 for (observationOption=0, i=0;
1450 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1454 (observationOption << 8) | optionData[i];
1456 response.sequenceNumber = observationOption;
1457 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1462 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1465 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1467 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1468 OCPayloadDestroy(response.payload);
1472 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1474 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1475 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1479 if (cbNode->method == OC_REST_OBSERVE &&
1480 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1481 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1482 response.sequenceNumber <= cbNode->sequenceNumber)
1484 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1485 response.sequenceNumber);
1489 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1492 cbNode->sequenceNumber = response.sequenceNumber;
1494 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1496 FindAndDeleteClientCB(cbNode);
1500 // To keep discovery callbacks active.
1501 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1502 MILLISECONDS_PER_SECOND);
1506 //Need to send ACK when the response is CON
1507 if(responseInfo->info.type == CA_MSG_CONFIRM)
1509 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1510 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1513 OCPayloadDestroy(response.payload);
1520 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1521 if(responseInfo->result == CA_EMPTY)
1523 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1524 if(responseInfo->info.type == CA_MSG_RESET)
1526 OIC_LOG(INFO, TAG, "This is a RESET");
1527 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1528 OC_OBSERVER_NOT_INTERESTED);
1530 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1532 OIC_LOG(INFO, TAG, "This is a pure ACK");
1533 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1534 OC_OBSERVER_STILL_INTERESTED);
1537 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1539 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1540 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1541 OC_OBSERVER_FAILED_COMM);
1546 if(!cbNode && !observer)
1548 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1549 || myStackMode == OC_GATEWAY)
1551 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1552 if(responseInfo->result == CA_EMPTY)
1554 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1558 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1559 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1560 CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1564 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1565 || myStackMode == OC_GATEWAY)
1567 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1568 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1570 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1571 responseInfo->info.messageId);
1573 if (responseInfo->info.type == CA_MSG_RESET)
1575 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1576 responseInfo->info.messageId);
1584 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1586 VERIFY_NON_NULL_NR(endPoint, FATAL);
1587 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1589 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1591 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1592 #ifdef ROUTING_GATEWAY
1593 bool needRIHandling = false;
1595 * Routing manager is going to update either of endpoint or response or both.
1596 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1597 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1600 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1602 if(ret != OC_STACK_OK || !needRIHandling)
1604 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1610 * Put source in sender endpoint so that the next packet from application can be routed to
1611 * proper destination and remove "RM" coap header option before passing request / response to
1612 * RI as this option will make no sense to either RI or application.
1614 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1615 (uint8_t *) &(responseInfo->info.numOptions),
1616 (CAEndpoint_t *) endPoint);
1619 OCHandleResponse(endPoint, responseInfo);
1621 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1625 * This function handles error response from CA
1626 * code shall be added to handle the errors
1628 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1630 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1632 if (NULL == endPoint)
1634 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1638 if (NULL == errorInfo)
1640 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1644 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1645 errorInfo->info.tokenLength, NULL, NULL);
1648 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1649 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1650 FixUpClientResponse(&response);
1651 response.resourceUri = errorInfo->info.resourceUri;
1652 memcpy(response.identity.id, errorInfo->info.identity.id,
1653 sizeof (response.identity.id));
1654 response.identity.id_length = errorInfo->info.identity.id_length;
1655 response.result = CAResultToOCStackResult(errorInfo->result);
1657 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1660 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1664 * This function sends out Direct Stack Responses. These are responses that are not coming
1665 * from the application entity handler. These responses have no payload and are usually ACKs,
1666 * RESETs or some error conditions that were caught by the stack.
1668 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1669 const CAResponseResult_t responseResult, const CAMessageType_t type,
1670 const uint8_t numOptions, const CAHeaderOption_t *options,
1671 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1672 CADataType_t dataType)
1674 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1675 CAResponseInfo_t respInfo = {
1676 .result = responseResult
1678 respInfo.info.messageId = coapID;
1679 respInfo.info.numOptions = numOptions;
1681 if (respInfo.info.numOptions)
1683 respInfo.info.options =
1684 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1685 memcpy (respInfo.info.options, options,
1686 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1690 respInfo.info.payload = NULL;
1691 respInfo.info.token = token;
1692 respInfo.info.tokenLength = tokenLength;
1693 respInfo.info.type = type;
1694 respInfo.info.resourceUri = OICStrdup (resourceUri);
1695 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1696 respInfo.info.dataType = dataType;
1698 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1699 // Add the destination to route option from the endpoint->routeData.
1700 bool doPost = false;
1701 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1702 if(OC_STACK_OK != result)
1704 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1709 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1710 CARequestInfo_t reqInfo = {.method = CA_POST };
1711 /* The following initialization is not done in a single initializer block as in
1712 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1713 * does not have designated initalizers. This is a work-around for now.
1715 reqInfo.info.type = CA_MSG_NONCONFIRM;
1716 reqInfo.info.messageId = coapID;
1717 reqInfo.info.tokenLength = tokenLength;
1718 reqInfo.info.token = token;
1719 reqInfo.info.numOptions = respInfo.info.numOptions;
1720 reqInfo.info.payload = NULL;
1721 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1722 if (reqInfo.info.numOptions)
1724 reqInfo.info.options =
1725 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1726 if (NULL == reqInfo.info.options)
1728 OIC_LOG(ERROR, TAG, "Calloc failed");
1729 return OC_STACK_NO_MEMORY;
1731 memcpy (reqInfo.info.options, respInfo.info.options,
1732 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1735 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1736 OICFree (reqInfo.info.resourceUri);
1737 OICFree (reqInfo.info.options);
1738 OICFree (respInfo.info.resourceUri);
1739 OICFree (respInfo.info.options);
1740 if (CA_STATUS_OK != caResult)
1742 OIC_LOG(ERROR, TAG, "CASendRequest error");
1743 return CAResultToOCResult(caResult);
1749 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1751 // resourceUri in the info field is cloned in the CA layer and
1752 // thus ownership is still here.
1753 OICFree (respInfo.info.resourceUri);
1754 OICFree (respInfo.info.options);
1755 if(CA_STATUS_OK != caResult)
1757 OIC_LOG(ERROR, TAG, "CASendResponse error");
1758 return CAResultToOCResult(caResult);
1761 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1765 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1767 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1768 OCStackResult result = OC_STACK_ERROR;
1769 if(!protocolRequest)
1771 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1772 return OC_STACK_INVALID_PARAM;
1775 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1776 protocolRequest->tokenLength);
1779 OIC_LOG(INFO, TAG, "This is a new Server Request");
1780 result = AddServerRequest(&request, protocolRequest->coapID,
1781 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1782 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1783 protocolRequest->observationOption, protocolRequest->qos,
1784 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1785 protocolRequest->payload, protocolRequest->requestToken,
1786 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1787 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1788 &protocolRequest->devAddr);
1789 if (OC_STACK_OK != result)
1791 OIC_LOG(ERROR, TAG, "Error adding server request");
1797 OIC_LOG(ERROR, TAG, "Out of Memory");
1798 return OC_STACK_NO_MEMORY;
1801 if(!protocolRequest->reqMorePacket)
1803 request->requestComplete = 1;
1808 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1811 if(request->requestComplete)
1813 OIC_LOG(INFO, TAG, "This Server Request is complete");
1814 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1815 OCResource *resource = NULL;
1816 result = DetermineResourceHandling (request, &resHandling, &resource);
1817 if (result == OC_STACK_OK)
1819 result = ProcessRequest(resHandling, resource, request);
1824 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1825 result = OC_STACK_CONTINUE;
1830 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1832 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1835 if (requestInfo->info.resourceUri &&
1836 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1838 HandleKeepAliveRequest(endPoint, requestInfo);
1843 OCStackResult requestResult = OC_STACK_ERROR;
1845 if(myStackMode == OC_CLIENT)
1847 //TODO: should the client be responding to requests?
1851 OCServerProtocolRequest serverRequest = {0};
1853 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1855 char * uriWithoutQuery = NULL;
1856 char * query = NULL;
1858 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1860 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1862 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1865 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1866 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1868 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1870 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1871 OICFree(uriWithoutQuery);
1875 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1876 OICFree(uriWithoutQuery);
1883 if(strlen(query) < MAX_QUERY_LENGTH)
1885 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1890 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1896 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1898 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1899 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1900 if (!serverRequest.payload)
1902 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1905 memcpy (serverRequest.payload, requestInfo->info.payload,
1906 requestInfo->info.payloadSize);
1910 serverRequest.reqTotalSize = 0;
1913 switch (requestInfo->method)
1916 serverRequest.method = OC_REST_GET;
1919 serverRequest.method = OC_REST_PUT;
1922 serverRequest.method = OC_REST_POST;
1925 serverRequest.method = OC_REST_DELETE;
1928 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1929 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1930 requestInfo->info.type, requestInfo->info.numOptions,
1931 requestInfo->info.options, requestInfo->info.token,
1932 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1934 OICFree(serverRequest.payload);
1938 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1939 requestInfo->info.tokenLength);
1941 serverRequest.tokenLength = requestInfo->info.tokenLength;
1942 if (serverRequest.tokenLength) {
1944 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1946 if (!serverRequest.requestToken)
1948 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1949 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1950 requestInfo->info.type, requestInfo->info.numOptions,
1951 requestInfo->info.options, requestInfo->info.token,
1952 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1954 OICFree(serverRequest.payload);
1957 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1960 switch (requestInfo->info.acceptFormat)
1962 case CA_FORMAT_APPLICATION_CBOR:
1963 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1965 case CA_FORMAT_UNDEFINED:
1966 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1969 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1972 if (requestInfo->info.type == CA_MSG_CONFIRM)
1974 serverRequest.qos = OC_HIGH_QOS;
1978 serverRequest.qos = OC_LOW_QOS;
1980 // CA does not need the following field
1981 // Are we sure CA does not need them? how is it responding to multicast
1982 serverRequest.delayedResNeeded = 0;
1984 serverRequest.coapID = requestInfo->info.messageId;
1986 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1988 // copy vendor specific header options
1989 uint8_t tempNum = (requestInfo->info.numOptions);
1991 // Assume no observation requested and it is a pure GET.
1992 // If obs registration/de-registration requested it'll be fetched from the
1993 // options in GetObserveHeaderOption()
1994 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1996 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1997 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2000 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2001 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2002 requestInfo->info.type, requestInfo->info.numOptions,
2003 requestInfo->info.options, requestInfo->info.token,
2004 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2006 OICFree(serverRequest.payload);
2007 OICFree(serverRequest.requestToken);
2010 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2011 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
2013 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
2014 sizeof(CAHeaderOption_t)*tempNum);
2017 requestResult = HandleStackRequests (&serverRequest);
2019 // Send ACK to client as precursor to slow response
2020 if (requestResult == OC_STACK_SLOW_RESOURCE)
2022 if (requestInfo->info.type == CA_MSG_CONFIRM)
2024 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2025 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2029 if (requestResult == OC_STACK_RESOURCE_ERROR
2030 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2032 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2034 else if(!OCResultToSuccess(requestResult))
2036 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2038 CAResponseResult_t stackResponse =
2039 OCToCAStackResult(requestResult, serverRequest.method);
2041 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2042 requestInfo->info.type, requestInfo->info.numOptions,
2043 requestInfo->info.options, requestInfo->info.token,
2044 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2047 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2048 // The token is copied in there, and is thus still owned by this function.
2049 OICFree(serverRequest.payload);
2050 OICFree(serverRequest.requestToken);
2051 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2054 //This function will be called back by CA layer when a request is received
2055 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2057 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2060 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2066 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2070 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2071 #ifdef ROUTING_GATEWAY
2072 bool needRIHandling = false;
2073 bool isEmptyMsg = false;
2075 * Routing manager is going to update either of endpoint or request or both.
2076 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2077 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2078 * destination. It can also remove "RM" coap header option before passing request / response to
2079 * RI as this option will make no sense to either RI or application.
2081 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2082 &needRIHandling, &isEmptyMsg);
2083 if(OC_STACK_OK != ret || !needRIHandling)
2085 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2091 * Put source in sender endpoint so that the next packet from application can be routed to
2092 * proper destination and remove RM header option.
2094 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2095 (uint8_t *) &(requestInfo->info.numOptions),
2096 (CAEndpoint_t *) endPoint);
2098 #ifdef ROUTING_GATEWAY
2102 * In Gateways, the MSGType in route option is used to check if the actual
2103 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2104 * EMPTY response is sent in the form of POST request which need to be changed
2105 * to a EMPTY response by RM. This translation is done in this part of the code.
2107 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2108 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2109 .info.messageId = requestInfo->info.messageId,
2110 .info.type = CA_MSG_ACKNOWLEDGE};
2111 OCHandleResponse(endPoint, &respInfo);
2117 // Normal handling of the packet
2118 OCHandleRequests(endPoint, requestInfo);
2120 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2123 bool validatePlatformInfo(OCPlatformInfo info)
2126 if (!info.platformID)
2128 OIC_LOG(ERROR, TAG, "No platform ID found.");
2132 if (info.manufacturerName)
2134 size_t lenManufacturerName = strlen(info.manufacturerName);
2136 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2138 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2144 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2148 if (info.manufacturerUrl)
2150 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2152 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2159 //-----------------------------------------------------------------------------
2161 //-----------------------------------------------------------------------------
2163 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2166 !raInfo->username ||
2167 !raInfo->hostname ||
2168 !raInfo->xmpp_domain)
2171 return OC_STACK_INVALID_PARAM;
2173 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2174 gRASetInfo = (result == OC_STACK_OK)? true : false;
2180 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2184 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2187 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2189 if(stackState == OC_STACK_INITIALIZED)
2191 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2192 OCStop() between them are ignored.");
2196 #ifndef ROUTING_GATEWAY
2197 if (OC_GATEWAY == mode)
2199 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2200 return OC_STACK_INVALID_PARAM;
2207 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2208 return OC_STACK_ERROR;
2212 OCStackResult result = OC_STACK_ERROR;
2213 OIC_LOG(INFO, TAG, "Entering OCInit");
2216 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2217 || (mode == OC_GATEWAY)))
2219 OIC_LOG(ERROR, TAG, "Invalid mode");
2220 return OC_STACK_ERROR;
2224 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2226 caglobals.client = true;
2228 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2230 caglobals.server = true;
2233 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2234 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2236 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2238 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2239 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2241 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2244 defaultDeviceHandler = NULL;
2245 defaultDeviceHandlerCallbackParameter = NULL;
2247 result = InitializeScheduleResourceList();
2248 VERIFY_SUCCESS(result, OC_STACK_OK);
2250 result = CAResultToOCResult(CAInitialize());
2251 VERIFY_SUCCESS(result, OC_STACK_OK);
2253 result = CAResultToOCResult(OCSelectNetwork());
2254 VERIFY_SUCCESS(result, OC_STACK_OK);
2256 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2257 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2258 VERIFY_SUCCESS(result, OC_STACK_OK);
2260 switch (myStackMode)
2263 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2264 result = CAResultToOCResult(CAStartDiscoveryServer());
2265 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2268 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2269 result = CAResultToOCResult(CAStartListeningServer());
2270 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2272 case OC_CLIENT_SERVER:
2274 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2275 result = CAResultToOCResult(CAStartListeningServer());
2276 if(result == OC_STACK_OK)
2278 result = CAResultToOCResult(CAStartDiscoveryServer());
2282 VERIFY_SUCCESS(result, OC_STACK_OK);
2285 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2288 #ifdef WITH_PRESENCE
2289 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2290 #endif // WITH_PRESENCE
2292 //Update Stack state to initialized
2293 stackState = OC_STACK_INITIALIZED;
2295 // Initialize resource
2296 if(myStackMode != OC_CLIENT)
2298 result = initResources();
2301 // Initialize the SRM Policy Engine
2302 if(result == OC_STACK_OK)
2304 result = SRMInitPolicyEngine();
2305 // TODO after BeachHead delivery: consolidate into single SRMInit()
2307 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2308 RMSetStackMode(mode);
2309 #ifdef ROUTING_GATEWAY
2310 if (OC_GATEWAY == myStackMode)
2312 result = RMInitialize();
2318 if (result == OC_STACK_OK)
2320 result = InitializeKeepAlive(myStackMode);
2325 if(result != OC_STACK_OK)
2327 OIC_LOG(ERROR, TAG, "Stack initialization error");
2328 deleteAllResources();
2330 TerminateScheduleResourceList();
2331 stackState = OC_STACK_UNINITIALIZED;
2336 OCStackResult OCStop()
2338 OIC_LOG(INFO, TAG, "Entering OCStop");
2340 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2342 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2345 else if (stackState != OC_STACK_INITIALIZED)
2347 OIC_LOG(ERROR, TAG, "Stack not initialized");
2348 return OC_STACK_ERROR;
2351 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2353 #ifdef WITH_PRESENCE
2354 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2355 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2356 presenceResource.presenceTTL = 0;
2357 #endif // WITH_PRESENCE
2359 #ifdef ROUTING_GATEWAY
2360 if (OC_GATEWAY == myStackMode)
2367 TerminateKeepAlive(myStackMode);
2370 // Free memory dynamically allocated for resources
2371 deleteAllResources();
2373 DeletePlatformInfo();
2375 TerminateScheduleResourceList();
2376 // Remove all observers
2377 DeleteObserverList();
2378 // Remove all the client callbacks
2379 DeleteClientCBList();
2381 // De-init the SRM Policy Engine
2382 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2383 SRMDeInitPolicyEngine();
2386 stackState = OC_STACK_UNINITIALIZED;
2390 OCStackResult OCStartMulticastServer()
2392 if(stackState != OC_STACK_INITIALIZED)
2394 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2395 return OC_STACK_ERROR;
2397 CAResult_t ret = CAStartListeningServer();
2398 if (CA_STATUS_OK != ret)
2400 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2401 return OC_STACK_ERROR;
2406 OCStackResult OCStopMulticastServer()
2408 CAResult_t ret = CAStopListeningServer();
2409 if (CA_STATUS_OK != ret)
2411 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2412 return OC_STACK_ERROR;
2417 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2422 return CA_MSG_CONFIRM;
2427 return CA_MSG_NONCONFIRM;
2432 * A request uri consists of the following components in order:
2435 * CoAP over UDP prefix "coap://"
2436 * CoAP over TCP prefix "coap+tcp://"
2437 * CoAP over DTLS prefix "coaps://"
2438 * CoAP over TLS prefix "coaps+tcp://"
2440 * IPv6 address "[1234::5678]"
2441 * IPv4 address "192.168.1.1"
2442 * optional port ":5683"
2443 * resource uri "/oc/core..."
2445 * for PRESENCE requests, extract resource type.
2447 static OCStackResult ParseRequestUri(const char *fullUri,
2448 OCTransportAdapter adapter,
2449 OCTransportFlags flags,
2450 OCDevAddr **devAddr,
2452 char **resourceType)
2454 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2456 OCStackResult result = OC_STACK_OK;
2457 OCDevAddr *da = NULL;
2461 // provide defaults for all returned values
2468 *resourceUri = NULL;
2472 *resourceType = NULL;
2475 // delimit url prefix, if any
2476 const char *start = fullUri;
2477 char *slash2 = strstr(start, "//");
2482 char *slash = strchr(start, '/');
2485 return OC_STACK_INVALID_URI;
2488 // process url scheme
2489 size_t prefixLen = slash2 - fullUri;
2493 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2494 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2500 // TODO: this logic should come in with unit tests exercising the various strings
2501 // processs url prefix, if any
2502 size_t urlLen = slash - start;
2506 if (urlLen && devAddr)
2507 { // construct OCDevAddr
2508 if (start[0] == '[')
2510 char *close = strchr(++start, ']');
2511 if (!close || close > slash)
2513 return OC_STACK_INVALID_URI;
2516 if (close[1] == ':')
2523 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2527 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2529 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2533 char *dot = strchr(start, '.');
2534 if (dot && dot < slash)
2536 colon = strchr(start, ':');
2537 end = (colon && colon < slash) ? colon : slash;
2542 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2546 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2548 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2556 if (len >= sizeof(da->addr))
2558 return OC_STACK_INVALID_URI;
2560 // collect port, if any
2561 if (colon && colon < slash)
2563 for (colon++; colon < slash; colon++)
2566 if (c < '0' || c > '9')
2568 return OC_STACK_INVALID_URI;
2570 port = 10 * port + c - '0';
2575 if (len >= sizeof(da->addr))
2577 return OC_STACK_INVALID_URI;
2580 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2583 return OC_STACK_NO_MEMORY;
2585 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2587 da->adapter = adapter;
2589 if (!strncmp(fullUri, "coaps", 5))
2591 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2596 // process resource uri, if any
2598 { // request uri and query
2599 size_t ulen = strlen(slash); // resource uri length
2600 size_t tlen = 0; // resource type length
2603 static const char strPresence[] = "/oic/ad?rt=";
2604 static const size_t lenPresence = sizeof(strPresence) - 1;
2605 if (!strncmp(slash, strPresence, lenPresence))
2607 type = slash + lenPresence;
2608 tlen = ulen - lenPresence;
2613 *resourceUri = (char *)OICMalloc(ulen + 1);
2616 result = OC_STACK_NO_MEMORY;
2619 strcpy(*resourceUri, slash);
2622 if (type && resourceType)
2624 *resourceType = (char *)OICMalloc(tlen + 1);
2627 result = OC_STACK_NO_MEMORY;
2631 OICStrcpy(*resourceType, (tlen+1), type);
2638 // free all returned values
2645 OICFree(*resourceUri);
2649 OICFree(*resourceType);
2654 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2659 char uri[CA_MAX_URI_LENGTH];
2661 FormCanonicalPresenceUri(endpoint, resourceUri, uri, isMulticast);
2663 *requestUri = OICStrdup(uri);
2666 return OC_STACK_NO_MEMORY;
2673 * Discover or Perform requests on a specified resource
2675 OCStackResult OCDoResource(OCDoHandle *handle,
2677 const char *requestUri,
2678 const OCDevAddr *destination,
2680 OCConnectivityType connectivityType,
2681 OCQualityOfService qos,
2682 OCCallbackData *cbData,
2683 OCHeaderOption *options,
2686 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2688 // Validate input parameters
2689 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2690 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2692 OCStackResult result = OC_STACK_ERROR;
2693 CAResult_t caResult;
2694 CAToken_t token = NULL;
2695 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2696 ClientCB *clientCB = NULL;
2697 OCDoHandle resHandle = NULL;
2698 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2699 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2701 OCTransportAdapter adapter;
2702 OCTransportFlags flags;
2703 // the request contents are put here
2704 CARequestInfo_t requestInfo = {.method = CA_GET};
2705 // requestUri will be parsed into the following three variables
2706 OCDevAddr *devAddr = NULL;
2707 char *resourceUri = NULL;
2708 char *resourceType = NULL;
2711 * Support original behavior with address on resourceUri argument.
2713 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2714 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2718 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2719 if (result != OC_STACK_OK)
2721 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2725 else if (!checkProxyUri(options, numOptions))
2727 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2734 case OC_REST_OBSERVE:
2735 case OC_REST_OBSERVE_ALL:
2736 requestInfo.method = CA_GET;
2739 requestInfo.method = CA_PUT;
2742 requestInfo.method = CA_POST;
2744 case OC_REST_DELETE:
2745 requestInfo.method = CA_DELETE;
2747 case OC_REST_DISCOVER:
2749 #ifdef WITH_PRESENCE
2750 case OC_REST_PRESENCE:
2752 if (destination || devAddr)
2754 requestInfo.isMulticast = false;
2758 tmpDevAddr.adapter = adapter;
2759 tmpDevAddr.flags = flags;
2760 destination = &tmpDevAddr;
2761 requestInfo.isMulticast = true;
2763 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
2764 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
2765 // replacing method type with GET.
2766 requestInfo.method = CA_GET;
2769 result = OC_STACK_INVALID_METHOD;
2773 if (!devAddr && !destination)
2775 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2776 result = OC_STACK_INVALID_PARAM;
2780 /* If not original behavior, use destination argument */
2781 if (destination && !devAddr)
2783 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2786 result = OC_STACK_NO_MEMORY;
2789 *devAddr = *destination;
2792 resHandle = GenerateInvocationHandle();
2795 result = OC_STACK_NO_MEMORY;
2799 caResult = CAGenerateToken(&token, tokenLength);
2800 if (caResult != CA_STATUS_OK)
2802 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2803 result= OC_STACK_ERROR;
2807 // fill in request data
2808 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2809 requestInfo.info.token = token;
2810 requestInfo.info.tokenLength = tokenLength;
2811 requestInfo.info.resourceUri = resourceUri;
2813 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2815 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2816 options, numOptions, OC_OBSERVE_REGISTER);
2817 if (result != OC_STACK_OK)
2821 requestInfo.info.numOptions = numOptions + 1;
2825 requestInfo.info.numOptions = numOptions;
2826 requestInfo.info.options =
2827 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2828 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2829 numOptions * sizeof(CAHeaderOption_t));
2832 CopyDevAddrToEndpoint(devAddr, &endpoint);
2837 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2840 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2843 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2847 requestInfo.info.payload = NULL;
2848 requestInfo.info.payloadSize = 0;
2849 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2852 // prepare for response
2853 #ifdef WITH_PRESENCE
2854 if (method == OC_REST_PRESENCE)
2856 char *presenceUri = NULL;
2857 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri,
2858 requestInfo.isMulticast);
2859 if (OC_STACK_OK != result)
2864 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2865 // Presence notification will form a canonical uri to
2866 // look for callbacks into the application.
2867 resourceUri = presenceUri;
2871 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2872 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2873 method, devAddr, resourceUri, resourceType, ttl);
2874 if (OC_STACK_OK != result)
2879 devAddr = NULL; // Client CB list entry now owns it
2880 resourceUri = NULL; // Client CB list entry now owns it
2881 resourceType = NULL; // Client CB list entry now owns it
2884 result = OCSendRequest(&endpoint, &requestInfo);
2885 if (OC_STACK_OK != result)
2892 *handle = resHandle;
2896 if (result != OC_STACK_OK)
2898 OIC_LOG(ERROR, TAG, "OCDoResource error");
2899 FindAndDeleteClientCB(clientCB);
2900 CADestroyToken(token);
2908 // This is the owner of the payload object, so we free it
2909 OCPayloadDestroy(payload);
2910 OICFree(requestInfo.info.payload);
2912 OICFree(resourceUri);
2913 OICFree(resourceType);
2914 OICFree(requestInfo.info.options);
2918 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2922 * This ftn is implemented one of two ways in the case of observation:
2924 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2925 * Remove the callback associated on client side.
2926 * When the next notification comes in from server,
2927 * reply with RESET message to server.
2928 * Keep in mind that the server will react to RESET only
2929 * if the last notification was sent as CON
2931 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2932 * and it is associated with an observe request
2933 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2934 * Send CON Observe request to server with
2935 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2936 * Remove the callback associated on client side.
2938 OCStackResult ret = OC_STACK_OK;
2939 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2940 CARequestInfo_t requestInfo = {.method = CA_GET};
2944 return OC_STACK_INVALID_PARAM;
2947 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2950 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2951 return OC_STACK_ERROR;
2954 switch (clientCB->method)
2956 case OC_REST_OBSERVE:
2957 case OC_REST_OBSERVE_ALL:
2959 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2961 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2963 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2965 FindAndDeleteClientCB(clientCB);
2969 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2971 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2972 requestInfo.info.token = clientCB->token;
2973 requestInfo.info.tokenLength = clientCB->tokenLength;
2975 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2976 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2978 return OC_STACK_ERROR;
2980 requestInfo.info.numOptions = numOptions + 1;
2981 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2984 ret = OCSendRequest(&endpoint, &requestInfo);
2986 if (requestInfo.info.options)
2988 OICFree (requestInfo.info.options);
2990 if (requestInfo.info.resourceUri)
2992 OICFree (requestInfo.info.resourceUri);
2997 case OC_REST_DISCOVER:
2998 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2999 clientCB->requestUri);
3000 FindAndDeleteClientCB(clientCB);
3003 #ifdef WITH_PRESENCE
3004 case OC_REST_PRESENCE:
3005 FindAndDeleteClientCB(clientCB);
3010 ret = OC_STACK_INVALID_METHOD;
3018 * @brief Register Persistent storage callback.
3019 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3021 * OC_STACK_OK - No errors; Success
3022 * OC_STACK_INVALID_PARAM - Invalid parameter
3024 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3026 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3027 if(!persistentStorageHandler)
3029 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3030 return OC_STACK_INVALID_PARAM;
3034 if( !persistentStorageHandler->open ||
3035 !persistentStorageHandler->close ||
3036 !persistentStorageHandler->read ||
3037 !persistentStorageHandler->unlink ||
3038 !persistentStorageHandler->write)
3040 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3041 return OC_STACK_INVALID_PARAM;
3044 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3047 #ifdef WITH_PRESENCE
3049 OCStackResult OCProcessPresence()
3051 OCStackResult result = OC_STACK_OK;
3053 // the following line floods the log with messages that are irrelevant
3054 // to most purposes. Uncomment as needed.
3055 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3056 ClientCB* cbNode = NULL;
3057 OCClientResponse clientResponse;
3058 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3060 LL_FOREACH(cbList, cbNode)
3062 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3067 uint32_t now = GetTicks(0);
3068 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3069 cbNode->presence->TTLlevel);
3070 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3072 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3077 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3079 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3080 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3082 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3084 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3086 clientResponse.sequenceNumber = 0;
3087 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3088 clientResponse.devAddr = *cbNode->devAddr;
3089 FixUpClientResponse(&clientResponse);
3090 clientResponse.payload = NULL;
3092 // Increment the TTLLevel (going to a next state), so we don't keep
3093 // sending presence notification to client.
3094 cbNode->presence->TTLlevel++;
3095 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3096 cbNode->presence->TTLlevel);
3098 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3099 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3101 FindAndDeleteClientCB(cbNode);
3105 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3110 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3111 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3112 CARequestInfo_t requestInfo = {.method = CA_GET};
3114 OIC_LOG(DEBUG, TAG, "time to test server presence");
3116 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3118 requestData.type = CA_MSG_NONCONFIRM;
3119 requestData.token = cbNode->token;
3120 requestData.tokenLength = cbNode->tokenLength;
3121 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3122 requestInfo.method = CA_GET;
3123 requestInfo.info = requestData;
3125 result = OCSendRequest(&endpoint, &requestInfo);
3126 if (OC_STACK_OK != result)
3131 cbNode->presence->TTLlevel++;
3132 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3135 if (result != OC_STACK_OK)
3137 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3142 #endif // WITH_PRESENCE
3144 OCStackResult OCProcess()
3146 #ifdef WITH_PRESENCE
3147 OCProcessPresence();
3149 CAHandleRequestResponse();
3151 #ifdef ROUTING_GATEWAY
3161 #ifdef WITH_PRESENCE
3162 OCStackResult OCStartPresence(const uint32_t ttl)
3164 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3165 OCChangeResourceProperty(
3166 &(((OCResource *)presenceResource.handle)->resourceProperties),
3169 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3171 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3172 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3176 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3177 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3181 presenceResource.presenceTTL = ttl;
3183 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3185 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3187 presenceState = OC_PRESENCE_INITIALIZED;
3189 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3191 CAToken_t caToken = NULL;
3192 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3193 if (caResult != CA_STATUS_OK)
3195 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3196 CADestroyToken(caToken);
3197 return OC_STACK_ERROR;
3200 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3201 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3202 CADestroyToken(caToken);
3205 // Each time OCStartPresence is called
3206 // a different random 32-bit integer number is used
3207 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3209 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3210 OC_PRESENCE_TRIGGER_CREATE);
3213 OCStackResult OCStopPresence()
3215 OCStackResult result = OC_STACK_ERROR;
3217 if(presenceResource.handle)
3219 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3221 // make resource inactive
3222 result = OCChangeResourceProperty(
3223 &(((OCResource *) presenceResource.handle)->resourceProperties),
3227 if(result != OC_STACK_OK)
3230 "Changing the presence resource properties to ACTIVE not successful");
3234 return SendStopNotification();
3238 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3239 void* callbackParameter)
3241 defaultDeviceHandler = entityHandler;
3242 defaultDeviceHandlerCallbackParameter = callbackParameter;
3247 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3249 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3251 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3253 if (validatePlatformInfo(platformInfo))
3255 return SavePlatformInfo(platformInfo);
3259 return OC_STACK_INVALID_PARAM;
3264 return OC_STACK_ERROR;
3268 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3270 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3272 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3274 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3275 return OC_STACK_INVALID_PARAM;
3278 if (deviceInfo.types)
3280 OCStringLL *type = deviceInfo.types;
3281 OCResource *resource = findResource((OCResource *) deviceResource);
3284 return OC_STACK_INVALID_PARAM;
3289 OCBindResourceTypeToResource(deviceResource, type->value);
3293 return SaveDeviceInfo(deviceInfo);
3296 OCStackResult OCCreateResource(OCResourceHandle *handle,
3297 const char *resourceTypeName,
3298 const char *resourceInterfaceName,
3299 const char *uri, OCEntityHandler entityHandler,
3300 void* callbackParam,
3301 uint8_t resourceProperties)
3304 OCResource *pointer = NULL;
3305 OCStackResult result = OC_STACK_ERROR;
3307 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3309 if(myStackMode == OC_CLIENT)
3311 return OC_STACK_INVALID_PARAM;
3313 // Validate parameters
3314 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3316 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3317 return OC_STACK_INVALID_URI;
3319 // Is it presented during resource discovery?
3320 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3322 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3323 return OC_STACK_INVALID_PARAM;
3326 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3328 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3332 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3334 // Make sure resourceProperties bitmask has allowed properties specified
3335 if (resourceProperties
3336 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3337 OC_EXPLICIT_DISCOVERABLE
3346 OIC_LOG(ERROR, TAG, "Invalid property");
3347 return OC_STACK_INVALID_PARAM;
3350 // If the headResource is NULL, then no resources have been created...
3351 pointer = headResource;
3354 // At least one resources is in the resource list, so we need to search for
3355 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3358 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3360 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3361 return OC_STACK_INVALID_PARAM;
3363 pointer = pointer->next;
3366 // Create the pointer and insert it into the resource list
3367 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3370 result = OC_STACK_NO_MEMORY;
3373 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3375 insertResource(pointer);
3378 pointer->uri = OICStrdup(uri);
3381 result = OC_STACK_NO_MEMORY;
3385 // Set properties. Set OC_ACTIVE
3386 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3389 // Add the resourcetype to the resource
3390 result = BindResourceTypeToResource(pointer, resourceTypeName);
3391 if (result != OC_STACK_OK)
3393 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3397 // Add the resourceinterface to the resource
3398 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3399 if (result != OC_STACK_OK)
3401 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3405 // If an entity handler has been passed, attach it to the newly created
3406 // resource. Otherwise, set the default entity handler.
3409 pointer->entityHandler = entityHandler;
3410 pointer->entityHandlerCallbackParam = callbackParam;
3414 pointer->entityHandler = defaultResourceEHandler;
3415 pointer->entityHandlerCallbackParam = NULL;
3418 // Initialize a pointer indicating child resources in case of collection
3419 pointer->rsrcChildResourcesHead = NULL;
3422 result = OC_STACK_OK;
3424 #ifdef WITH_PRESENCE
3425 if (presenceResource.handle)
3427 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3428 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3432 if (result != OC_STACK_OK)
3434 // Deep delete of resource and other dynamic elements that it contains
3435 deleteResource(pointer);
3440 OCStackResult OCBindResource(
3441 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3443 OCResource *resource = NULL;
3444 OCChildResource *tempChildResource = NULL;
3445 OCChildResource *newChildResource = NULL;
3447 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3449 // Validate parameters
3450 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3451 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3452 // Container cannot contain itself
3453 if (collectionHandle == resourceHandle)
3455 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3456 return OC_STACK_INVALID_PARAM;
3459 // Use the handle to find the resource in the resource linked list
3460 resource = findResource((OCResource *) collectionHandle);
3463 OIC_LOG(ERROR, TAG, "Collection handle not found");
3464 return OC_STACK_INVALID_PARAM;
3467 // Look for an open slot to add add the child resource.
3468 // If found, add it and return success
3470 tempChildResource = resource->rsrcChildResourcesHead;
3472 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3474 // TODO: what if one of child resource was deregistered without unbinding?
3475 tempChildResource = tempChildResource->next;
3478 // Do memory allocation for child resource
3479 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3480 if(!newChildResource)
3482 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3483 return OC_STACK_ERROR;
3486 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3487 newChildResource->next = NULL;
3489 if(!resource->rsrcChildResourcesHead)
3491 resource->rsrcChildResourcesHead = newChildResource;
3494 tempChildResource->next = newChildResource;
3497 OIC_LOG(INFO, TAG, "resource bound");
3499 #ifdef WITH_PRESENCE
3500 if (presenceResource.handle)
3502 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3503 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3504 OC_PRESENCE_TRIGGER_CHANGE);
3511 OCStackResult OCUnBindResource(
3512 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3514 OCResource *resource = NULL;
3515 OCChildResource *tempChildResource = NULL;
3516 OCChildResource *tempLastChildResource = NULL;
3518 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3520 // Validate parameters
3521 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3522 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3523 // Container cannot contain itself
3524 if (collectionHandle == resourceHandle)
3526 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3527 return OC_STACK_INVALID_PARAM;
3530 // Use the handle to find the resource in the resource linked list
3531 resource = findResource((OCResource *) collectionHandle);
3534 OIC_LOG(ERROR, TAG, "Collection handle not found");
3535 return OC_STACK_INVALID_PARAM;
3538 // Look for an open slot to add add the child resource.
3539 // If found, add it and return success
3540 if(!resource->rsrcChildResourcesHead)
3542 OIC_LOG(INFO, TAG, "resource not found in collection");
3544 // Unable to add resourceHandle, so return error
3545 return OC_STACK_ERROR;
3549 tempChildResource = resource->rsrcChildResourcesHead;
3551 while (tempChildResource)
3553 if(tempChildResource->rsrcResource == resourceHandle)
3555 // if resource going to be unbinded is the head one.
3556 if( tempChildResource == resource->rsrcChildResourcesHead )
3558 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3559 OICFree(resource->rsrcChildResourcesHead);
3560 resource->rsrcChildResourcesHead = temp;
3565 OCChildResource *temp = tempChildResource->next;
3566 OICFree(tempChildResource);
3567 tempLastChildResource->next = temp;
3571 OIC_LOG(INFO, TAG, "resource unbound");
3573 // Send notification when resource is unbounded successfully.
3574 #ifdef WITH_PRESENCE
3575 if (presenceResource.handle)
3577 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3578 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3579 OC_PRESENCE_TRIGGER_CHANGE);
3582 tempChildResource = NULL;
3583 tempLastChildResource = NULL;
3589 tempLastChildResource = tempChildResource;
3590 tempChildResource = tempChildResource->next;
3593 OIC_LOG(INFO, TAG, "resource not found in collection");
3595 tempChildResource = NULL;
3596 tempLastChildResource = NULL;
3598 // Unable to add resourceHandle, so return error
3599 return OC_STACK_ERROR;
3602 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3604 if (!resourceItemName)
3608 // Per RFC 6690 only registered values must follow the first rule below.
3609 // At this point in time the only values registered begin with "core", and
3610 // all other values are specified as opaque strings where multiple values
3611 // are separated by a space.
3612 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3614 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3616 if (resourceItemName[index] != '.'
3617 && resourceItemName[index] != '-'
3618 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3619 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3627 for (size_t index = 0; resourceItemName[index]; ++index)
3629 if (resourceItemName[index] == ' '
3630 || resourceItemName[index] == '\t'
3631 || resourceItemName[index] == '\r'
3632 || resourceItemName[index] == '\n')
3642 OCStackResult BindResourceTypeToResource(OCResource* resource,
3643 const char *resourceTypeName)
3645 OCResourceType *pointer = NULL;
3647 OCStackResult result = OC_STACK_ERROR;
3649 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3651 if (!ValidateResourceTypeInterface(resourceTypeName))
3653 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3654 return OC_STACK_INVALID_PARAM;
3657 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3660 result = OC_STACK_NO_MEMORY;
3664 str = OICStrdup(resourceTypeName);
3667 result = OC_STACK_NO_MEMORY;
3670 pointer->resourcetypename = str;
3671 pointer->next = NULL;
3673 insertResourceType(resource, pointer);
3674 result = OC_STACK_OK;
3677 if (result != OC_STACK_OK)
3686 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3687 const char *resourceInterfaceName)
3689 OCResourceInterface *pointer = NULL;
3691 OCStackResult result = OC_STACK_ERROR;
3693 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3695 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3697 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3698 return OC_STACK_INVALID_PARAM;
3701 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3703 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3706 result = OC_STACK_NO_MEMORY;
3710 str = OICStrdup(resourceInterfaceName);
3713 result = OC_STACK_NO_MEMORY;
3716 pointer->name = str;
3718 // Bind the resourceinterface to the resource
3719 insertResourceInterface(resource, pointer);
3721 result = OC_STACK_OK;
3724 if (result != OC_STACK_OK)
3733 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3734 const char *resourceTypeName)
3737 OCStackResult result = OC_STACK_ERROR;
3738 OCResource *resource = NULL;
3740 resource = findResource((OCResource *) handle);
3743 OIC_LOG(ERROR, TAG, "Resource not found");
3744 return OC_STACK_ERROR;
3747 result = BindResourceTypeToResource(resource, resourceTypeName);
3749 #ifdef WITH_PRESENCE
3750 if(presenceResource.handle)
3752 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3753 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3760 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3761 const char *resourceInterfaceName)
3764 OCStackResult result = OC_STACK_ERROR;
3765 OCResource *resource = NULL;
3767 resource = findResource((OCResource *) handle);
3770 OIC_LOG(ERROR, TAG, "Resource not found");
3771 return OC_STACK_ERROR;
3774 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3776 #ifdef WITH_PRESENCE
3777 if (presenceResource.handle)
3779 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3780 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3787 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3789 OCResource *pointer = headResource;
3791 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3795 *numResources = *numResources + 1;
3796 pointer = pointer->next;
3801 OCResourceHandle OCGetResourceHandle(uint8_t index)
3803 OCResource *pointer = headResource;
3805 for( uint8_t i = 0; i < index && pointer; ++i)
3807 pointer = pointer->next;
3809 return (OCResourceHandle) pointer;
3812 OCStackResult OCDeleteResource(OCResourceHandle handle)
3816 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3817 return OC_STACK_INVALID_PARAM;
3820 OCResource *resource = findResource((OCResource *) handle);
3821 if (resource == NULL)
3823 OIC_LOG(ERROR, TAG, "Resource not found");
3824 return OC_STACK_NO_RESOURCE;
3827 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3829 OIC_LOG(ERROR, TAG, "Error deleting resource");
3830 return OC_STACK_ERROR;
3836 const char *OCGetResourceUri(OCResourceHandle handle)
3838 OCResource *resource = NULL;
3840 resource = findResource((OCResource *) handle);
3843 return resource->uri;
3845 return (const char *) NULL;
3848 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3850 OCResource *resource = NULL;
3852 resource = findResource((OCResource *) handle);
3855 return resource->resourceProperties;
3857 return (OCResourceProperty)-1;
3860 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3861 uint8_t *numResourceTypes)
3863 OCResource *resource = NULL;
3864 OCResourceType *pointer = NULL;
3866 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3867 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3869 *numResourceTypes = 0;
3871 resource = findResource((OCResource *) handle);
3874 pointer = resource->rsrcType;
3877 *numResourceTypes = *numResourceTypes + 1;
3878 pointer = pointer->next;
3884 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3886 OCResourceType *resourceType = NULL;
3888 resourceType = findResourceTypeAtIndex(handle, index);
3891 return resourceType->resourcetypename;
3893 return (const char *) NULL;
3896 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3897 uint8_t *numResourceInterfaces)
3899 OCResourceInterface *pointer = NULL;
3900 OCResource *resource = NULL;
3902 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3903 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3905 *numResourceInterfaces = 0;
3906 resource = findResource((OCResource *) handle);
3909 pointer = resource->rsrcInterface;
3912 *numResourceInterfaces = *numResourceInterfaces + 1;
3913 pointer = pointer->next;
3919 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3921 OCResourceInterface *resourceInterface = NULL;
3923 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3924 if (resourceInterface)
3926 return resourceInterface->name;
3928 return (const char *) NULL;
3931 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3934 OCResource *resource = NULL;
3935 OCChildResource *tempChildResource = NULL;
3938 resource = findResource((OCResource *) collectionHandle);
3944 tempChildResource = resource->rsrcChildResourcesHead;
3946 while(tempChildResource)
3950 return tempChildResource->rsrcResource;
3953 tempChildResource = tempChildResource->next;
3956 // In this case, the number of resource handles in the collection exceeds the index
3957 tempChildResource = NULL;
3961 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3962 OCEntityHandler entityHandler,
3963 void* callbackParam)
3965 OCResource *resource = NULL;
3967 // Validate parameters
3968 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3970 // Use the handle to find the resource in the resource linked list
3971 resource = findResource((OCResource *)handle);
3974 OIC_LOG(ERROR, TAG, "Resource not found");
3975 return OC_STACK_ERROR;
3979 resource->entityHandler = entityHandler;
3980 resource->entityHandlerCallbackParam = callbackParam;
3982 #ifdef WITH_PRESENCE
3983 if (presenceResource.handle)
3985 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3986 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3993 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3995 OCResource *resource = NULL;
3997 resource = findResource((OCResource *)handle);
4000 OIC_LOG(ERROR, TAG, "Resource not found");
4005 return resource->entityHandler;
4008 void incrementSequenceNumber(OCResource * resPtr)
4010 // Increment the sequence number
4011 resPtr->sequenceNum += 1;
4012 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4014 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4019 #ifdef WITH_PRESENCE
4020 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4021 OCPresenceTrigger trigger)
4023 OCResource *resPtr = NULL;
4024 OCStackResult result = OC_STACK_ERROR;
4025 OCMethod method = OC_REST_PRESENCE;
4026 uint32_t maxAge = 0;
4027 resPtr = findResource((OCResource *) presenceResource.handle);
4030 return OC_STACK_NO_RESOURCE;
4033 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4035 maxAge = presenceResource.presenceTTL;
4037 result = SendAllObserverNotification(method, resPtr, maxAge,
4038 trigger, resourceType, OC_LOW_QOS);
4044 OCStackResult SendStopNotification()
4046 OCResource *resPtr = NULL;
4047 OCStackResult result = OC_STACK_ERROR;
4048 OCMethod method = OC_REST_PRESENCE;
4049 resPtr = findResource((OCResource *) presenceResource.handle);
4052 return OC_STACK_NO_RESOURCE;
4055 // maxAge is 0. ResourceType is NULL.
4056 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4062 #endif // WITH_PRESENCE
4063 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4065 OCResource *resPtr = NULL;
4066 OCStackResult result = OC_STACK_ERROR;
4067 OCMethod method = OC_REST_NOMETHOD;
4068 uint32_t maxAge = 0;
4070 OIC_LOG(INFO, TAG, "Notifying all observers");
4071 #ifdef WITH_PRESENCE
4072 if(handle == presenceResource.handle)
4076 #endif // WITH_PRESENCE
4077 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4079 // Verify that the resource exists
4080 resPtr = findResource ((OCResource *) handle);
4083 return OC_STACK_NO_RESOURCE;
4087 //only increment in the case of regular observing (not presence)
4088 incrementSequenceNumber(resPtr);
4089 method = OC_REST_OBSERVE;
4090 maxAge = MAX_OBSERVE_AGE;
4091 #ifdef WITH_PRESENCE
4092 result = SendAllObserverNotification (method, resPtr, maxAge,
4093 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4095 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4102 OCNotifyListOfObservers (OCResourceHandle handle,
4103 OCObservationId *obsIdList,
4104 uint8_t numberOfIds,
4105 const OCRepPayload *payload,
4106 OCQualityOfService qos)
4108 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4110 OCResource *resPtr = NULL;
4111 //TODO: we should allow the server to define this
4112 uint32_t maxAge = MAX_OBSERVE_AGE;
4114 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4115 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4116 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4118 resPtr = findResource ((OCResource *) handle);
4119 if (NULL == resPtr || myStackMode == OC_CLIENT)
4121 return OC_STACK_NO_RESOURCE;
4125 incrementSequenceNumber(resPtr);
4127 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4128 payload, maxAge, qos));
4131 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4133 OCStackResult result = OC_STACK_ERROR;
4134 OCServerRequest *serverRequest = NULL;
4136 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4138 // Validate input parameters
4139 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4140 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4143 // Get pointer to request info
4144 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4147 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4148 result = serverRequest->ehResponseHandler(ehResponse);
4154 //#ifdef DIRECT_PAIRING
4155 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4157 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4158 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4160 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4164 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4167 const OCDPDev_t* OCGetDirectPairedDevices()
4169 return (const OCDPDev_t*)DPGetPairedDevices();
4172 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4173 OCDirectPairingCB resultCallback)
4175 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4176 if(NULL == peer || NULL == pinNumber)
4178 OIC_LOG(ERROR, TAG, "Invalid parameters");
4179 return OC_STACK_INVALID_PARAM;
4181 if (NULL == resultCallback)
4183 OIC_LOG(ERROR, TAG, "Invalid callback");
4184 return OC_STACK_INVALID_CALLBACK;
4187 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4188 pinNumber, (OCDirectPairingResultCB)resultCallback);
4190 //#endif // DIRECT_PAIRING
4192 //-----------------------------------------------------------------------------
4193 // Private internal function definitions
4194 //-----------------------------------------------------------------------------
4195 static OCDoHandle GenerateInvocationHandle()
4197 OCDoHandle handle = NULL;
4198 // Generate token here, it will be deleted when the transaction is deleted
4199 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4202 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4208 #ifdef WITH_PRESENCE
4209 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4210 OCResourceProperty resourceProperties, uint8_t enable)
4214 return OC_STACK_INVALID_PARAM;
4216 if (resourceProperties
4217 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4219 OIC_LOG(ERROR, TAG, "Invalid property");
4220 return OC_STACK_INVALID_PARAM;
4224 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4228 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4234 OCStackResult initResources()
4236 OCStackResult result = OC_STACK_OK;
4238 headResource = NULL;
4239 tailResource = NULL;
4240 // Init Virtual Resources
4241 #ifdef WITH_PRESENCE
4242 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4244 result = OCCreateResource(&presenceResource.handle,
4245 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4247 OC_RSRVD_PRESENCE_URI,
4251 //make resource inactive
4252 result = OCChangeResourceProperty(
4253 &(((OCResource *) presenceResource.handle)->resourceProperties),
4256 #ifndef WITH_ARDUINO
4257 if (result == OC_STACK_OK)
4259 result = SRMInitSecureResources();
4263 if(result == OC_STACK_OK)
4265 CreateResetProfile();
4266 result = OCCreateResource(&deviceResource,
4267 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4268 OC_RSRVD_INTERFACE_DEFAULT,
4269 OC_RSRVD_DEVICE_URI,
4273 if(result == OC_STACK_OK)
4275 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4276 OC_RSRVD_INTERFACE_READ);
4280 if(result == OC_STACK_OK)
4282 result = OCCreateResource(&platformResource,
4283 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4284 OC_RSRVD_INTERFACE_DEFAULT,
4285 OC_RSRVD_PLATFORM_URI,
4289 if(result == OC_STACK_OK)
4291 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4292 OC_RSRVD_INTERFACE_READ);
4299 void insertResource(OCResource *resource)
4303 headResource = resource;
4304 tailResource = resource;
4308 tailResource->next = resource;
4309 tailResource = resource;
4311 resource->next = NULL;
4314 OCResource *findResource(OCResource *resource)
4316 OCResource *pointer = headResource;
4320 if (pointer == resource)
4324 pointer = pointer->next;
4329 void deleteAllResources()
4331 OCResource *pointer = headResource;
4332 OCResource *temp = NULL;
4336 temp = pointer->next;
4337 #ifdef WITH_PRESENCE
4338 if (pointer != (OCResource *) presenceResource.handle)
4340 #endif // WITH_PRESENCE
4341 deleteResource(pointer);
4342 #ifdef WITH_PRESENCE
4344 #endif // WITH_PRESENCE
4347 memset(&platformResource, 0, sizeof(platformResource));
4348 memset(&deviceResource, 0, sizeof(deviceResource));
4350 memset(&brokerResource, 0, sizeof(brokerResource));
4353 SRMDeInitSecureResources();
4355 #ifdef WITH_PRESENCE
4356 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4357 // presence notification attributed to their deletion to be processed.
4358 deleteResource((OCResource *) presenceResource.handle);
4359 memset(&presenceResource, 0, sizeof(presenceResource));
4360 #endif // WITH_PRESENCE
4363 OCStackResult deleteResource(OCResource *resource)
4365 OCResource *prev = NULL;
4366 OCResource *temp = NULL;
4369 OIC_LOG(DEBUG,TAG,"resource is NULL");
4370 return OC_STACK_INVALID_PARAM;
4373 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4375 temp = headResource;
4378 if (temp == resource)
4380 // Invalidate all Resource Properties.
4381 resource->resourceProperties = (OCResourceProperty) 0;
4382 #ifdef WITH_PRESENCE
4383 if(resource != (OCResource *) presenceResource.handle)
4385 #endif // WITH_PRESENCE
4386 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4387 #ifdef WITH_PRESENCE
4390 if(presenceResource.handle)
4392 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4393 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4396 // Only resource in list.
4397 if (temp == headResource && temp == tailResource)
4399 headResource = NULL;
4400 tailResource = NULL;
4403 else if (temp == headResource)
4405 headResource = temp->next;
4408 else if (temp == tailResource)
4410 tailResource = prev;
4411 tailResource->next = NULL;
4415 prev->next = temp->next;
4418 deleteResourceElements(temp);
4429 return OC_STACK_ERROR;
4432 void deleteResourceElements(OCResource *resource)
4439 OICFree(resource->uri);
4440 deleteResourceType(resource->rsrcType);
4441 deleteResourceInterface(resource->rsrcInterface);
4444 void deleteResourceType(OCResourceType *resourceType)
4446 OCResourceType *pointer = resourceType;
4447 OCResourceType *next = NULL;
4451 next = pointer->next;
4452 OICFree(pointer->resourcetypename);
4458 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4460 OCResourceInterface *pointer = resourceInterface;
4461 OCResourceInterface *next = NULL;
4465 next = pointer->next;
4466 OICFree(pointer->name);
4472 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4474 OCResourceType *pointer = NULL;
4475 OCResourceType *previous = NULL;
4476 if (!resource || !resourceType)
4480 // resource type list is empty.
4481 else if (!resource->rsrcType)
4483 resource->rsrcType = resourceType;
4487 pointer = resource->rsrcType;
4491 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4493 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4494 OICFree(resourceType->resourcetypename);
4495 OICFree(resourceType);
4499 pointer = pointer->next;
4504 previous->next = resourceType;
4507 resourceType->next = NULL;
4509 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4512 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4514 OCResource *resource = NULL;
4515 OCResourceType *pointer = NULL;
4517 // Find the specified resource
4518 resource = findResource((OCResource *) handle);
4524 // Make sure a resource has a resourcetype
4525 if (!resource->rsrcType)
4530 // Iterate through the list
4531 pointer = resource->rsrcType;
4532 for(uint8_t i = 0; i< index && pointer; ++i)
4534 pointer = pointer->next;
4539 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4541 if(resourceTypeList && resourceTypeName)
4543 OCResourceType * rtPointer = resourceTypeList;
4544 while(resourceTypeName && rtPointer)
4546 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4547 if(rtPointer->resourcetypename &&
4548 strcmp(resourceTypeName, (const char *)
4549 (rtPointer->resourcetypename)) == 0)
4553 rtPointer = rtPointer->next;
4561 * Insert a new interface into interface linked list only if not already present.
4562 * If alredy present, 2nd arg is free'd.
4563 * Default interface will always be first if present.
4565 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4567 OCResourceInterface *pointer = NULL;
4568 OCResourceInterface *previous = NULL;
4570 newInterface->next = NULL;
4572 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4574 if (!*firstInterface)
4576 // If first interface is not oic.if.baseline, by default add it as first interface type.
4577 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4579 *firstInterface = newInterface;
4583 OCStackResult result = BindResourceInterfaceToResource(resource,
4584 OC_RSRVD_INTERFACE_DEFAULT);
4585 if (result != OC_STACK_OK)
4587 OICFree(newInterface->name);
4588 OICFree(newInterface);
4591 if (*firstInterface)
4593 (*firstInterface)->next = newInterface;
4597 // If once add oic.if.baseline, later too below code take care of freeing memory.
4598 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4600 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4602 OICFree(newInterface->name);
4603 OICFree(newInterface);
4606 // This code will not hit anymore, keeping
4609 newInterface->next = *firstInterface;
4610 *firstInterface = newInterface;
4615 pointer = *firstInterface;
4618 if (strcmp(newInterface->name, pointer->name) == 0)
4620 OICFree(newInterface->name);
4621 OICFree(newInterface);
4625 pointer = pointer->next;
4630 previous->next = newInterface;
4635 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4638 OCResource *resource = NULL;
4639 OCResourceInterface *pointer = NULL;
4641 // Find the specified resource
4642 resource = findResource((OCResource *) handle);
4648 // Make sure a resource has a resourceinterface
4649 if (!resource->rsrcInterface)
4654 // Iterate through the list
4655 pointer = resource->rsrcInterface;
4657 for (uint8_t i = 0; i < index && pointer; ++i)
4659 pointer = pointer->next;
4665 * This function splits the uri using the '?' delimiter.
4666 * "uriWithoutQuery" is the block of characters between the beginning
4667 * till the delimiter or '\0' which ever comes first.
4668 * "query" is whatever is to the right of the delimiter if present.
4669 * No delimiter sets the query to NULL.
4670 * If either are present, they will be malloc'ed into the params 2, 3.
4671 * The first param, *uri is left untouched.
4673 * NOTE: This function does not account for whitespace at the end of the uri NOR
4674 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4675 * part of the query.
4677 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4681 return OC_STACK_INVALID_URI;
4683 if(!query || !uriWithoutQuery)
4685 return OC_STACK_INVALID_PARAM;
4689 *uriWithoutQuery = NULL;
4691 size_t uriWithoutQueryLen = 0;
4692 size_t queryLen = 0;
4693 size_t uriLen = strlen(uri);
4695 char *pointerToDelimiter = strstr(uri, "?");
4697 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4698 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4700 if (uriWithoutQueryLen)
4702 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4703 if (!*uriWithoutQuery)
4707 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4711 *query = (char *) OICCalloc(queryLen + 1, 1);
4714 OICFree(*uriWithoutQuery);
4715 *uriWithoutQuery = NULL;
4718 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4724 return OC_STACK_NO_MEMORY;
4727 static const OicUuid_t* OCGetServerInstanceID(void)
4729 static bool generated = false;
4730 static OicUuid_t sid;
4736 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4738 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4745 const char* OCGetServerInstanceIDString(void)
4747 static bool generated = false;
4748 static char sidStr[UUID_STRING_SIZE];
4755 const OicUuid_t *sid = OCGetServerInstanceID();
4756 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4758 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4766 CAResult_t OCSelectNetwork()
4768 CAResult_t retResult = CA_STATUS_FAILED;
4769 CAResult_t caResult = CA_STATUS_OK;
4771 CATransportAdapter_t connTypes[] = {
4773 CA_ADAPTER_RFCOMM_BTEDR,
4774 CA_ADAPTER_GATT_BTLE,
4777 ,CA_ADAPTER_REMOTE_ACCESS
4784 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4786 for(int i = 0; i < numConnTypes; i++)
4788 // If CA status is not initialized, CASelectNetwork() will not be called.
4789 if (caResult != CA_STATUS_NOT_INITIALIZED)
4791 caResult = CASelectNetwork(connTypes[i]);
4792 if (caResult == CA_STATUS_OK)
4794 retResult = CA_STATUS_OK;
4799 if (retResult != CA_STATUS_OK)
4801 return caResult; // Returns error of appropriate transport that failed fatally.
4807 OCStackResult CAResultToOCResult(CAResult_t caResult)
4813 case CA_STATUS_INVALID_PARAM:
4814 return OC_STACK_INVALID_PARAM;
4815 case CA_ADAPTER_NOT_ENABLED:
4816 return OC_STACK_ADAPTER_NOT_ENABLED;
4817 case CA_SERVER_STARTED_ALREADY:
4819 case CA_SERVER_NOT_STARTED:
4820 return OC_STACK_ERROR;
4821 case CA_DESTINATION_NOT_REACHABLE:
4822 return OC_STACK_COMM_ERROR;
4823 case CA_SOCKET_OPERATION_FAILED:
4824 return OC_STACK_COMM_ERROR;
4825 case CA_SEND_FAILED:
4826 return OC_STACK_COMM_ERROR;
4827 case CA_RECEIVE_FAILED:
4828 return OC_STACK_COMM_ERROR;
4829 case CA_MEMORY_ALLOC_FAILED:
4830 return OC_STACK_NO_MEMORY;
4831 case CA_REQUEST_TIMEOUT:
4832 return OC_STACK_TIMEOUT;
4833 case CA_DESTINATION_DISCONNECTED:
4834 return OC_STACK_COMM_ERROR;
4835 case CA_STATUS_FAILED:
4836 return OC_STACK_ERROR;
4837 case CA_NOT_SUPPORTED:
4838 return OC_STACK_NOTIMPL;
4840 return OC_STACK_ERROR;
4844 bool OCResultToSuccess(OCStackResult ocResult)
4849 case OC_STACK_RESOURCE_CREATED:
4850 case OC_STACK_RESOURCE_DELETED:
4851 case OC_STACK_CONTINUE:
4852 case OC_STACK_RESOURCE_CHANGED:
4853 case OC_STACK_SLOW_RESOURCE:
4861 OCStackResult OCSetProxyURI(const char *uri)
4863 return CAResultToOCResult(CASetProxyUri(uri));
4867 #if defined(RD_CLIENT) || defined(RD_SERVER)
4868 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
4870 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4872 OCResource *resource = NULL;
4874 resource = findResource((OCResource *) handle);
4877 OIC_LOG(ERROR, TAG, "Resource not found");
4878 return OC_STACK_ERROR;
4881 resource->ins = ins;
4886 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
4890 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
4894 OCResource *pointer = headResource;
4898 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
4900 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
4903 pointer = pointer->next;
4908 OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
4910 OCResource *resource = NULL;
4912 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4913 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
4915 resource = findResource((OCResource *) handle);
4918 *ins = resource->ins;
4921 return OC_STACK_ERROR;
4924 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
4925 void* optionData, size_t optionDataLength)
4929 OIC_LOG (INFO, TAG, "Header options are NULL");
4930 return OC_STACK_INVALID_PARAM;
4935 OIC_LOG (INFO, TAG, "optionData are NULL");
4936 return OC_STACK_INVALID_PARAM;
4941 OIC_LOG (INFO, TAG, "numOptions is NULL");
4942 return OC_STACK_INVALID_PARAM;
4945 if (*numOptions >= MAX_HEADER_OPTIONS)
4947 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
4948 return OC_STACK_NO_MEMORY;
4951 ocHdrOpt += *numOptions;
4952 ocHdrOpt->protocolID = OC_COAP_ID;
4953 ocHdrOpt->optionID = optionID;
4954 ocHdrOpt->optionLength =
4955 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
4956 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
4957 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
4962 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
4963 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
4965 if (!ocHdrOpt || !numOptions)
4967 OIC_LOG (INFO, TAG, "No options present");
4973 OIC_LOG (INFO, TAG, "optionData are NULL");
4974 return OC_STACK_INVALID_PARAM;
4977 if (!receivedDataLength)
4979 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
4980 return OC_STACK_INVALID_PARAM;
4983 for (uint8_t i = 0; i < numOptions; i++)
4985 if (ocHdrOpt[i].optionID == optionID)
4987 if (optionDataLength >= ocHdrOpt->optionLength)
4989 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
4990 *receivedDataLength = ocHdrOpt->optionLength;
4995 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
4996 return OC_STACK_ERROR;
5004 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5006 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5007 if (g_adapterHandler)
5009 g_adapterHandler(adapter, enabled);
5013 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5015 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5016 if (g_connectionHandler)
5018 g_connectionHandler(info, isConnected);
5022 void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
5023 CAConnectionStateChangedCB connectionHandler)
5025 OIC_LOG(DEBUG, TAG, "OCSetNetworkMonitorHandler");
5026 g_adapterHandler = adapterHandler;
5027 g_connectionHandler = connectionHandler;