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,
994 char *presenceUri, bool isMulticast)
996 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
997 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1001 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1002 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1005 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1006 if (ep->adapter == CA_ADAPTER_IP)
1008 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1010 if ('\0' == ep->addr[0]) // multicast
1012 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1016 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1018 OCStackResult result = encodeAddressForRFC6874(addressEncoded,
1019 sizeof(addressEncoded),
1022 if (OC_STACK_OK != result)
1027 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1028 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1033 if ('\0' == ep->addr[0]) // multicast
1035 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1036 ep->port = OC_MULTICAST_PORT;
1038 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1039 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1043 // might work for other adapters (untested, but better than nothing)
1044 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1045 OC_RSRVD_PRESENCE_URI);
1049 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1050 const CAResponseInfo_t *responseInfo)
1052 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1053 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1055 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1056 ClientCB * cbNode = NULL;
1057 char *resourceTypeName = NULL;
1058 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1059 OCStackResult result = OC_STACK_ERROR;
1060 uint32_t maxAge = 0;
1062 char presenceUri[CA_MAX_URI_LENGTH];
1064 int presenceSubscribe = 0;
1065 int multicastPresenceSubscribe = 0;
1067 if (responseInfo->result != CA_CONTENT)
1069 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1070 return OC_STACK_ERROR;
1073 response.payload = NULL;
1074 response.result = OC_STACK_OK;
1076 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1077 FixUpClientResponse(&response);
1079 if (responseInfo->info.payload)
1081 result = OCParsePayload(&response.payload,
1082 PAYLOAD_TYPE_PRESENCE,
1083 responseInfo->info.payload,
1084 responseInfo->info.payloadSize);
1086 if(result != OC_STACK_OK)
1088 OIC_LOG(ERROR, TAG, "Presence parse failed");
1091 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1093 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1094 result = OC_STACK_ERROR;
1097 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1098 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1099 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1102 // check for unicast presence
1103 uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1104 responseInfo->isMulticast);
1105 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1107 return OC_STACK_INVALID_URI;
1109 OIC_LOG(ERROR, TAG, "check for unicast presence");
1110 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1113 presenceSubscribe = 1;
1117 // check for multicast presence
1118 OIC_LOG(ERROR, TAG, "check for multicast presence");
1119 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1122 multicastPresenceSubscribe = 1;
1126 if (!presenceSubscribe && !multicastPresenceSubscribe)
1128 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1132 if (presenceSubscribe)
1134 if(cbNode->sequenceNumber == response.sequenceNumber)
1136 OIC_LOG(INFO, TAG, "No presence change");
1137 ResetPresenceTTL(cbNode, maxAge);
1138 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1144 OIC_LOG(INFO, TAG, "Stopping presence");
1145 response.result = OC_STACK_PRESENCE_STOPPED;
1146 if(cbNode->presence)
1148 OICFree(cbNode->presence->timeOut);
1149 OICFree(cbNode->presence);
1150 cbNode->presence = NULL;
1155 if(!cbNode->presence)
1157 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1159 if(!(cbNode->presence))
1161 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1162 result = OC_STACK_NO_MEMORY;
1166 VERIFY_NON_NULL_V(cbNode->presence);
1167 cbNode->presence->timeOut = NULL;
1168 cbNode->presence->timeOut = (uint32_t *)
1169 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1170 if(!(cbNode->presence->timeOut)){
1172 "Could not allocate memory for cbNode->presence->timeOut");
1173 OICFree(cbNode->presence);
1174 result = OC_STACK_NO_MEMORY;
1179 ResetPresenceTTL(cbNode, maxAge);
1181 cbNode->sequenceNumber = response.sequenceNumber;
1183 // Ensure that a filter is actually applied.
1184 if( resourceTypeName && cbNode->filterResourceType)
1186 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1195 // This is the multicast case
1196 OCMulticastNode* mcNode = NULL;
1197 mcNode = GetMCPresenceNode(presenceUri);
1201 if(mcNode->nonce == response.sequenceNumber)
1203 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1206 mcNode->nonce = response.sequenceNumber;
1210 OIC_LOG(INFO, TAG, "Stopping presence");
1211 response.result = OC_STACK_PRESENCE_STOPPED;
1216 char* uri = OICStrdup(presenceUri);
1220 "No Memory for URI to store in the presence node");
1221 result = OC_STACK_NO_MEMORY;
1225 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1226 if(result == OC_STACK_NO_MEMORY)
1229 "No Memory for Multicast Presence Node");
1233 // presence node now owns uri
1238 // Ensure that a filter is actually applied.
1239 if(resourceTypeName && cbNode->filterResourceType)
1241 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1242 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1248 OIC_LOG(INFO, TAG, "Callback for presence");
1250 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1252 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1254 FindAndDeleteClientCB(cbNode);
1258 OCPayloadDestroy(response.payload);
1262 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1264 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1266 if(responseInfo->info.resourceUri &&
1267 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1269 HandlePresenceResponse(endPoint, responseInfo);
1273 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1274 responseInfo->info.tokenLength, NULL, NULL);
1276 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1277 responseInfo->info.tokenLength);
1281 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1282 if(responseInfo->result == CA_EMPTY)
1284 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1285 // We do not have a case for the client to receive a RESET
1286 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1288 //This is the case of receiving an ACK on a request to a slow resource!
1289 OIC_LOG(INFO, TAG, "This is a pure ACK");
1290 //TODO: should we inform the client
1291 // app that at least the request was received at the server?
1294 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1296 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1297 OIC_LOG(INFO, TAG, "Calling into application address space");
1299 OCClientResponse response =
1300 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1301 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1302 FixUpClientResponse(&response);
1303 response.resourceUri = responseInfo->info.resourceUri;
1304 memcpy(response.identity.id, responseInfo->info.identity.id,
1305 sizeof (response.identity.id));
1306 response.identity.id_length = responseInfo->info.identity.id_length;
1308 response.result = CAResponseToOCStackResult(responseInfo->result);
1309 cbNode->callBack(cbNode->context,
1310 cbNode->handle, &response);
1311 FindAndDeleteClientCB(cbNode);
1315 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1316 OIC_LOG(INFO, TAG, "Calling into application address space");
1318 OCClientResponse response =
1319 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1320 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1321 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1322 FixUpClientResponse(&response);
1323 response.resourceUri = responseInfo->info.resourceUri;
1324 memcpy(response.identity.id, responseInfo->info.identity.id,
1325 sizeof (response.identity.id));
1326 response.identity.id_length = responseInfo->info.identity.id_length;
1328 response.result = CAResponseToOCStackResult(responseInfo->result);
1330 if(responseInfo->info.payload &&
1331 responseInfo->info.payloadSize)
1333 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1334 // check the security resource
1335 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1337 type = PAYLOAD_TYPE_SECURITY;
1339 else if (cbNode->method == OC_REST_DISCOVER)
1341 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1342 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1344 type = PAYLOAD_TYPE_DISCOVERY;
1347 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1349 type = PAYLOAD_TYPE_DISCOVERY;
1352 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1354 type = PAYLOAD_TYPE_DEVICE;
1356 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1358 type = PAYLOAD_TYPE_PLATFORM;
1360 #ifdef ROUTING_GATEWAY
1361 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1363 type = PAYLOAD_TYPE_REPRESENTATION;
1366 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1368 type = PAYLOAD_TYPE_REPRESENTATION ;
1371 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1373 type = PAYLOAD_TYPE_REPRESENTATION;
1378 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1379 cbNode->method, cbNode->requestUri);
1383 else if (cbNode->method == OC_REST_GET ||
1384 cbNode->method == OC_REST_PUT ||
1385 cbNode->method == OC_REST_POST ||
1386 cbNode->method == OC_REST_OBSERVE ||
1387 cbNode->method == OC_REST_OBSERVE_ALL ||
1388 cbNode->method == OC_REST_DELETE)
1390 if (cbNode->requestUri)
1392 if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1394 type = PAYLOAD_TYPE_PLATFORM;
1396 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1398 type = PAYLOAD_TYPE_DEVICE;
1400 if (type == PAYLOAD_TYPE_INVALID)
1402 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1403 cbNode->method, cbNode->requestUri);
1404 type = PAYLOAD_TYPE_REPRESENTATION;
1409 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1410 type = PAYLOAD_TYPE_REPRESENTATION;
1415 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1416 cbNode->method, cbNode->requestUri);
1420 if(OC_STACK_OK != OCParsePayload(&response.payload,
1422 responseInfo->info.payload,
1423 responseInfo->info.payloadSize))
1425 OIC_LOG(ERROR, TAG, "Error converting payload");
1426 OCPayloadDestroy(response.payload);
1431 response.numRcvdVendorSpecificHeaderOptions = 0;
1432 if(responseInfo->info.numOptions > 0)
1435 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1436 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1439 uint32_t observationOption;
1440 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1441 for (observationOption=0, i=0;
1442 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1446 (observationOption << 8) | optionData[i];
1448 response.sequenceNumber = observationOption;
1449 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1454 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1457 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1459 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1460 OCPayloadDestroy(response.payload);
1464 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1466 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1467 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1471 if (cbNode->method == OC_REST_OBSERVE &&
1472 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1473 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1474 response.sequenceNumber <= cbNode->sequenceNumber)
1476 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1477 response.sequenceNumber);
1481 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1484 cbNode->sequenceNumber = response.sequenceNumber;
1486 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1488 FindAndDeleteClientCB(cbNode);
1492 // To keep discovery callbacks active.
1493 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1494 MILLISECONDS_PER_SECOND);
1498 //Need to send ACK when the response is CON
1499 if(responseInfo->info.type == CA_MSG_CONFIRM)
1501 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1502 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1505 OCPayloadDestroy(response.payload);
1512 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1513 if(responseInfo->result == CA_EMPTY)
1515 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1516 if(responseInfo->info.type == CA_MSG_RESET)
1518 OIC_LOG(INFO, TAG, "This is a RESET");
1519 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1520 OC_OBSERVER_NOT_INTERESTED);
1522 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1524 OIC_LOG(INFO, TAG, "This is a pure ACK");
1525 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1526 OC_OBSERVER_STILL_INTERESTED);
1529 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1531 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1532 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1533 OC_OBSERVER_FAILED_COMM);
1538 if(!cbNode && !observer)
1540 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1541 || myStackMode == OC_GATEWAY)
1543 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1544 if(responseInfo->result == CA_EMPTY)
1546 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1550 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1551 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1552 CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1556 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1557 || myStackMode == OC_GATEWAY)
1559 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1560 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1562 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1563 responseInfo->info.messageId);
1565 if (responseInfo->info.type == CA_MSG_RESET)
1567 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1568 responseInfo->info.messageId);
1576 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1578 VERIFY_NON_NULL_NR(endPoint, FATAL);
1579 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1581 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1583 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1584 #ifdef ROUTING_GATEWAY
1585 bool needRIHandling = false;
1587 * Routing manager is going to update either of endpoint or response or both.
1588 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1589 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1592 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1594 if(ret != OC_STACK_OK || !needRIHandling)
1596 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1602 * Put source in sender endpoint so that the next packet from application can be routed to
1603 * proper destination and remove "RM" coap header option before passing request / response to
1604 * RI as this option will make no sense to either RI or application.
1606 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1607 (uint8_t *) &(responseInfo->info.numOptions),
1608 (CAEndpoint_t *) endPoint);
1611 OCHandleResponse(endPoint, responseInfo);
1613 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1617 * This function handles error response from CA
1618 * code shall be added to handle the errors
1620 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1622 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1624 if (NULL == endPoint)
1626 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1630 if (NULL == errorInfo)
1632 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1636 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1637 errorInfo->info.tokenLength, NULL, NULL);
1640 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1641 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1642 FixUpClientResponse(&response);
1643 response.resourceUri = errorInfo->info.resourceUri;
1644 memcpy(response.identity.id, errorInfo->info.identity.id,
1645 sizeof (response.identity.id));
1646 response.identity.id_length = errorInfo->info.identity.id_length;
1647 response.result = CAResultToOCStackResult(errorInfo->result);
1649 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1652 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1656 * This function sends out Direct Stack Responses. These are responses that are not coming
1657 * from the application entity handler. These responses have no payload and are usually ACKs,
1658 * RESETs or some error conditions that were caught by the stack.
1660 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1661 const CAResponseResult_t responseResult, const CAMessageType_t type,
1662 const uint8_t numOptions, const CAHeaderOption_t *options,
1663 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1664 CADataType_t dataType)
1666 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1667 CAResponseInfo_t respInfo = {
1668 .result = responseResult
1670 respInfo.info.messageId = coapID;
1671 respInfo.info.numOptions = numOptions;
1673 if (respInfo.info.numOptions)
1675 respInfo.info.options =
1676 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1677 memcpy (respInfo.info.options, options,
1678 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1682 respInfo.info.payload = NULL;
1683 respInfo.info.token = token;
1684 respInfo.info.tokenLength = tokenLength;
1685 respInfo.info.type = type;
1686 respInfo.info.resourceUri = OICStrdup (resourceUri);
1687 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1688 respInfo.info.dataType = dataType;
1690 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1691 // Add the destination to route option from the endpoint->routeData.
1692 bool doPost = false;
1693 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1694 if(OC_STACK_OK != result)
1696 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1701 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1702 CARequestInfo_t reqInfo = {.method = CA_POST };
1703 /* The following initialization is not done in a single initializer block as in
1704 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1705 * does not have designated initalizers. This is a work-around for now.
1707 reqInfo.info.type = CA_MSG_NONCONFIRM;
1708 reqInfo.info.messageId = coapID;
1709 reqInfo.info.tokenLength = tokenLength;
1710 reqInfo.info.token = token;
1711 reqInfo.info.numOptions = respInfo.info.numOptions;
1712 reqInfo.info.payload = NULL;
1713 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1714 if (reqInfo.info.numOptions)
1716 reqInfo.info.options =
1717 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1718 if (NULL == reqInfo.info.options)
1720 OIC_LOG(ERROR, TAG, "Calloc failed");
1721 return OC_STACK_NO_MEMORY;
1723 memcpy (reqInfo.info.options, respInfo.info.options,
1724 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1727 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1728 OICFree (reqInfo.info.resourceUri);
1729 OICFree (reqInfo.info.options);
1730 OICFree (respInfo.info.resourceUri);
1731 OICFree (respInfo.info.options);
1732 if (CA_STATUS_OK != caResult)
1734 OIC_LOG(ERROR, TAG, "CASendRequest error");
1735 return CAResultToOCResult(caResult);
1741 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1743 // resourceUri in the info field is cloned in the CA layer and
1744 // thus ownership is still here.
1745 OICFree (respInfo.info.resourceUri);
1746 OICFree (respInfo.info.options);
1747 if(CA_STATUS_OK != caResult)
1749 OIC_LOG(ERROR, TAG, "CASendResponse error");
1750 return CAResultToOCResult(caResult);
1753 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1757 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1759 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1760 OCStackResult result = OC_STACK_ERROR;
1761 if(!protocolRequest)
1763 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1764 return OC_STACK_INVALID_PARAM;
1767 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1768 protocolRequest->tokenLength);
1771 OIC_LOG(INFO, TAG, "This is a new Server Request");
1772 result = AddServerRequest(&request, protocolRequest->coapID,
1773 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1774 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1775 protocolRequest->observationOption, protocolRequest->qos,
1776 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1777 protocolRequest->payload, protocolRequest->requestToken,
1778 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1779 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1780 &protocolRequest->devAddr);
1781 if (OC_STACK_OK != result)
1783 OIC_LOG(ERROR, TAG, "Error adding server request");
1789 OIC_LOG(ERROR, TAG, "Out of Memory");
1790 return OC_STACK_NO_MEMORY;
1793 if(!protocolRequest->reqMorePacket)
1795 request->requestComplete = 1;
1800 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1803 if(request->requestComplete)
1805 OIC_LOG(INFO, TAG, "This Server Request is complete");
1806 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1807 OCResource *resource = NULL;
1808 result = DetermineResourceHandling (request, &resHandling, &resource);
1809 if (result == OC_STACK_OK)
1811 result = ProcessRequest(resHandling, resource, request);
1816 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1817 result = OC_STACK_CONTINUE;
1822 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1824 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1827 if (requestInfo->info.resourceUri &&
1828 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1830 HandleKeepAliveRequest(endPoint, requestInfo);
1835 OCStackResult requestResult = OC_STACK_ERROR;
1837 if(myStackMode == OC_CLIENT)
1839 //TODO: should the client be responding to requests?
1843 OCServerProtocolRequest serverRequest = {0};
1845 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1847 char * uriWithoutQuery = NULL;
1848 char * query = NULL;
1850 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1852 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1854 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1857 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1858 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1860 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1862 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1863 OICFree(uriWithoutQuery);
1867 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1868 OICFree(uriWithoutQuery);
1875 if(strlen(query) < MAX_QUERY_LENGTH)
1877 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1882 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1888 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1890 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1891 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1892 if (!serverRequest.payload)
1894 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1897 memcpy (serverRequest.payload, requestInfo->info.payload,
1898 requestInfo->info.payloadSize);
1902 serverRequest.reqTotalSize = 0;
1905 switch (requestInfo->method)
1908 serverRequest.method = OC_REST_GET;
1911 serverRequest.method = OC_REST_PUT;
1914 serverRequest.method = OC_REST_POST;
1917 serverRequest.method = OC_REST_DELETE;
1920 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1921 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1922 requestInfo->info.type, requestInfo->info.numOptions,
1923 requestInfo->info.options, requestInfo->info.token,
1924 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1926 OICFree(serverRequest.payload);
1930 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1931 requestInfo->info.tokenLength);
1933 serverRequest.tokenLength = requestInfo->info.tokenLength;
1934 if (serverRequest.tokenLength) {
1936 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1938 if (!serverRequest.requestToken)
1940 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1941 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1942 requestInfo->info.type, requestInfo->info.numOptions,
1943 requestInfo->info.options, requestInfo->info.token,
1944 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1946 OICFree(serverRequest.payload);
1949 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1952 switch (requestInfo->info.acceptFormat)
1954 case CA_FORMAT_APPLICATION_CBOR:
1955 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1957 case CA_FORMAT_UNDEFINED:
1958 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1961 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1964 if (requestInfo->info.type == CA_MSG_CONFIRM)
1966 serverRequest.qos = OC_HIGH_QOS;
1970 serverRequest.qos = OC_LOW_QOS;
1972 // CA does not need the following field
1973 // Are we sure CA does not need them? how is it responding to multicast
1974 serverRequest.delayedResNeeded = 0;
1976 serverRequest.coapID = requestInfo->info.messageId;
1978 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1980 // copy vendor specific header options
1981 uint8_t tempNum = (requestInfo->info.numOptions);
1983 // Assume no observation requested and it is a pure GET.
1984 // If obs registration/de-registration requested it'll be fetched from the
1985 // options in GetObserveHeaderOption()
1986 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1988 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1989 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1992 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1993 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1994 requestInfo->info.type, requestInfo->info.numOptions,
1995 requestInfo->info.options, requestInfo->info.token,
1996 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1998 OICFree(serverRequest.payload);
1999 OICFree(serverRequest.requestToken);
2002 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2003 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
2005 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
2006 sizeof(CAHeaderOption_t)*tempNum);
2009 requestResult = HandleStackRequests (&serverRequest);
2011 // Send ACK to client as precursor to slow response
2012 if (requestResult == OC_STACK_SLOW_RESOURCE)
2014 if (requestInfo->info.type == CA_MSG_CONFIRM)
2016 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2017 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2021 if (requestResult == OC_STACK_RESOURCE_ERROR
2022 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2024 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2026 else if(!OCResultToSuccess(requestResult))
2028 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2030 CAResponseResult_t stackResponse =
2031 OCToCAStackResult(requestResult, serverRequest.method);
2033 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2034 requestInfo->info.type, requestInfo->info.numOptions,
2035 requestInfo->info.options, requestInfo->info.token,
2036 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2039 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2040 // The token is copied in there, and is thus still owned by this function.
2041 OICFree(serverRequest.payload);
2042 OICFree(serverRequest.requestToken);
2043 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2046 //This function will be called back by CA layer when a request is received
2047 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2049 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2052 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2058 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2062 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2063 #ifdef ROUTING_GATEWAY
2064 bool needRIHandling = false;
2065 bool isEmptyMsg = false;
2067 * Routing manager is going to update either of endpoint or request or both.
2068 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2069 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2070 * destination. It can also remove "RM" coap header option before passing request / response to
2071 * RI as this option will make no sense to either RI or application.
2073 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2074 &needRIHandling, &isEmptyMsg);
2075 if(OC_STACK_OK != ret || !needRIHandling)
2077 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2083 * Put source in sender endpoint so that the next packet from application can be routed to
2084 * proper destination and remove RM header option.
2086 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2087 (uint8_t *) &(requestInfo->info.numOptions),
2088 (CAEndpoint_t *) endPoint);
2090 #ifdef ROUTING_GATEWAY
2094 * In Gateways, the MSGType in route option is used to check if the actual
2095 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2096 * EMPTY response is sent in the form of POST request which need to be changed
2097 * to a EMPTY response by RM. This translation is done in this part of the code.
2099 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2100 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2101 .info.messageId = requestInfo->info.messageId,
2102 .info.type = CA_MSG_ACKNOWLEDGE};
2103 OCHandleResponse(endPoint, &respInfo);
2109 // Normal handling of the packet
2110 OCHandleRequests(endPoint, requestInfo);
2112 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2115 bool validatePlatformInfo(OCPlatformInfo info)
2118 if (!info.platformID)
2120 OIC_LOG(ERROR, TAG, "No platform ID found.");
2124 if (info.manufacturerName)
2126 size_t lenManufacturerName = strlen(info.manufacturerName);
2128 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2130 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2136 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2140 if (info.manufacturerUrl)
2142 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2144 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2151 //-----------------------------------------------------------------------------
2153 //-----------------------------------------------------------------------------
2155 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2158 !raInfo->username ||
2159 !raInfo->hostname ||
2160 !raInfo->xmpp_domain)
2163 return OC_STACK_INVALID_PARAM;
2165 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2166 gRASetInfo = (result == OC_STACK_OK)? true : false;
2172 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2176 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2179 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2181 if(stackState == OC_STACK_INITIALIZED)
2183 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2184 OCStop() between them are ignored.");
2188 #ifndef ROUTING_GATEWAY
2189 if (OC_GATEWAY == mode)
2191 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2192 return OC_STACK_INVALID_PARAM;
2199 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2200 return OC_STACK_ERROR;
2204 OCStackResult result = OC_STACK_ERROR;
2205 OIC_LOG(INFO, TAG, "Entering OCInit");
2208 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2209 || (mode == OC_GATEWAY)))
2211 OIC_LOG(ERROR, TAG, "Invalid mode");
2212 return OC_STACK_ERROR;
2216 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2218 caglobals.client = true;
2220 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2222 caglobals.server = true;
2225 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2226 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2228 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2230 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2231 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2233 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2236 defaultDeviceHandler = NULL;
2237 defaultDeviceHandlerCallbackParameter = NULL;
2239 result = InitializeScheduleResourceList();
2240 VERIFY_SUCCESS(result, OC_STACK_OK);
2242 result = CAResultToOCResult(CAInitialize());
2243 VERIFY_SUCCESS(result, OC_STACK_OK);
2245 result = CAResultToOCResult(OCSelectNetwork());
2246 VERIFY_SUCCESS(result, OC_STACK_OK);
2248 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2249 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2250 VERIFY_SUCCESS(result, OC_STACK_OK);
2252 switch (myStackMode)
2255 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2256 result = CAResultToOCResult(CAStartDiscoveryServer());
2257 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2260 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2261 result = CAResultToOCResult(CAStartListeningServer());
2262 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2264 case OC_CLIENT_SERVER:
2266 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2267 result = CAResultToOCResult(CAStartListeningServer());
2268 if(result == OC_STACK_OK)
2270 result = CAResultToOCResult(CAStartDiscoveryServer());
2274 VERIFY_SUCCESS(result, OC_STACK_OK);
2277 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2280 #ifdef WITH_PRESENCE
2281 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2282 #endif // WITH_PRESENCE
2284 //Update Stack state to initialized
2285 stackState = OC_STACK_INITIALIZED;
2287 // Initialize resource
2288 if(myStackMode != OC_CLIENT)
2290 result = initResources();
2293 // Initialize the SRM Policy Engine
2294 if(result == OC_STACK_OK)
2296 result = SRMInitPolicyEngine();
2297 // TODO after BeachHead delivery: consolidate into single SRMInit()
2299 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2300 RMSetStackMode(mode);
2301 #ifdef ROUTING_GATEWAY
2302 if (OC_GATEWAY == myStackMode)
2304 result = RMInitialize();
2310 if (result == OC_STACK_OK)
2312 result = InitializeKeepAlive(myStackMode);
2317 if(result != OC_STACK_OK)
2319 OIC_LOG(ERROR, TAG, "Stack initialization error");
2320 deleteAllResources();
2322 TerminateScheduleResourceList();
2323 stackState = OC_STACK_UNINITIALIZED;
2328 OCStackResult OCStop()
2330 OIC_LOG(INFO, TAG, "Entering OCStop");
2332 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2334 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2337 else if (stackState != OC_STACK_INITIALIZED)
2339 OIC_LOG(ERROR, TAG, "Stack not initialized");
2340 return OC_STACK_ERROR;
2343 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2345 #ifdef WITH_PRESENCE
2346 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2347 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2348 presenceResource.presenceTTL = 0;
2349 #endif // WITH_PRESENCE
2351 #ifdef ROUTING_GATEWAY
2352 if (OC_GATEWAY == myStackMode)
2359 TerminateKeepAlive(myStackMode);
2362 // Free memory dynamically allocated for resources
2363 deleteAllResources();
2365 DeletePlatformInfo();
2367 TerminateScheduleResourceList();
2368 // Remove all observers
2369 DeleteObserverList();
2370 // Remove all the client callbacks
2371 DeleteClientCBList();
2373 // De-init the SRM Policy Engine
2374 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2375 SRMDeInitPolicyEngine();
2378 stackState = OC_STACK_UNINITIALIZED;
2382 OCStackResult OCStartMulticastServer()
2384 if(stackState != OC_STACK_INITIALIZED)
2386 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2387 return OC_STACK_ERROR;
2389 CAResult_t ret = CAStartListeningServer();
2390 if (CA_STATUS_OK != ret)
2392 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2393 return OC_STACK_ERROR;
2398 OCStackResult OCStopMulticastServer()
2400 CAResult_t ret = CAStopListeningServer();
2401 if (CA_STATUS_OK != ret)
2403 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2404 return OC_STACK_ERROR;
2409 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2414 return CA_MSG_CONFIRM;
2419 return CA_MSG_NONCONFIRM;
2424 * A request uri consists of the following components in order:
2427 * CoAP over UDP prefix "coap://"
2428 * CoAP over TCP prefix "coap+tcp://"
2429 * CoAP over DTLS prefix "coaps://"
2430 * CoAP over TLS prefix "coaps+tcp://"
2432 * IPv6 address "[1234::5678]"
2433 * IPv4 address "192.168.1.1"
2434 * optional port ":5683"
2435 * resource uri "/oc/core..."
2437 * for PRESENCE requests, extract resource type.
2439 static OCStackResult ParseRequestUri(const char *fullUri,
2440 OCTransportAdapter adapter,
2441 OCTransportFlags flags,
2442 OCDevAddr **devAddr,
2444 char **resourceType)
2446 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2448 OCStackResult result = OC_STACK_OK;
2449 OCDevAddr *da = NULL;
2453 // provide defaults for all returned values
2460 *resourceUri = NULL;
2464 *resourceType = NULL;
2467 // delimit url prefix, if any
2468 const char *start = fullUri;
2469 char *slash2 = strstr(start, "//");
2474 char *slash = strchr(start, '/');
2477 return OC_STACK_INVALID_URI;
2480 // process url scheme
2481 size_t prefixLen = slash2 - fullUri;
2485 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2486 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2492 // TODO: this logic should come in with unit tests exercising the various strings
2493 // processs url prefix, if any
2494 size_t urlLen = slash - start;
2498 if (urlLen && devAddr)
2499 { // construct OCDevAddr
2500 if (start[0] == '[')
2502 char *close = strchr(++start, ']');
2503 if (!close || close > slash)
2505 return OC_STACK_INVALID_URI;
2508 if (close[1] == ':')
2515 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2519 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2521 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2525 char *dot = strchr(start, '.');
2526 if (dot && dot < slash)
2528 colon = strchr(start, ':');
2529 end = (colon && colon < slash) ? colon : slash;
2534 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2538 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2540 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2548 if (len >= sizeof(da->addr))
2550 return OC_STACK_INVALID_URI;
2552 // collect port, if any
2553 if (colon && colon < slash)
2555 for (colon++; colon < slash; colon++)
2558 if (c < '0' || c > '9')
2560 return OC_STACK_INVALID_URI;
2562 port = 10 * port + c - '0';
2567 if (len >= sizeof(da->addr))
2569 return OC_STACK_INVALID_URI;
2572 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2575 return OC_STACK_NO_MEMORY;
2577 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2579 da->adapter = adapter;
2581 if (!strncmp(fullUri, "coaps", 5))
2583 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2588 // process resource uri, if any
2590 { // request uri and query
2591 size_t ulen = strlen(slash); // resource uri length
2592 size_t tlen = 0; // resource type length
2595 static const char strPresence[] = "/oic/ad?rt=";
2596 static const size_t lenPresence = sizeof(strPresence) - 1;
2597 if (!strncmp(slash, strPresence, lenPresence))
2599 type = slash + lenPresence;
2600 tlen = ulen - lenPresence;
2605 *resourceUri = (char *)OICMalloc(ulen + 1);
2608 result = OC_STACK_NO_MEMORY;
2611 strcpy(*resourceUri, slash);
2614 if (type && resourceType)
2616 *resourceType = (char *)OICMalloc(tlen + 1);
2619 result = OC_STACK_NO_MEMORY;
2623 OICStrcpy(*resourceType, (tlen+1), type);
2630 // free all returned values
2637 OICFree(*resourceUri);
2641 OICFree(*resourceType);
2646 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2650 char uri[CA_MAX_URI_LENGTH];
2652 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2654 *requestUri = OICStrdup(uri);
2657 return OC_STACK_NO_MEMORY;
2664 * Discover or Perform requests on a specified resource
2666 OCStackResult OCDoResource(OCDoHandle *handle,
2668 const char *requestUri,
2669 const OCDevAddr *destination,
2671 OCConnectivityType connectivityType,
2672 OCQualityOfService qos,
2673 OCCallbackData *cbData,
2674 OCHeaderOption *options,
2677 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2679 // Validate input parameters
2680 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2681 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2683 OCStackResult result = OC_STACK_ERROR;
2684 CAResult_t caResult;
2685 CAToken_t token = NULL;
2686 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2687 ClientCB *clientCB = NULL;
2688 OCDoHandle resHandle = NULL;
2689 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2690 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2692 OCTransportAdapter adapter;
2693 OCTransportFlags flags;
2694 // the request contents are put here
2695 CARequestInfo_t requestInfo = {.method = CA_GET};
2696 // requestUri will be parsed into the following three variables
2697 OCDevAddr *devAddr = NULL;
2698 char *resourceUri = NULL;
2699 char *resourceType = NULL;
2702 * Support original behavior with address on resourceUri argument.
2704 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2705 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2709 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2710 if (result != OC_STACK_OK)
2712 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2716 else if (!checkProxyUri(options, numOptions))
2718 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2725 case OC_REST_OBSERVE:
2726 case OC_REST_OBSERVE_ALL:
2727 requestInfo.method = CA_GET;
2730 requestInfo.method = CA_PUT;
2733 requestInfo.method = CA_POST;
2735 case OC_REST_DELETE:
2736 requestInfo.method = CA_DELETE;
2738 case OC_REST_DISCOVER:
2740 #ifdef WITH_PRESENCE
2741 case OC_REST_PRESENCE:
2743 if (destination || devAddr)
2745 requestInfo.isMulticast = false;
2749 tmpDevAddr.adapter = adapter;
2750 tmpDevAddr.flags = flags;
2751 destination = &tmpDevAddr;
2752 requestInfo.isMulticast = true;
2754 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
2755 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
2756 // replacing method type with GET.
2757 requestInfo.method = CA_GET;
2760 result = OC_STACK_INVALID_METHOD;
2764 if (!devAddr && !destination)
2766 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2767 result = OC_STACK_INVALID_PARAM;
2771 /* If not original behavior, use destination argument */
2772 if (destination && !devAddr)
2774 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2777 result = OC_STACK_NO_MEMORY;
2780 *devAddr = *destination;
2783 resHandle = GenerateInvocationHandle();
2786 result = OC_STACK_NO_MEMORY;
2790 caResult = CAGenerateToken(&token, tokenLength);
2791 if (caResult != CA_STATUS_OK)
2793 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2794 result= OC_STACK_ERROR;
2798 // fill in request data
2799 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2800 requestInfo.info.token = token;
2801 requestInfo.info.tokenLength = tokenLength;
2803 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2805 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2806 options, numOptions, OC_OBSERVE_REGISTER);
2807 if (result != OC_STACK_OK)
2811 requestInfo.info.numOptions = numOptions + 1;
2815 requestInfo.info.numOptions = numOptions;
2816 requestInfo.info.options =
2817 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2818 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2819 numOptions * sizeof(CAHeaderOption_t));
2822 CopyDevAddrToEndpoint(devAddr, &endpoint);
2827 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2830 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2833 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2837 requestInfo.info.payload = NULL;
2838 requestInfo.info.payloadSize = 0;
2839 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2842 // prepare for response
2843 #ifdef WITH_PRESENCE
2844 if (method == OC_REST_PRESENCE)
2846 char *presenceUri = NULL;
2847 result = OCPreparePresence(&endpoint, &presenceUri,
2848 requestInfo.isMulticast);
2849 if (OC_STACK_OK != result)
2854 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2855 // Presence notification will form a canonical uri to
2856 // look for callbacks into the application.
2859 OICFree(resourceUri);
2861 resourceUri = presenceUri;
2865 // update resourceUri onto requestInfo after check presence uri
2866 requestInfo.info.resourceUri = resourceUri;
2868 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2869 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2870 method, devAddr, resourceUri, resourceType, ttl);
2871 if (OC_STACK_OK != result)
2876 devAddr = NULL; // Client CB list entry now owns it
2877 resourceUri = NULL; // Client CB list entry now owns it
2878 resourceType = NULL; // Client CB list entry now owns it
2881 result = OCSendRequest(&endpoint, &requestInfo);
2882 if (OC_STACK_OK != result)
2889 *handle = resHandle;
2893 if (result != OC_STACK_OK)
2895 OIC_LOG(ERROR, TAG, "OCDoResource error");
2896 FindAndDeleteClientCB(clientCB);
2897 CADestroyToken(token);
2905 // This is the owner of the payload object, so we free it
2906 OCPayloadDestroy(payload);
2907 OICFree(requestInfo.info.payload);
2909 OICFree(resourceUri);
2910 OICFree(resourceType);
2911 OICFree(requestInfo.info.options);
2915 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2919 * This ftn is implemented one of two ways in the case of observation:
2921 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2922 * Remove the callback associated on client side.
2923 * When the next notification comes in from server,
2924 * reply with RESET message to server.
2925 * Keep in mind that the server will react to RESET only
2926 * if the last notification was sent as CON
2928 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2929 * and it is associated with an observe request
2930 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2931 * Send CON Observe request to server with
2932 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2933 * Remove the callback associated on client side.
2935 OCStackResult ret = OC_STACK_OK;
2936 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2937 CARequestInfo_t requestInfo = {.method = CA_GET};
2941 return OC_STACK_INVALID_PARAM;
2944 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2947 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2948 return OC_STACK_ERROR;
2951 switch (clientCB->method)
2953 case OC_REST_OBSERVE:
2954 case OC_REST_OBSERVE_ALL:
2956 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2958 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2960 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2962 FindAndDeleteClientCB(clientCB);
2966 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2968 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2969 requestInfo.info.token = clientCB->token;
2970 requestInfo.info.tokenLength = clientCB->tokenLength;
2972 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2973 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2975 return OC_STACK_ERROR;
2977 requestInfo.info.numOptions = numOptions + 1;
2978 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2981 ret = OCSendRequest(&endpoint, &requestInfo);
2983 if (requestInfo.info.options)
2985 OICFree (requestInfo.info.options);
2987 if (requestInfo.info.resourceUri)
2989 OICFree (requestInfo.info.resourceUri);
2994 case OC_REST_DISCOVER:
2995 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2996 clientCB->requestUri);
2997 FindAndDeleteClientCB(clientCB);
3000 #ifdef WITH_PRESENCE
3001 case OC_REST_PRESENCE:
3002 FindAndDeleteClientCB(clientCB);
3007 ret = OC_STACK_INVALID_METHOD;
3015 * @brief Register Persistent storage callback.
3016 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3018 * OC_STACK_OK - No errors; Success
3019 * OC_STACK_INVALID_PARAM - Invalid parameter
3021 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3023 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3024 if(!persistentStorageHandler)
3026 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3027 return OC_STACK_INVALID_PARAM;
3031 if( !persistentStorageHandler->open ||
3032 !persistentStorageHandler->close ||
3033 !persistentStorageHandler->read ||
3034 !persistentStorageHandler->unlink ||
3035 !persistentStorageHandler->write)
3037 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3038 return OC_STACK_INVALID_PARAM;
3041 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3044 #ifdef WITH_PRESENCE
3046 OCStackResult OCProcessPresence()
3048 OCStackResult result = OC_STACK_OK;
3050 // the following line floods the log with messages that are irrelevant
3051 // to most purposes. Uncomment as needed.
3052 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3053 ClientCB* cbNode = NULL;
3054 OCClientResponse clientResponse;
3055 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3057 LL_FOREACH(cbList, cbNode)
3059 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3064 uint32_t now = GetTicks(0);
3065 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3066 cbNode->presence->TTLlevel);
3067 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3069 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3074 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3076 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3077 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3079 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3081 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3083 clientResponse.sequenceNumber = 0;
3084 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3085 clientResponse.devAddr = *cbNode->devAddr;
3086 FixUpClientResponse(&clientResponse);
3087 clientResponse.payload = NULL;
3089 // Increment the TTLLevel (going to a next state), so we don't keep
3090 // sending presence notification to client.
3091 cbNode->presence->TTLlevel++;
3092 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3093 cbNode->presence->TTLlevel);
3095 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3096 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3098 FindAndDeleteClientCB(cbNode);
3102 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3107 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3108 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3109 CARequestInfo_t requestInfo = {.method = CA_GET};
3111 OIC_LOG(DEBUG, TAG, "time to test server presence");
3113 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3115 requestData.type = CA_MSG_NONCONFIRM;
3116 requestData.token = cbNode->token;
3117 requestData.tokenLength = cbNode->tokenLength;
3118 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3119 requestInfo.method = CA_GET;
3120 requestInfo.info = requestData;
3122 result = OCSendRequest(&endpoint, &requestInfo);
3123 if (OC_STACK_OK != result)
3128 cbNode->presence->TTLlevel++;
3129 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3132 if (result != OC_STACK_OK)
3134 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3139 #endif // WITH_PRESENCE
3141 OCStackResult OCProcess()
3143 #ifdef WITH_PRESENCE
3144 OCProcessPresence();
3146 CAHandleRequestResponse();
3148 #ifdef ROUTING_GATEWAY
3158 #ifdef WITH_PRESENCE
3159 OCStackResult OCStartPresence(const uint32_t ttl)
3161 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3162 OCChangeResourceProperty(
3163 &(((OCResource *)presenceResource.handle)->resourceProperties),
3166 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3168 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3169 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3173 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3174 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3178 presenceResource.presenceTTL = ttl;
3180 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3182 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3184 presenceState = OC_PRESENCE_INITIALIZED;
3186 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3188 CAToken_t caToken = NULL;
3189 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3190 if (caResult != CA_STATUS_OK)
3192 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3193 CADestroyToken(caToken);
3194 return OC_STACK_ERROR;
3197 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3198 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3199 CADestroyToken(caToken);
3202 // Each time OCStartPresence is called
3203 // a different random 32-bit integer number is used
3204 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3206 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3207 OC_PRESENCE_TRIGGER_CREATE);
3210 OCStackResult OCStopPresence()
3212 OCStackResult result = OC_STACK_ERROR;
3214 if(presenceResource.handle)
3216 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3218 // make resource inactive
3219 result = OCChangeResourceProperty(
3220 &(((OCResource *) presenceResource.handle)->resourceProperties),
3224 if(result != OC_STACK_OK)
3227 "Changing the presence resource properties to ACTIVE not successful");
3231 return SendStopNotification();
3235 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3236 void* callbackParameter)
3238 defaultDeviceHandler = entityHandler;
3239 defaultDeviceHandlerCallbackParameter = callbackParameter;
3244 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3246 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3248 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3250 if (validatePlatformInfo(platformInfo))
3252 return SavePlatformInfo(platformInfo);
3256 return OC_STACK_INVALID_PARAM;
3261 return OC_STACK_ERROR;
3265 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3267 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3269 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3271 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3272 return OC_STACK_INVALID_PARAM;
3275 if (deviceInfo.types)
3277 OCStringLL *type = deviceInfo.types;
3278 OCResource *resource = findResource((OCResource *) deviceResource);
3281 return OC_STACK_INVALID_PARAM;
3286 OCBindResourceTypeToResource(deviceResource, type->value);
3290 return SaveDeviceInfo(deviceInfo);
3293 OCStackResult OCCreateResource(OCResourceHandle *handle,
3294 const char *resourceTypeName,
3295 const char *resourceInterfaceName,
3296 const char *uri, OCEntityHandler entityHandler,
3297 void* callbackParam,
3298 uint8_t resourceProperties)
3301 OCResource *pointer = NULL;
3302 OCStackResult result = OC_STACK_ERROR;
3304 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3306 if(myStackMode == OC_CLIENT)
3308 return OC_STACK_INVALID_PARAM;
3310 // Validate parameters
3311 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3313 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3314 return OC_STACK_INVALID_URI;
3316 // Is it presented during resource discovery?
3317 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3319 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3320 return OC_STACK_INVALID_PARAM;
3323 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3325 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3329 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3331 // Make sure resourceProperties bitmask has allowed properties specified
3332 if (resourceProperties
3333 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3334 OC_EXPLICIT_DISCOVERABLE
3343 OIC_LOG(ERROR, TAG, "Invalid property");
3344 return OC_STACK_INVALID_PARAM;
3347 // If the headResource is NULL, then no resources have been created...
3348 pointer = headResource;
3351 // At least one resources is in the resource list, so we need to search for
3352 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3355 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3357 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3358 return OC_STACK_INVALID_PARAM;
3360 pointer = pointer->next;
3363 // Create the pointer and insert it into the resource list
3364 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3367 result = OC_STACK_NO_MEMORY;
3370 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3372 insertResource(pointer);
3375 pointer->uri = OICStrdup(uri);
3378 result = OC_STACK_NO_MEMORY;
3382 // Set properties. Set OC_ACTIVE
3383 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3386 // Add the resourcetype to the resource
3387 result = BindResourceTypeToResource(pointer, resourceTypeName);
3388 if (result != OC_STACK_OK)
3390 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3394 // Add the resourceinterface to the resource
3395 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3396 if (result != OC_STACK_OK)
3398 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3402 // If an entity handler has been passed, attach it to the newly created
3403 // resource. Otherwise, set the default entity handler.
3406 pointer->entityHandler = entityHandler;
3407 pointer->entityHandlerCallbackParam = callbackParam;
3411 pointer->entityHandler = defaultResourceEHandler;
3412 pointer->entityHandlerCallbackParam = NULL;
3415 // Initialize a pointer indicating child resources in case of collection
3416 pointer->rsrcChildResourcesHead = NULL;
3419 result = OC_STACK_OK;
3421 #ifdef WITH_PRESENCE
3422 if (presenceResource.handle)
3424 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3425 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3429 if (result != OC_STACK_OK)
3431 // Deep delete of resource and other dynamic elements that it contains
3432 deleteResource(pointer);
3437 OCStackResult OCBindResource(
3438 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3440 OCResource *resource = NULL;
3441 OCChildResource *tempChildResource = NULL;
3442 OCChildResource *newChildResource = NULL;
3444 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3446 // Validate parameters
3447 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3448 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3449 // Container cannot contain itself
3450 if (collectionHandle == resourceHandle)
3452 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3453 return OC_STACK_INVALID_PARAM;
3456 // Use the handle to find the resource in the resource linked list
3457 resource = findResource((OCResource *) collectionHandle);
3460 OIC_LOG(ERROR, TAG, "Collection handle not found");
3461 return OC_STACK_INVALID_PARAM;
3464 // Look for an open slot to add add the child resource.
3465 // If found, add it and return success
3467 tempChildResource = resource->rsrcChildResourcesHead;
3469 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3471 // TODO: what if one of child resource was deregistered without unbinding?
3472 tempChildResource = tempChildResource->next;
3475 // Do memory allocation for child resource
3476 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3477 if(!newChildResource)
3479 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3480 return OC_STACK_ERROR;
3483 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3484 newChildResource->next = NULL;
3486 if(!resource->rsrcChildResourcesHead)
3488 resource->rsrcChildResourcesHead = newChildResource;
3491 tempChildResource->next = newChildResource;
3494 OIC_LOG(INFO, TAG, "resource bound");
3496 #ifdef WITH_PRESENCE
3497 if (presenceResource.handle)
3499 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3500 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3501 OC_PRESENCE_TRIGGER_CHANGE);
3508 OCStackResult OCUnBindResource(
3509 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3511 OCResource *resource = NULL;
3512 OCChildResource *tempChildResource = NULL;
3513 OCChildResource *tempLastChildResource = NULL;
3515 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3517 // Validate parameters
3518 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3519 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3520 // Container cannot contain itself
3521 if (collectionHandle == resourceHandle)
3523 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3524 return OC_STACK_INVALID_PARAM;
3527 // Use the handle to find the resource in the resource linked list
3528 resource = findResource((OCResource *) collectionHandle);
3531 OIC_LOG(ERROR, TAG, "Collection handle not found");
3532 return OC_STACK_INVALID_PARAM;
3535 // Look for an open slot to add add the child resource.
3536 // If found, add it and return success
3537 if(!resource->rsrcChildResourcesHead)
3539 OIC_LOG(INFO, TAG, "resource not found in collection");
3541 // Unable to add resourceHandle, so return error
3542 return OC_STACK_ERROR;
3546 tempChildResource = resource->rsrcChildResourcesHead;
3548 while (tempChildResource)
3550 if(tempChildResource->rsrcResource == resourceHandle)
3552 // if resource going to be unbinded is the head one.
3553 if( tempChildResource == resource->rsrcChildResourcesHead )
3555 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3556 OICFree(resource->rsrcChildResourcesHead);
3557 resource->rsrcChildResourcesHead = temp;
3562 OCChildResource *temp = tempChildResource->next;
3563 OICFree(tempChildResource);
3564 tempLastChildResource->next = temp;
3568 OIC_LOG(INFO, TAG, "resource unbound");
3570 // Send notification when resource is unbounded successfully.
3571 #ifdef WITH_PRESENCE
3572 if (presenceResource.handle)
3574 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3575 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3576 OC_PRESENCE_TRIGGER_CHANGE);
3579 tempChildResource = NULL;
3580 tempLastChildResource = NULL;
3586 tempLastChildResource = tempChildResource;
3587 tempChildResource = tempChildResource->next;
3590 OIC_LOG(INFO, TAG, "resource not found in collection");
3592 tempChildResource = NULL;
3593 tempLastChildResource = NULL;
3595 // Unable to add resourceHandle, so return error
3596 return OC_STACK_ERROR;
3599 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3601 if (!resourceItemName)
3605 // Per RFC 6690 only registered values must follow the first rule below.
3606 // At this point in time the only values registered begin with "core", and
3607 // all other values are specified as opaque strings where multiple values
3608 // are separated by a space.
3609 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3611 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3613 if (resourceItemName[index] != '.'
3614 && resourceItemName[index] != '-'
3615 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3616 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3624 for (size_t index = 0; resourceItemName[index]; ++index)
3626 if (resourceItemName[index] == ' '
3627 || resourceItemName[index] == '\t'
3628 || resourceItemName[index] == '\r'
3629 || resourceItemName[index] == '\n')
3639 OCStackResult BindResourceTypeToResource(OCResource* resource,
3640 const char *resourceTypeName)
3642 OCResourceType *pointer = NULL;
3644 OCStackResult result = OC_STACK_ERROR;
3646 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3648 if (!ValidateResourceTypeInterface(resourceTypeName))
3650 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3651 return OC_STACK_INVALID_PARAM;
3654 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3657 result = OC_STACK_NO_MEMORY;
3661 str = OICStrdup(resourceTypeName);
3664 result = OC_STACK_NO_MEMORY;
3667 pointer->resourcetypename = str;
3668 pointer->next = NULL;
3670 insertResourceType(resource, pointer);
3671 result = OC_STACK_OK;
3674 if (result != OC_STACK_OK)
3683 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3684 const char *resourceInterfaceName)
3686 OCResourceInterface *pointer = NULL;
3688 OCStackResult result = OC_STACK_ERROR;
3690 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3692 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3694 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3695 return OC_STACK_INVALID_PARAM;
3698 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3700 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3703 result = OC_STACK_NO_MEMORY;
3707 str = OICStrdup(resourceInterfaceName);
3710 result = OC_STACK_NO_MEMORY;
3713 pointer->name = str;
3715 // Bind the resourceinterface to the resource
3716 insertResourceInterface(resource, pointer);
3718 result = OC_STACK_OK;
3721 if (result != OC_STACK_OK)
3730 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3731 const char *resourceTypeName)
3734 OCStackResult result = OC_STACK_ERROR;
3735 OCResource *resource = NULL;
3737 resource = findResource((OCResource *) handle);
3740 OIC_LOG(ERROR, TAG, "Resource not found");
3741 return OC_STACK_ERROR;
3744 result = BindResourceTypeToResource(resource, resourceTypeName);
3746 #ifdef WITH_PRESENCE
3747 if(presenceResource.handle)
3749 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3750 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3757 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3758 const char *resourceInterfaceName)
3761 OCStackResult result = OC_STACK_ERROR;
3762 OCResource *resource = NULL;
3764 resource = findResource((OCResource *) handle);
3767 OIC_LOG(ERROR, TAG, "Resource not found");
3768 return OC_STACK_ERROR;
3771 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3773 #ifdef WITH_PRESENCE
3774 if (presenceResource.handle)
3776 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3777 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3784 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3786 OCResource *pointer = headResource;
3788 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3792 *numResources = *numResources + 1;
3793 pointer = pointer->next;
3798 OCResourceHandle OCGetResourceHandle(uint8_t index)
3800 OCResource *pointer = headResource;
3802 for( uint8_t i = 0; i < index && pointer; ++i)
3804 pointer = pointer->next;
3806 return (OCResourceHandle) pointer;
3809 OCStackResult OCDeleteResource(OCResourceHandle handle)
3813 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3814 return OC_STACK_INVALID_PARAM;
3817 OCResource *resource = findResource((OCResource *) handle);
3818 if (resource == NULL)
3820 OIC_LOG(ERROR, TAG, "Resource not found");
3821 return OC_STACK_NO_RESOURCE;
3824 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3826 OIC_LOG(ERROR, TAG, "Error deleting resource");
3827 return OC_STACK_ERROR;
3833 const char *OCGetResourceUri(OCResourceHandle handle)
3835 OCResource *resource = NULL;
3837 resource = findResource((OCResource *) handle);
3840 return resource->uri;
3842 return (const char *) NULL;
3845 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3847 OCResource *resource = NULL;
3849 resource = findResource((OCResource *) handle);
3852 return resource->resourceProperties;
3854 return (OCResourceProperty)-1;
3857 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3858 uint8_t *numResourceTypes)
3860 OCResource *resource = NULL;
3861 OCResourceType *pointer = NULL;
3863 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3864 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3866 *numResourceTypes = 0;
3868 resource = findResource((OCResource *) handle);
3871 pointer = resource->rsrcType;
3874 *numResourceTypes = *numResourceTypes + 1;
3875 pointer = pointer->next;
3881 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3883 OCResourceType *resourceType = NULL;
3885 resourceType = findResourceTypeAtIndex(handle, index);
3888 return resourceType->resourcetypename;
3890 return (const char *) NULL;
3893 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3894 uint8_t *numResourceInterfaces)
3896 OCResourceInterface *pointer = NULL;
3897 OCResource *resource = NULL;
3899 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3900 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3902 *numResourceInterfaces = 0;
3903 resource = findResource((OCResource *) handle);
3906 pointer = resource->rsrcInterface;
3909 *numResourceInterfaces = *numResourceInterfaces + 1;
3910 pointer = pointer->next;
3916 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3918 OCResourceInterface *resourceInterface = NULL;
3920 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3921 if (resourceInterface)
3923 return resourceInterface->name;
3925 return (const char *) NULL;
3928 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3931 OCResource *resource = NULL;
3932 OCChildResource *tempChildResource = NULL;
3935 resource = findResource((OCResource *) collectionHandle);
3941 tempChildResource = resource->rsrcChildResourcesHead;
3943 while(tempChildResource)
3947 return tempChildResource->rsrcResource;
3950 tempChildResource = tempChildResource->next;
3953 // In this case, the number of resource handles in the collection exceeds the index
3954 tempChildResource = NULL;
3958 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3959 OCEntityHandler entityHandler,
3960 void* callbackParam)
3962 OCResource *resource = NULL;
3964 // Validate parameters
3965 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3967 // Use the handle to find the resource in the resource linked list
3968 resource = findResource((OCResource *)handle);
3971 OIC_LOG(ERROR, TAG, "Resource not found");
3972 return OC_STACK_ERROR;
3976 resource->entityHandler = entityHandler;
3977 resource->entityHandlerCallbackParam = callbackParam;
3979 #ifdef WITH_PRESENCE
3980 if (presenceResource.handle)
3982 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3983 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3990 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3992 OCResource *resource = NULL;
3994 resource = findResource((OCResource *)handle);
3997 OIC_LOG(ERROR, TAG, "Resource not found");
4002 return resource->entityHandler;
4005 void incrementSequenceNumber(OCResource * resPtr)
4007 // Increment the sequence number
4008 resPtr->sequenceNum += 1;
4009 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4011 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4016 #ifdef WITH_PRESENCE
4017 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4018 OCPresenceTrigger trigger)
4020 OCResource *resPtr = NULL;
4021 OCStackResult result = OC_STACK_ERROR;
4022 OCMethod method = OC_REST_PRESENCE;
4023 uint32_t maxAge = 0;
4024 resPtr = findResource((OCResource *) presenceResource.handle);
4027 return OC_STACK_NO_RESOURCE;
4030 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4032 maxAge = presenceResource.presenceTTL;
4034 result = SendAllObserverNotification(method, resPtr, maxAge,
4035 trigger, resourceType, OC_LOW_QOS);
4041 OCStackResult SendStopNotification()
4043 OCResource *resPtr = NULL;
4044 OCStackResult result = OC_STACK_ERROR;
4045 OCMethod method = OC_REST_PRESENCE;
4046 resPtr = findResource((OCResource *) presenceResource.handle);
4049 return OC_STACK_NO_RESOURCE;
4052 // maxAge is 0. ResourceType is NULL.
4053 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4059 #endif // WITH_PRESENCE
4060 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4062 OCResource *resPtr = NULL;
4063 OCStackResult result = OC_STACK_ERROR;
4064 OCMethod method = OC_REST_NOMETHOD;
4065 uint32_t maxAge = 0;
4067 OIC_LOG(INFO, TAG, "Notifying all observers");
4068 #ifdef WITH_PRESENCE
4069 if(handle == presenceResource.handle)
4073 #endif // WITH_PRESENCE
4074 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4076 // Verify that the resource exists
4077 resPtr = findResource ((OCResource *) handle);
4080 return OC_STACK_NO_RESOURCE;
4084 //only increment in the case of regular observing (not presence)
4085 incrementSequenceNumber(resPtr);
4086 method = OC_REST_OBSERVE;
4087 maxAge = MAX_OBSERVE_AGE;
4088 #ifdef WITH_PRESENCE
4089 result = SendAllObserverNotification (method, resPtr, maxAge,
4090 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4092 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4099 OCNotifyListOfObservers (OCResourceHandle handle,
4100 OCObservationId *obsIdList,
4101 uint8_t numberOfIds,
4102 const OCRepPayload *payload,
4103 OCQualityOfService qos)
4105 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4107 OCResource *resPtr = NULL;
4108 //TODO: we should allow the server to define this
4109 uint32_t maxAge = MAX_OBSERVE_AGE;
4111 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4112 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4113 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4115 resPtr = findResource ((OCResource *) handle);
4116 if (NULL == resPtr || myStackMode == OC_CLIENT)
4118 return OC_STACK_NO_RESOURCE;
4122 incrementSequenceNumber(resPtr);
4124 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4125 payload, maxAge, qos));
4128 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4130 OCStackResult result = OC_STACK_ERROR;
4131 OCServerRequest *serverRequest = NULL;
4133 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4135 // Validate input parameters
4136 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4137 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4140 // Get pointer to request info
4141 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4144 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4145 result = serverRequest->ehResponseHandler(ehResponse);
4151 //#ifdef DIRECT_PAIRING
4152 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4154 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4155 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4157 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4161 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4164 const OCDPDev_t* OCGetDirectPairedDevices()
4166 return (const OCDPDev_t*)DPGetPairedDevices();
4169 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4170 OCDirectPairingCB resultCallback)
4172 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4173 if(NULL == peer || NULL == pinNumber)
4175 OIC_LOG(ERROR, TAG, "Invalid parameters");
4176 return OC_STACK_INVALID_PARAM;
4178 if (NULL == resultCallback)
4180 OIC_LOG(ERROR, TAG, "Invalid callback");
4181 return OC_STACK_INVALID_CALLBACK;
4184 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4185 pinNumber, (OCDirectPairingResultCB)resultCallback);
4187 //#endif // DIRECT_PAIRING
4189 //-----------------------------------------------------------------------------
4190 // Private internal function definitions
4191 //-----------------------------------------------------------------------------
4192 static OCDoHandle GenerateInvocationHandle()
4194 OCDoHandle handle = NULL;
4195 // Generate token here, it will be deleted when the transaction is deleted
4196 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4199 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4205 #ifdef WITH_PRESENCE
4206 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4207 OCResourceProperty resourceProperties, uint8_t enable)
4211 return OC_STACK_INVALID_PARAM;
4213 if (resourceProperties
4214 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4216 OIC_LOG(ERROR, TAG, "Invalid property");
4217 return OC_STACK_INVALID_PARAM;
4221 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4225 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4231 OCStackResult initResources()
4233 OCStackResult result = OC_STACK_OK;
4235 headResource = NULL;
4236 tailResource = NULL;
4237 // Init Virtual Resources
4238 #ifdef WITH_PRESENCE
4239 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4241 result = OCCreateResource(&presenceResource.handle,
4242 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4244 OC_RSRVD_PRESENCE_URI,
4248 //make resource inactive
4249 result = OCChangeResourceProperty(
4250 &(((OCResource *) presenceResource.handle)->resourceProperties),
4253 #ifndef WITH_ARDUINO
4254 if (result == OC_STACK_OK)
4256 result = SRMInitSecureResources();
4260 if(result == OC_STACK_OK)
4262 CreateResetProfile();
4263 result = OCCreateResource(&deviceResource,
4264 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4265 OC_RSRVD_INTERFACE_DEFAULT,
4266 OC_RSRVD_DEVICE_URI,
4270 if(result == OC_STACK_OK)
4272 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4273 OC_RSRVD_INTERFACE_READ);
4277 if(result == OC_STACK_OK)
4279 result = OCCreateResource(&platformResource,
4280 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4281 OC_RSRVD_INTERFACE_DEFAULT,
4282 OC_RSRVD_PLATFORM_URI,
4286 if(result == OC_STACK_OK)
4288 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4289 OC_RSRVD_INTERFACE_READ);
4296 void insertResource(OCResource *resource)
4300 headResource = resource;
4301 tailResource = resource;
4305 tailResource->next = resource;
4306 tailResource = resource;
4308 resource->next = NULL;
4311 OCResource *findResource(OCResource *resource)
4313 OCResource *pointer = headResource;
4317 if (pointer == resource)
4321 pointer = pointer->next;
4326 void deleteAllResources()
4328 OCResource *pointer = headResource;
4329 OCResource *temp = NULL;
4333 temp = pointer->next;
4334 #ifdef WITH_PRESENCE
4335 if (pointer != (OCResource *) presenceResource.handle)
4337 #endif // WITH_PRESENCE
4338 deleteResource(pointer);
4339 #ifdef WITH_PRESENCE
4341 #endif // WITH_PRESENCE
4344 memset(&platformResource, 0, sizeof(platformResource));
4345 memset(&deviceResource, 0, sizeof(deviceResource));
4347 memset(&brokerResource, 0, sizeof(brokerResource));
4350 SRMDeInitSecureResources();
4352 #ifdef WITH_PRESENCE
4353 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4354 // presence notification attributed to their deletion to be processed.
4355 deleteResource((OCResource *) presenceResource.handle);
4356 memset(&presenceResource, 0, sizeof(presenceResource));
4357 #endif // WITH_PRESENCE
4360 OCStackResult deleteResource(OCResource *resource)
4362 OCResource *prev = NULL;
4363 OCResource *temp = NULL;
4366 OIC_LOG(DEBUG,TAG,"resource is NULL");
4367 return OC_STACK_INVALID_PARAM;
4370 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4372 temp = headResource;
4375 if (temp == resource)
4377 // Invalidate all Resource Properties.
4378 resource->resourceProperties = (OCResourceProperty) 0;
4379 #ifdef WITH_PRESENCE
4380 if(resource != (OCResource *) presenceResource.handle)
4382 #endif // WITH_PRESENCE
4383 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4384 #ifdef WITH_PRESENCE
4387 if(presenceResource.handle)
4389 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4390 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4393 // Only resource in list.
4394 if (temp == headResource && temp == tailResource)
4396 headResource = NULL;
4397 tailResource = NULL;
4400 else if (temp == headResource)
4402 headResource = temp->next;
4405 else if (temp == tailResource)
4407 tailResource = prev;
4408 tailResource->next = NULL;
4412 prev->next = temp->next;
4415 deleteResourceElements(temp);
4426 return OC_STACK_ERROR;
4429 void deleteResourceElements(OCResource *resource)
4436 OICFree(resource->uri);
4437 deleteResourceType(resource->rsrcType);
4438 deleteResourceInterface(resource->rsrcInterface);
4441 void deleteResourceType(OCResourceType *resourceType)
4443 OCResourceType *pointer = resourceType;
4444 OCResourceType *next = NULL;
4448 next = pointer->next;
4449 OICFree(pointer->resourcetypename);
4455 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4457 OCResourceInterface *pointer = resourceInterface;
4458 OCResourceInterface *next = NULL;
4462 next = pointer->next;
4463 OICFree(pointer->name);
4469 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4471 OCResourceType *pointer = NULL;
4472 OCResourceType *previous = NULL;
4473 if (!resource || !resourceType)
4477 // resource type list is empty.
4478 else if (!resource->rsrcType)
4480 resource->rsrcType = resourceType;
4484 pointer = resource->rsrcType;
4488 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4490 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4491 OICFree(resourceType->resourcetypename);
4492 OICFree(resourceType);
4496 pointer = pointer->next;
4501 previous->next = resourceType;
4504 resourceType->next = NULL;
4506 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4509 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4511 OCResource *resource = NULL;
4512 OCResourceType *pointer = NULL;
4514 // Find the specified resource
4515 resource = findResource((OCResource *) handle);
4521 // Make sure a resource has a resourcetype
4522 if (!resource->rsrcType)
4527 // Iterate through the list
4528 pointer = resource->rsrcType;
4529 for(uint8_t i = 0; i< index && pointer; ++i)
4531 pointer = pointer->next;
4536 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4538 if(resourceTypeList && resourceTypeName)
4540 OCResourceType * rtPointer = resourceTypeList;
4541 while(resourceTypeName && rtPointer)
4543 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4544 if(rtPointer->resourcetypename &&
4545 strcmp(resourceTypeName, (const char *)
4546 (rtPointer->resourcetypename)) == 0)
4550 rtPointer = rtPointer->next;
4558 * Insert a new interface into interface linked list only if not already present.
4559 * If alredy present, 2nd arg is free'd.
4560 * Default interface will always be first if present.
4562 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4564 OCResourceInterface *pointer = NULL;
4565 OCResourceInterface *previous = NULL;
4567 newInterface->next = NULL;
4569 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4571 if (!*firstInterface)
4573 // If first interface is not oic.if.baseline, by default add it as first interface type.
4574 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4576 *firstInterface = newInterface;
4580 OCStackResult result = BindResourceInterfaceToResource(resource,
4581 OC_RSRVD_INTERFACE_DEFAULT);
4582 if (result != OC_STACK_OK)
4584 OICFree(newInterface->name);
4585 OICFree(newInterface);
4588 if (*firstInterface)
4590 (*firstInterface)->next = newInterface;
4594 // If once add oic.if.baseline, later too below code take care of freeing memory.
4595 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4597 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4599 OICFree(newInterface->name);
4600 OICFree(newInterface);
4603 // This code will not hit anymore, keeping
4606 newInterface->next = *firstInterface;
4607 *firstInterface = newInterface;
4612 pointer = *firstInterface;
4615 if (strcmp(newInterface->name, pointer->name) == 0)
4617 OICFree(newInterface->name);
4618 OICFree(newInterface);
4622 pointer = pointer->next;
4627 previous->next = newInterface;
4632 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4635 OCResource *resource = NULL;
4636 OCResourceInterface *pointer = NULL;
4638 // Find the specified resource
4639 resource = findResource((OCResource *) handle);
4645 // Make sure a resource has a resourceinterface
4646 if (!resource->rsrcInterface)
4651 // Iterate through the list
4652 pointer = resource->rsrcInterface;
4654 for (uint8_t i = 0; i < index && pointer; ++i)
4656 pointer = pointer->next;
4662 * This function splits the uri using the '?' delimiter.
4663 * "uriWithoutQuery" is the block of characters between the beginning
4664 * till the delimiter or '\0' which ever comes first.
4665 * "query" is whatever is to the right of the delimiter if present.
4666 * No delimiter sets the query to NULL.
4667 * If either are present, they will be malloc'ed into the params 2, 3.
4668 * The first param, *uri is left untouched.
4670 * NOTE: This function does not account for whitespace at the end of the uri NOR
4671 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4672 * part of the query.
4674 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4678 return OC_STACK_INVALID_URI;
4680 if(!query || !uriWithoutQuery)
4682 return OC_STACK_INVALID_PARAM;
4686 *uriWithoutQuery = NULL;
4688 size_t uriWithoutQueryLen = 0;
4689 size_t queryLen = 0;
4690 size_t uriLen = strlen(uri);
4692 char *pointerToDelimiter = strstr(uri, "?");
4694 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4695 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4697 if (uriWithoutQueryLen)
4699 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4700 if (!*uriWithoutQuery)
4704 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4708 *query = (char *) OICCalloc(queryLen + 1, 1);
4711 OICFree(*uriWithoutQuery);
4712 *uriWithoutQuery = NULL;
4715 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4721 return OC_STACK_NO_MEMORY;
4724 static const OicUuid_t* OCGetServerInstanceID(void)
4726 static bool generated = false;
4727 static OicUuid_t sid;
4733 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4735 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4742 const char* OCGetServerInstanceIDString(void)
4744 static bool generated = false;
4745 static char sidStr[UUID_STRING_SIZE];
4752 const OicUuid_t *sid = OCGetServerInstanceID();
4753 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4755 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4763 CAResult_t OCSelectNetwork()
4765 CAResult_t retResult = CA_STATUS_FAILED;
4766 CAResult_t caResult = CA_STATUS_OK;
4768 CATransportAdapter_t connTypes[] = {
4770 CA_ADAPTER_RFCOMM_BTEDR,
4771 CA_ADAPTER_GATT_BTLE,
4774 ,CA_ADAPTER_REMOTE_ACCESS
4781 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4783 for(int i = 0; i < numConnTypes; i++)
4785 // If CA status is not initialized, CASelectNetwork() will not be called.
4786 if (caResult != CA_STATUS_NOT_INITIALIZED)
4788 caResult = CASelectNetwork(connTypes[i]);
4789 if (caResult == CA_STATUS_OK)
4791 retResult = CA_STATUS_OK;
4796 if (retResult != CA_STATUS_OK)
4798 return caResult; // Returns error of appropriate transport that failed fatally.
4804 OCStackResult CAResultToOCResult(CAResult_t caResult)
4810 case CA_STATUS_INVALID_PARAM:
4811 return OC_STACK_INVALID_PARAM;
4812 case CA_ADAPTER_NOT_ENABLED:
4813 return OC_STACK_ADAPTER_NOT_ENABLED;
4814 case CA_SERVER_STARTED_ALREADY:
4816 case CA_SERVER_NOT_STARTED:
4817 return OC_STACK_ERROR;
4818 case CA_DESTINATION_NOT_REACHABLE:
4819 return OC_STACK_COMM_ERROR;
4820 case CA_SOCKET_OPERATION_FAILED:
4821 return OC_STACK_COMM_ERROR;
4822 case CA_SEND_FAILED:
4823 return OC_STACK_COMM_ERROR;
4824 case CA_RECEIVE_FAILED:
4825 return OC_STACK_COMM_ERROR;
4826 case CA_MEMORY_ALLOC_FAILED:
4827 return OC_STACK_NO_MEMORY;
4828 case CA_REQUEST_TIMEOUT:
4829 return OC_STACK_TIMEOUT;
4830 case CA_DESTINATION_DISCONNECTED:
4831 return OC_STACK_COMM_ERROR;
4832 case CA_STATUS_FAILED:
4833 return OC_STACK_ERROR;
4834 case CA_NOT_SUPPORTED:
4835 return OC_STACK_NOTIMPL;
4837 return OC_STACK_ERROR;
4841 bool OCResultToSuccess(OCStackResult ocResult)
4846 case OC_STACK_RESOURCE_CREATED:
4847 case OC_STACK_RESOURCE_DELETED:
4848 case OC_STACK_CONTINUE:
4849 case OC_STACK_RESOURCE_CHANGED:
4850 case OC_STACK_SLOW_RESOURCE:
4858 OCStackResult OCSetProxyURI(const char *uri)
4860 return CAResultToOCResult(CASetProxyUri(uri));
4864 #if defined(RD_CLIENT) || defined(RD_SERVER)
4865 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
4867 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4869 OCResource *resource = NULL;
4871 resource = findResource((OCResource *) handle);
4874 OIC_LOG(ERROR, TAG, "Resource not found");
4875 return OC_STACK_ERROR;
4878 resource->ins = ins;
4883 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
4887 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
4891 OCResource *pointer = headResource;
4895 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
4897 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
4900 pointer = pointer->next;
4905 OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
4907 OCResource *resource = NULL;
4909 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4910 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
4912 resource = findResource((OCResource *) handle);
4915 *ins = resource->ins;
4918 return OC_STACK_ERROR;
4921 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
4922 void* optionData, size_t optionDataLength)
4926 OIC_LOG (INFO, TAG, "Header options are NULL");
4927 return OC_STACK_INVALID_PARAM;
4932 OIC_LOG (INFO, TAG, "optionData are NULL");
4933 return OC_STACK_INVALID_PARAM;
4938 OIC_LOG (INFO, TAG, "numOptions is NULL");
4939 return OC_STACK_INVALID_PARAM;
4942 if (*numOptions >= MAX_HEADER_OPTIONS)
4944 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
4945 return OC_STACK_NO_MEMORY;
4948 ocHdrOpt += *numOptions;
4949 ocHdrOpt->protocolID = OC_COAP_ID;
4950 ocHdrOpt->optionID = optionID;
4951 ocHdrOpt->optionLength =
4952 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
4953 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
4954 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
4959 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
4960 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
4962 if (!ocHdrOpt || !numOptions)
4964 OIC_LOG (INFO, TAG, "No options present");
4970 OIC_LOG (INFO, TAG, "optionData are NULL");
4971 return OC_STACK_INVALID_PARAM;
4974 if (!receivedDataLength)
4976 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
4977 return OC_STACK_INVALID_PARAM;
4980 for (uint8_t i = 0; i < numOptions; i++)
4982 if (ocHdrOpt[i].optionID == optionID)
4984 if (optionDataLength >= ocHdrOpt->optionLength)
4986 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
4987 *receivedDataLength = ocHdrOpt->optionLength;
4992 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
4993 return OC_STACK_ERROR;
5001 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5003 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5004 if (g_adapterHandler)
5006 g_adapterHandler(adapter, enabled);
5010 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5012 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5013 if (g_connectionHandler)
5015 g_connectionHandler(info, isConnected);
5019 void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
5020 CAConnectionStateChangedCB connectionHandler)
5022 OIC_LOG(DEBUG, TAG, "OCSetNetworkMonitorHandler");
5023 g_adapterHandler = adapterHandler;
5024 g_connectionHandler = connectionHandler;
5027 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5032 ret = GetDoxmDeviceID(&oicUuid);
5033 if (OC_STACK_OK == ret)
5035 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5039 OIC_LOG(ERROR, TAG, "Device ID Get error");
5044 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5048 OIC_LOG(ERROR, TAG, "Set deviceId DOXM");
5050 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5051 for(int i=0;i < UUID_LENGTH; i++)
5053 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5055 ret = SetDoxmDeviceID(&oicUuid);