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 * Convert CAResponseResult_t to OCStackResult.
302 * @param caCode CAResponseResult_t code.
303 * @return ::OC_STACK_OK on success, some other value upon failure.
305 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
308 * Convert OCTransportFlags_t to CATransportModifiers_t.
310 * @param ocConType OCTransportFlags_t input.
311 * @return CATransportFlags
313 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
316 * Convert CATransportFlags_t to OCTransportModifiers_t.
318 * @param caConType CATransportFlags_t input.
319 * @return OCTransportFlags
321 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
324 * Handle response from presence request.
326 * @param endPoint CA remote endpoint.
327 * @param responseInfo CA response info.
328 * @return ::OC_STACK_OK on success, some other value upon failure.
330 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
331 const CAResponseInfo_t *responseInfo);
334 * This function will be called back by CA layer when a response is received.
336 * @param endPoint CA remote endpoint.
337 * @param responseInfo CA response info.
339 static void HandleCAResponses(const CAEndpoint_t* endPoint,
340 const CAResponseInfo_t* responseInfo);
343 * This function will be called back by CA layer when a request is received.
345 * @param endPoint CA remote endpoint.
346 * @param requestInfo CA request info.
348 static void HandleCARequests(const CAEndpoint_t* endPoint,
349 const CARequestInfo_t* requestInfo);
352 * Extract query from a URI.
354 * @param uri Full URI with query.
355 * @param query Pointer to string that will contain query.
356 * @param newURI Pointer to string that will contain URI.
357 * @return ::OC_STACK_OK on success, some other value upon failure.
359 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
362 * Finds a resource type in an OCResourceType link-list.
364 * @param resourceTypeList The link-list to be searched through.
365 * @param resourceTypeName The key to search for.
367 * @return Resource type that matches the key (ie. resourceTypeName) or
368 * NULL if there is either an invalid parameter or this function was unable to find the key.
370 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
371 const char * resourceTypeName);
374 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
375 * TTL will be set to maxAge.
377 * @param cbNode Callback Node for which presence ttl is to be reset.
378 * @param maxAge New value of ttl in seconds.
380 * @return ::OC_STACK_OK on success, some other value upon failure.
382 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
385 * Ensure the accept header option is set appropriatly before sending the requests and routing
386 * header option is updated with destination.
388 * @param object CA remote endpoint.
389 * @param requestInfo CA request info.
391 * @return ::OC_STACK_OK on success, some other value upon failure.
393 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
396 * default adapter state change callback method
398 * @param adapter CA network adapter type.
399 * @param enabled current adapter state.
401 static void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled);
404 * default connection state change callback method
406 * @param info CAEndpoint which has address, port and etc.
407 * @param isConnected current connection state.
409 static void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected);
412 * Register network monitoring callback.
413 * Network status changes are delivered these callback.
414 * @param adapterHandler Adapter state monitoring callback.
415 * @param connectionHandler Connection state monitoring callback.
417 static void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
418 CAConnectionStateChangedCB connectionHandler);
420 //-----------------------------------------------------------------------------
421 // Internal functions
422 //-----------------------------------------------------------------------------
424 bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
426 if (!options || 0 == numOptions)
428 OIC_LOG (INFO, TAG, "No options present");
432 for (uint8_t i = 0; i < numOptions; i++)
434 if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
436 OIC_LOG(DEBUG, TAG, "Proxy URI is present");
443 uint32_t GetTicks(uint32_t milliSeconds)
448 // Guard against overflow of uint32_t
449 if (milliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
450 COAP_TICKS_PER_SECOND)
452 return now + (milliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
460 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
462 VERIFY_NON_NULL_NR(in, FATAL);
463 VERIFY_NON_NULL_NR(out, FATAL);
465 out->adapter = (OCTransportAdapter)in->adapter;
466 out->flags = CAToOCTransportFlags(in->flags);
467 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
468 out->port = in->port;
469 out->ifindex = in->ifindex;
470 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
471 /* This assert is to prevent accidental mismatch between address size macros defined in
472 * RI and CA and cause crash here. */
473 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
474 "Address size mismatch between RI and CA");
475 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
479 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
481 VERIFY_NON_NULL_NR(in, FATAL);
482 VERIFY_NON_NULL_NR(out, FATAL);
484 out->adapter = (CATransportAdapter_t)in->adapter;
485 out->flags = OCToCATransportFlags(in->flags);
486 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
487 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
488 /* This assert is to prevent accidental mismatch between address size macros defined in
489 * RI and CA and cause crash here. */
490 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
491 "Address size mismatch between RI and CA");
492 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
494 out->port = in->port;
495 out->ifindex = in->ifindex;
498 void FixUpClientResponse(OCClientResponse *cr)
500 VERIFY_NON_NULL_NR(cr, FATAL);
502 cr->addr = &cr->devAddr;
503 cr->connType = (OCConnectivityType)
504 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
507 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
509 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
510 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
512 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
513 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
514 if (OC_STACK_OK != rmResult)
516 OIC_LOG(ERROR, TAG, "Add destination option failed");
521 // OC stack prefer CBOR encoded payloads.
522 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
523 CAResult_t result = CASendRequest(object, requestInfo);
524 if(CA_STATUS_OK != result)
526 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
527 return CAResultToOCResult(result);
531 //-----------------------------------------------------------------------------
532 // Internal API function
533 //-----------------------------------------------------------------------------
535 // This internal function is called to update the stack with the status of
536 // observers and communication failures
537 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
539 OCStackResult result = OC_STACK_ERROR;
540 ResourceObserver * observer = NULL;
541 OCEntityHandlerRequest ehRequest = {0};
545 case OC_OBSERVER_NOT_INTERESTED:
546 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
547 observer = GetObserverUsingToken(token, tokenLength);
550 result = FormOCEntityHandlerRequest(&ehRequest,
554 (OCResourceHandle)NULL,
555 NULL, PAYLOAD_TYPE_REPRESENTATION,
557 OC_OBSERVE_DEREGISTER,
560 if (result != OC_STACK_OK)
565 if (observer->resource && observer->resource->entityHandler)
567 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
568 observer->resource->entityHandlerCallbackParam);
572 result = DeleteObserverUsingToken(token, tokenLength);
573 if (result == OC_STACK_OK)
575 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
579 result = OC_STACK_OK;
580 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
584 case OC_OBSERVER_STILL_INTERESTED:
585 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
586 observer = GetObserverUsingToken(token, tokenLength);
589 observer->forceHighQos = 0;
590 observer->failedCommCount = 0;
591 result = OC_STACK_OK;
595 result = OC_STACK_OBSERVER_NOT_FOUND;
599 case OC_OBSERVER_FAILED_COMM:
600 OIC_LOG(DEBUG, TAG, "observer is unreachable");
601 observer = GetObserverUsingToken (token, tokenLength);
604 if (observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
606 result = FormOCEntityHandlerRequest(&ehRequest,
610 (OCResourceHandle)NULL,
611 NULL, PAYLOAD_TYPE_REPRESENTATION,
613 OC_OBSERVE_DEREGISTER,
616 if (result != OC_STACK_OK)
618 return OC_STACK_ERROR;
621 if (observer->resource && observer->resource->entityHandler)
623 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
624 observer->resource->entityHandlerCallbackParam);
627 result = DeleteObserverUsingToken(token, tokenLength);
628 if (result == OC_STACK_OK)
630 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
634 result = OC_STACK_OK;
635 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
640 observer->failedCommCount++;
641 observer->forceHighQos = 1;
642 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",
643 observer->failedCommCount);
644 result = OC_STACK_CONTINUE;
649 OIC_LOG(ERROR, TAG, "Unknown status");
650 result = OC_STACK_ERROR;
656 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
658 OCStackResult ret = OC_STACK_ERROR;
662 ret = OC_STACK_RESOURCE_CREATED;
665 ret = OC_STACK_RESOURCE_DELETED;
668 ret = OC_STACK_RESOURCE_CHANGED;
675 ret = OC_STACK_INVALID_QUERY;
677 case CA_UNAUTHORIZED_REQ:
678 ret = OC_STACK_UNAUTHORIZED_REQ;
681 ret = OC_STACK_INVALID_OPTION;
684 ret = OC_STACK_NO_RESOURCE;
686 case CA_RETRANSMIT_TIMEOUT:
687 ret = OC_STACK_COMM_ERROR;
689 case CA_REQUEST_ENTITY_TOO_LARGE:
690 ret = OC_STACK_TOO_LARGE_REQ;
692 case CA_FORBIDDEN_REQ:
693 ret = OC_STACK_FORBIDDEN_REQ;
695 case CA_INTERNAL_SERVER_ERROR:
696 ret = OC_STACK_INTERNAL_SERVER_ERROR;
704 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
706 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
715 // This Response Code is like HTTP 204 "No Content" but only used in
716 // response to POST and PUT requests.
720 // This Response Code is like HTTP 200 "OK" but only used in response to
725 // This should not happen but,
726 // give it a value just in case but output an error
728 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
732 case OC_STACK_RESOURCE_CREATED:
735 case OC_STACK_RESOURCE_DELETED:
738 case OC_STACK_RESOURCE_CHANGED:
741 case OC_STACK_INVALID_QUERY:
744 case OC_STACK_INVALID_OPTION:
747 case OC_STACK_NO_RESOURCE:
750 case OC_STACK_COMM_ERROR:
751 ret = CA_RETRANSMIT_TIMEOUT;
753 case OC_STACK_UNAUTHORIZED_REQ:
754 ret = CA_UNAUTHORIZED_REQ;
756 case OC_STACK_FORBIDDEN_REQ:
757 ret = CA_FORBIDDEN_REQ;
759 case OC_STACK_INTERNAL_SERVER_ERROR:
760 ret = CA_INTERNAL_SERVER_ERROR;
768 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
770 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
772 // supply default behavior.
773 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
775 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
777 if ((caFlags & OC_MASK_SCOPE) == 0)
779 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
784 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
786 return (OCTransportFlags)caFlags;
789 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
791 uint32_t lowerBound = 0;
792 uint32_t higherBound = 0;
794 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
796 return OC_STACK_INVALID_PARAM;
799 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
801 cbNode->presence->TTL = maxAgeSeconds;
803 for (int index = 0; index < PresenceTimeOutSize; index++)
805 // Guard against overflow
806 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
809 lowerBound = GetTicks((PresenceTimeOut[index] *
810 cbNode->presence->TTL *
811 MILLISECONDS_PER_SECOND)/100);
815 lowerBound = GetTicks(UINT32_MAX);
818 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
821 higherBound = GetTicks((PresenceTimeOut[index + 1] *
822 cbNode->presence->TTL *
823 MILLISECONDS_PER_SECOND)/100);
827 higherBound = GetTicks(UINT32_MAX);
830 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
832 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
833 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
834 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
837 cbNode->presence->TTLlevel = 0;
839 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
843 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
845 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
847 return OC_RSRVD_TRIGGER_CREATE;
849 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
851 return OC_RSRVD_TRIGGER_CHANGE;
855 return OC_RSRVD_TRIGGER_DELETE;
859 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
863 return OC_PRESENCE_TRIGGER_CREATE;
865 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
867 return OC_PRESENCE_TRIGGER_CREATE;
869 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
871 return OC_PRESENCE_TRIGGER_CHANGE;
875 return OC_PRESENCE_TRIGGER_DELETE;
879 OCStackResult OCEncodeAddressForRFC6874(char *outputAddress,
881 const char *inputAddress)
883 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
884 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
886 size_t inputLength = strnlen(inputAddress, outputSize);
888 // inputSize includes the null terminator
889 size_t inputSize = inputLength + 1;
891 if (inputSize > outputSize)
893 OIC_LOG_V(ERROR, TAG,
894 "OCEncodeAddressForRFC6874 failed: "
895 "outputSize (%zu) < inputSize (%zu)",
896 outputSize, inputSize);
898 return OC_STACK_ERROR;
901 char* percentChar = strchr(inputAddress, '%');
903 // If there is no '%' character, then no change is required to the string.
904 if (NULL == percentChar)
906 OICStrcpy(outputAddress, outputSize, inputAddress);
910 const char* addressPart = &inputAddress[0];
911 const char* scopeIdPart = percentChar + 1;
913 // Sanity check to make sure this string doesn't have more '%' characters
914 if (NULL != strchr(scopeIdPart, '%'))
916 return OC_STACK_ERROR;
919 // If no string follows the first '%', then the input was invalid.
920 if (scopeIdPart[0] == '\0')
922 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
923 return OC_STACK_ERROR;
926 // Check to see if the string is already encoded
927 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
929 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Input string is already encoded");
930 return OC_STACK_ERROR;
933 // Fail if we don't have room for encoded string's two additional chars
934 if (outputSize < (inputSize + 2))
936 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: encoded output will not fit!");
937 return OC_STACK_ERROR;
940 // Restore the null terminator with an escaped '%' character, per RFC 6874
941 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
942 strcat(outputAddress, "%25");
943 strcat(outputAddress, scopeIdPart);
948 OCStackResult OCDecodeAddressForRFC6874(char *outputAddress,
950 const char *inputAddress,
953 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
954 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
958 end = inputAddress + strlen(inputAddress);
960 size_t inputLength = end - inputAddress;
962 const char *percent = strchr(inputAddress, '%');
963 if (!percent || (percent > end))
965 OICStrcpyPartial(outputAddress, outputSize, inputAddress, inputLength);
969 if (percent[1] != '2' || percent[2] != '5')
971 return OC_STACK_INVALID_URI;
974 int addrlen = percent - inputAddress + 1;
975 OICStrcpyPartial(outputAddress, outputSize, inputAddress, addrlen);
976 OICStrcpyPartial(outputAddress + addrlen, outputSize - addrlen,
977 percent + 3, end - percent - 3);
984 * The cononical presence allows constructed URIs to be string compared.
986 * requestUri must be a char array of size CA_MAX_URI_LENGTH
988 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
989 char *presenceUri, bool isMulticast)
991 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
992 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
996 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
997 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1000 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1001 if (ep->adapter == CA_ADAPTER_IP)
1003 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1005 if ('\0' == ep->addr[0]) // multicast
1007 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1011 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1013 OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1014 sizeof(addressEncoded),
1017 if (OC_STACK_OK != result)
1022 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1023 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1028 if ('\0' == ep->addr[0]) // multicast
1030 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1031 ep->port = OC_MULTICAST_PORT;
1033 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1034 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1038 // might work for other adapters (untested, but better than nothing)
1039 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1040 OC_RSRVD_PRESENCE_URI);
1044 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1045 const CAResponseInfo_t *responseInfo)
1047 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1048 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1050 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1051 ClientCB * cbNode = NULL;
1052 char *resourceTypeName = NULL;
1053 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1054 OCStackResult result = OC_STACK_ERROR;
1055 uint32_t maxAge = 0;
1057 char presenceUri[CA_MAX_URI_LENGTH];
1059 int presenceSubscribe = 0;
1060 int multicastPresenceSubscribe = 0;
1062 if (responseInfo->result != CA_CONTENT)
1064 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1065 return OC_STACK_ERROR;
1068 response.payload = NULL;
1069 response.result = OC_STACK_OK;
1071 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1072 FixUpClientResponse(&response);
1074 if (responseInfo->info.payload)
1076 result = OCParsePayload(&response.payload,
1077 PAYLOAD_TYPE_PRESENCE,
1078 responseInfo->info.payload,
1079 responseInfo->info.payloadSize);
1081 if(result != OC_STACK_OK)
1083 OIC_LOG(ERROR, TAG, "Presence parse failed");
1086 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1088 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1089 result = OC_STACK_ERROR;
1092 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1093 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1094 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1097 // check for unicast presence
1098 uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1099 responseInfo->isMulticast);
1100 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1102 return OC_STACK_INVALID_URI;
1104 OIC_LOG(ERROR, TAG, "check for unicast presence");
1105 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1108 presenceSubscribe = 1;
1112 // check for multicast presence
1113 OIC_LOG(ERROR, TAG, "check for multicast presence");
1114 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1117 multicastPresenceSubscribe = 1;
1121 if (!presenceSubscribe && !multicastPresenceSubscribe)
1123 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1127 if (presenceSubscribe)
1129 if(cbNode->sequenceNumber == response.sequenceNumber)
1131 OIC_LOG(INFO, TAG, "No presence change");
1132 ResetPresenceTTL(cbNode, maxAge);
1133 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1139 OIC_LOG(INFO, TAG, "Stopping presence");
1140 response.result = OC_STACK_PRESENCE_STOPPED;
1141 if(cbNode->presence)
1143 OICFree(cbNode->presence->timeOut);
1144 OICFree(cbNode->presence);
1145 cbNode->presence = NULL;
1150 if(!cbNode->presence)
1152 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1154 if(!(cbNode->presence))
1156 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1157 result = OC_STACK_NO_MEMORY;
1161 VERIFY_NON_NULL_V(cbNode->presence);
1162 cbNode->presence->timeOut = NULL;
1163 cbNode->presence->timeOut = (uint32_t *)
1164 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1165 if(!(cbNode->presence->timeOut)){
1167 "Could not allocate memory for cbNode->presence->timeOut");
1168 OICFree(cbNode->presence);
1169 result = OC_STACK_NO_MEMORY;
1174 ResetPresenceTTL(cbNode, maxAge);
1176 cbNode->sequenceNumber = response.sequenceNumber;
1181 // This is the multicast case
1182 OIC_LOG(INFO, TAG, "this is the multicast presence");
1185 OIC_LOG(INFO, TAG, "Stopping presence");
1186 response.result = OC_STACK_PRESENCE_STOPPED;
1190 // Ensure that a filter is actually applied.
1191 if (resourceTypeName && cbNode->filterResourceType)
1193 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1194 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1200 OIC_LOG(INFO, TAG, "Callback for presence");
1202 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1204 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1206 FindAndDeleteClientCB(cbNode);
1210 OCPayloadDestroy(response.payload);
1214 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1216 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1218 if(responseInfo->info.resourceUri &&
1219 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1221 HandlePresenceResponse(endPoint, responseInfo);
1225 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1226 responseInfo->info.tokenLength, NULL, NULL);
1228 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1229 responseInfo->info.tokenLength);
1233 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1234 if(responseInfo->result == CA_EMPTY)
1236 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1237 // We do not have a case for the client to receive a RESET
1238 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1240 //This is the case of receiving an ACK on a request to a slow resource!
1241 OIC_LOG(INFO, TAG, "This is a pure ACK");
1242 //TODO: should we inform the client
1243 // app that at least the request was received at the server?
1246 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1248 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1249 OIC_LOG(INFO, TAG, "Calling into application address space");
1251 OCClientResponse response =
1252 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1253 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1254 FixUpClientResponse(&response);
1255 response.resourceUri = responseInfo->info.resourceUri;
1256 memcpy(response.identity.id, responseInfo->info.identity.id,
1257 sizeof (response.identity.id));
1258 response.identity.id_length = responseInfo->info.identity.id_length;
1260 response.result = CAResponseToOCStackResult(responseInfo->result);
1261 cbNode->callBack(cbNode->context,
1262 cbNode->handle, &response);
1263 FindAndDeleteClientCB(cbNode);
1267 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1268 OIC_LOG(INFO, TAG, "Calling into application address space");
1270 OCClientResponse response =
1271 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1272 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1273 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1274 FixUpClientResponse(&response);
1275 response.resourceUri = responseInfo->info.resourceUri;
1276 memcpy(response.identity.id, responseInfo->info.identity.id,
1277 sizeof (response.identity.id));
1278 response.identity.id_length = responseInfo->info.identity.id_length;
1280 response.result = CAResponseToOCStackResult(responseInfo->result);
1282 if(responseInfo->info.payload &&
1283 responseInfo->info.payloadSize)
1285 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1286 // check the security resource
1287 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1289 type = PAYLOAD_TYPE_SECURITY;
1291 else if (cbNode->method == OC_REST_DISCOVER)
1293 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1294 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1296 type = PAYLOAD_TYPE_DISCOVERY;
1299 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1301 type = PAYLOAD_TYPE_DISCOVERY;
1304 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1306 type = PAYLOAD_TYPE_REPRESENTATION;
1308 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1310 type = PAYLOAD_TYPE_REPRESENTATION;
1313 #ifdef ROUTING_GATEWAY
1314 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1316 type = PAYLOAD_TYPE_REPRESENTATION;
1319 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1321 type = PAYLOAD_TYPE_REPRESENTATION;
1324 else if (strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1326 type = PAYLOAD_TYPE_REPRESENTATION;
1331 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1332 cbNode->method, cbNode->requestUri);
1336 else if (cbNode->method == OC_REST_GET ||
1337 cbNode->method == OC_REST_PUT ||
1338 cbNode->method == OC_REST_POST ||
1339 cbNode->method == OC_REST_OBSERVE ||
1340 cbNode->method == OC_REST_OBSERVE_ALL ||
1341 cbNode->method == OC_REST_DELETE)
1343 if (cbNode->requestUri)
1345 if (0 == strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri))
1347 type = PAYLOAD_TYPE_REPRESENTATION;
1349 else if (0 == strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri))
1351 type = PAYLOAD_TYPE_REPRESENTATION;
1353 if (type == PAYLOAD_TYPE_INVALID)
1355 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1356 cbNode->method, cbNode->requestUri);
1357 type = PAYLOAD_TYPE_REPRESENTATION;
1362 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1363 type = PAYLOAD_TYPE_REPRESENTATION;
1368 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1369 cbNode->method, cbNode->requestUri);
1373 if(OC_STACK_OK != OCParsePayload(&response.payload,
1375 responseInfo->info.payload,
1376 responseInfo->info.payloadSize))
1378 OIC_LOG(ERROR, TAG, "Error converting payload");
1379 OCPayloadDestroy(response.payload);
1384 response.numRcvdVendorSpecificHeaderOptions = 0;
1385 if(responseInfo->info.numOptions > 0)
1388 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1389 if(responseInfo->info.options
1390 && responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1393 uint32_t observationOption;
1394 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1395 for (observationOption=0, i=0;
1396 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1400 (observationOption << 8) | optionData[i];
1402 response.sequenceNumber = observationOption;
1403 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1408 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1411 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1413 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1414 OCPayloadDestroy(response.payload);
1418 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1420 if(&(responseInfo->info.options[i]))
1422 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1423 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1428 if (cbNode->method == OC_REST_OBSERVE &&
1429 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1430 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1431 response.sequenceNumber <= cbNode->sequenceNumber)
1433 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1434 response.sequenceNumber);
1439 // if request uri is '/oic/rd', update ins value of resource.
1440 char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
1443 OCUpdateResourceInsWithResponse(cbNode->requestUri, &response);
1446 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1449 cbNode->sequenceNumber = response.sequenceNumber;
1451 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1453 FindAndDeleteClientCB(cbNode);
1457 // To keep discovery callbacks active.
1458 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1459 MILLISECONDS_PER_SECOND);
1463 //Need to send ACK when the response is CON
1464 if(responseInfo->info.type == CA_MSG_CONFIRM)
1466 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1467 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1470 OCPayloadDestroy(response.payload);
1477 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1478 if(responseInfo->result == CA_EMPTY)
1480 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1481 if(responseInfo->info.type == CA_MSG_RESET)
1483 OIC_LOG(INFO, TAG, "This is a RESET");
1484 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1485 OC_OBSERVER_NOT_INTERESTED);
1487 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1489 OIC_LOG(INFO, TAG, "This is a pure ACK");
1490 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1491 OC_OBSERVER_STILL_INTERESTED);
1494 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1496 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1497 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1498 OC_OBSERVER_FAILED_COMM);
1503 if(!cbNode && !observer)
1505 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1506 || myStackMode == OC_GATEWAY)
1508 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1509 if(responseInfo->result == CA_EMPTY)
1511 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1515 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1516 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1517 CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1521 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1522 || myStackMode == OC_GATEWAY)
1524 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1525 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1527 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1528 responseInfo->info.messageId);
1530 if (responseInfo->info.type == CA_MSG_RESET)
1532 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1533 responseInfo->info.messageId);
1541 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1543 VERIFY_NON_NULL_NR(endPoint, FATAL);
1544 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1546 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1548 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1549 #ifdef ROUTING_GATEWAY
1550 bool needRIHandling = false;
1552 * Routing manager is going to update either of endpoint or response or both.
1553 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1554 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1557 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1559 if(ret != OC_STACK_OK || !needRIHandling)
1561 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1567 * Put source in sender endpoint so that the next packet from application can be routed to
1568 * proper destination and remove "RM" coap header option before passing request / response to
1569 * RI as this option will make no sense to either RI or application.
1571 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1572 (uint8_t *) &(responseInfo->info.numOptions),
1573 (CAEndpoint_t *) endPoint);
1576 OCHandleResponse(endPoint, responseInfo);
1578 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1582 * This function handles error response from CA
1583 * code shall be added to handle the errors
1585 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1587 VERIFY_NON_NULL_NR(endPoint, FATAL);
1588 VERIFY_NON_NULL_NR(errorInfo, FATAL);
1590 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1592 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1593 errorInfo->info.tokenLength, NULL, NULL);
1596 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1597 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1598 FixUpClientResponse(&response);
1599 response.resourceUri = errorInfo->info.resourceUri;
1600 memcpy(response.identity.id, errorInfo->info.identity.id,
1601 sizeof (response.identity.id));
1602 response.identity.id_length = errorInfo->info.identity.id_length;
1603 response.result = CAResultToOCResult(errorInfo->result);
1605 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1608 ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1609 errorInfo->info.tokenLength);
1612 OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1613 OCStackResult result = CAResultToOCResult(errorInfo->result);
1614 if (OC_STACK_COMM_ERROR == result)
1616 OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1617 OC_OBSERVER_FAILED_COMM);
1621 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1625 * This function sends out Direct Stack Responses. These are responses that are not coming
1626 * from the application entity handler. These responses have no payload and are usually ACKs,
1627 * RESETs or some error conditions that were caught by the stack.
1629 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1630 const CAResponseResult_t responseResult, const CAMessageType_t type,
1631 const uint8_t numOptions, const CAHeaderOption_t *options,
1632 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1633 CADataType_t dataType)
1635 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1636 CAResponseInfo_t respInfo = {
1637 .result = responseResult
1639 respInfo.info.messageId = coapID;
1640 respInfo.info.numOptions = numOptions;
1642 if (respInfo.info.numOptions)
1644 respInfo.info.options =
1645 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1646 memcpy (respInfo.info.options, options,
1647 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1651 respInfo.info.payload = NULL;
1652 respInfo.info.token = token;
1653 respInfo.info.tokenLength = tokenLength;
1654 respInfo.info.type = type;
1655 respInfo.info.resourceUri = OICStrdup (resourceUri);
1656 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1657 respInfo.info.dataType = dataType;
1659 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1660 // Add the destination to route option from the endpoint->routeData.
1661 bool doPost = false;
1662 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1663 if(OC_STACK_OK != result)
1665 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1666 OICFree (respInfo.info.resourceUri);
1667 OICFree (respInfo.info.options);
1672 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1673 CARequestInfo_t reqInfo = {.method = CA_POST };
1674 /* The following initialization is not done in a single initializer block as in
1675 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1676 * does not have designated initalizers. This is a work-around for now.
1678 reqInfo.info.type = CA_MSG_NONCONFIRM;
1679 reqInfo.info.messageId = coapID;
1680 reqInfo.info.tokenLength = tokenLength;
1681 reqInfo.info.token = token;
1682 reqInfo.info.numOptions = respInfo.info.numOptions;
1683 reqInfo.info.payload = NULL;
1684 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1685 if (reqInfo.info.numOptions)
1687 reqInfo.info.options =
1688 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1689 if (NULL == reqInfo.info.options)
1691 OIC_LOG(ERROR, TAG, "Calloc failed");
1692 OICFree (reqInfo.info.resourceUri);
1693 OICFree (respInfo.info.resourceUri);
1694 OICFree (respInfo.info.options);
1695 return OC_STACK_NO_MEMORY;
1697 memcpy (reqInfo.info.options, respInfo.info.options,
1698 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1701 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1702 OICFree (reqInfo.info.resourceUri);
1703 OICFree (reqInfo.info.options);
1704 OICFree (respInfo.info.resourceUri);
1705 OICFree (respInfo.info.options);
1706 if (CA_STATUS_OK != caResult)
1708 OIC_LOG(ERROR, TAG, "CASendRequest error");
1709 return CAResultToOCResult(caResult);
1715 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1717 // resourceUri in the info field is cloned in the CA layer and
1718 // thus ownership is still here.
1719 OICFree (respInfo.info.resourceUri);
1720 OICFree (respInfo.info.options);
1721 if(CA_STATUS_OK != caResult)
1723 OIC_LOG(ERROR, TAG, "CASendResponse error");
1724 return CAResultToOCResult(caResult);
1727 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1731 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1733 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1734 OCStackResult result = OC_STACK_ERROR;
1735 if(!protocolRequest)
1737 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1738 return OC_STACK_INVALID_PARAM;
1741 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1742 protocolRequest->tokenLength);
1745 OIC_LOG(INFO, TAG, "This is a new Server Request");
1746 result = AddServerRequest(&request, protocolRequest->coapID,
1747 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1748 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1749 protocolRequest->observationOption, protocolRequest->qos,
1750 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1751 protocolRequest->payload, protocolRequest->requestToken,
1752 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1753 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1754 &protocolRequest->devAddr);
1755 if (OC_STACK_OK != result)
1757 OIC_LOG(ERROR, TAG, "Error adding server request");
1763 OIC_LOG(ERROR, TAG, "Out of Memory");
1764 return OC_STACK_NO_MEMORY;
1767 if(!protocolRequest->reqMorePacket)
1769 request->requestComplete = 1;
1774 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1777 if(request->requestComplete)
1779 OIC_LOG(INFO, TAG, "This Server Request is complete");
1780 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1781 OCResource *resource = NULL;
1782 result = DetermineResourceHandling (request, &resHandling, &resource);
1783 if (result == OC_STACK_OK)
1785 result = ProcessRequest(resHandling, resource, request);
1790 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1791 result = OC_STACK_CONTINUE;
1796 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1798 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1800 OCStackResult requestResult = OC_STACK_ERROR;
1802 if(myStackMode == OC_CLIENT)
1804 //TODO: should the client be responding to requests?
1808 OCServerProtocolRequest serverRequest = {0};
1810 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1812 char * uriWithoutQuery = NULL;
1813 char * query = NULL;
1815 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1817 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1819 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1822 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1823 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1825 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1827 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1828 OICFree(uriWithoutQuery);
1832 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1833 OICFree(uriWithoutQuery);
1840 if(strlen(query) < MAX_QUERY_LENGTH)
1842 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1847 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1853 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1855 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1856 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1857 if (!serverRequest.payload)
1859 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1862 memcpy (serverRequest.payload, requestInfo->info.payload,
1863 requestInfo->info.payloadSize);
1867 serverRequest.reqTotalSize = 0;
1870 switch (requestInfo->method)
1873 serverRequest.method = OC_REST_GET;
1876 serverRequest.method = OC_REST_PUT;
1879 serverRequest.method = OC_REST_POST;
1882 serverRequest.method = OC_REST_DELETE;
1885 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1886 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1887 requestInfo->info.type, requestInfo->info.numOptions,
1888 requestInfo->info.options, requestInfo->info.token,
1889 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1891 OICFree(serverRequest.payload);
1895 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1896 requestInfo->info.tokenLength);
1898 serverRequest.tokenLength = requestInfo->info.tokenLength;
1899 if (serverRequest.tokenLength) {
1901 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1903 if (!serverRequest.requestToken)
1905 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1906 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1907 requestInfo->info.type, requestInfo->info.numOptions,
1908 requestInfo->info.options, requestInfo->info.token,
1909 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1911 OICFree(serverRequest.payload);
1914 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1917 switch (requestInfo->info.acceptFormat)
1919 case CA_FORMAT_APPLICATION_CBOR:
1920 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1922 case CA_FORMAT_UNDEFINED:
1923 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1926 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1929 if (requestInfo->info.type == CA_MSG_CONFIRM)
1931 serverRequest.qos = OC_HIGH_QOS;
1935 serverRequest.qos = OC_LOW_QOS;
1937 // CA does not need the following field
1938 // Are we sure CA does not need them? how is it responding to multicast
1939 serverRequest.delayedResNeeded = 0;
1941 serverRequest.coapID = requestInfo->info.messageId;
1943 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1945 // copy vendor specific header options
1946 uint8_t tempNum = (requestInfo->info.numOptions);
1948 // Assume no observation requested and it is a pure GET.
1949 // If obs registration/de-registration requested it'll be fetched from the
1950 // options in GetObserveHeaderOption()
1951 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1953 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1954 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1957 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1958 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1959 requestInfo->info.type, requestInfo->info.numOptions,
1960 requestInfo->info.options, requestInfo->info.token,
1961 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1963 OICFree(serverRequest.payload);
1964 OICFree(serverRequest.requestToken);
1967 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1968 if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
1970 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1971 sizeof(CAHeaderOption_t)*tempNum);
1974 requestResult = HandleStackRequests (&serverRequest);
1976 // Send ACK to client as precursor to slow response
1977 if (requestResult == OC_STACK_SLOW_RESOURCE)
1979 if (requestInfo->info.type == CA_MSG_CONFIRM)
1981 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1982 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
1986 if (requestResult == OC_STACK_RESOURCE_ERROR
1987 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
1989 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
1991 else if(!OCResultToSuccess(requestResult))
1993 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1995 CAResponseResult_t stackResponse =
1996 OCToCAStackResult(requestResult, serverRequest.method);
1998 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1999 requestInfo->info.type, requestInfo->info.numOptions,
2000 requestInfo->info.options, requestInfo->info.token,
2001 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2004 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2005 // The token is copied in there, and is thus still owned by this function.
2006 OICFree(serverRequest.payload);
2007 OICFree(serverRequest.requestToken);
2008 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2011 //This function will be called back by CA layer when a request is received
2012 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2014 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2017 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2023 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2027 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2028 #ifdef ROUTING_GATEWAY
2029 bool needRIHandling = false;
2030 bool isEmptyMsg = false;
2032 * Routing manager is going to update either of endpoint or request or both.
2033 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2034 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2035 * destination. It can also remove "RM" coap header option before passing request / response to
2036 * RI as this option will make no sense to either RI or application.
2038 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2039 &needRIHandling, &isEmptyMsg);
2040 if(OC_STACK_OK != ret || !needRIHandling)
2042 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2048 * Put source in sender endpoint so that the next packet from application can be routed to
2049 * proper destination and remove RM header option.
2051 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2052 (uint8_t *) &(requestInfo->info.numOptions),
2053 (CAEndpoint_t *) endPoint);
2055 #ifdef ROUTING_GATEWAY
2059 * In Gateways, the MSGType in route option is used to check if the actual
2060 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2061 * EMPTY response is sent in the form of POST request which need to be changed
2062 * to a EMPTY response by RM. This translation is done in this part of the code.
2064 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2065 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2066 .info.messageId = requestInfo->info.messageId,
2067 .info.type = CA_MSG_ACKNOWLEDGE};
2068 OCHandleResponse(endPoint, &respInfo);
2074 // Normal handling of the packet
2075 OCHandleRequests(endPoint, requestInfo);
2077 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2080 //-----------------------------------------------------------------------------
2082 //-----------------------------------------------------------------------------
2084 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2087 !raInfo->username ||
2088 !raInfo->hostname ||
2089 !raInfo->xmpp_domain)
2092 return OC_STACK_INVALID_PARAM;
2094 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2095 gRASetInfo = (result == OC_STACK_OK)? true : false;
2101 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2105 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2108 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2110 if(stackState == OC_STACK_INITIALIZED)
2112 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2113 OCStop() between them are ignored.");
2117 #ifndef ROUTING_GATEWAY
2118 if (OC_GATEWAY == mode)
2120 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2121 return OC_STACK_INVALID_PARAM;
2128 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2129 return OC_STACK_ERROR;
2133 OCStackResult result = OC_STACK_ERROR;
2134 OIC_LOG(INFO, TAG, "Entering OCInit");
2137 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2138 || (mode == OC_GATEWAY)))
2140 OIC_LOG(ERROR, TAG, "Invalid mode");
2141 return OC_STACK_ERROR;
2145 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2147 caglobals.client = true;
2149 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2151 caglobals.server = true;
2154 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2155 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2157 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2159 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2160 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2162 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2165 defaultDeviceHandler = NULL;
2166 defaultDeviceHandlerCallbackParameter = NULL;
2168 result = InitializeScheduleResourceList();
2169 VERIFY_SUCCESS(result, OC_STACK_OK);
2171 result = CAResultToOCResult(CAInitialize());
2172 VERIFY_SUCCESS(result, OC_STACK_OK);
2174 result = CAResultToOCResult(OCSelectNetwork());
2175 VERIFY_SUCCESS(result, OC_STACK_OK);
2177 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2178 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2179 VERIFY_SUCCESS(result, OC_STACK_OK);
2181 switch (myStackMode)
2184 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2185 result = CAResultToOCResult(CAStartDiscoveryServer());
2186 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2189 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2190 result = CAResultToOCResult(CAStartListeningServer());
2191 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2193 case OC_CLIENT_SERVER:
2195 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2196 result = CAResultToOCResult(CAStartListeningServer());
2197 if(result == OC_STACK_OK)
2199 result = CAResultToOCResult(CAStartDiscoveryServer());
2203 VERIFY_SUCCESS(result, OC_STACK_OK);
2206 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2209 #ifdef WITH_PRESENCE
2210 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2211 #endif // WITH_PRESENCE
2213 //Update Stack state to initialized
2214 stackState = OC_STACK_INITIALIZED;
2216 // Initialize resource
2217 if(myStackMode != OC_CLIENT)
2219 result = initResources();
2222 // Initialize the SRM Policy Engine
2223 if(result == OC_STACK_OK)
2225 result = SRMInitPolicyEngine();
2226 // TODO after BeachHead delivery: consolidate into single SRMInit()
2228 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2229 RMSetStackMode(mode);
2230 #ifdef ROUTING_GATEWAY
2231 if (OC_GATEWAY == myStackMode)
2233 result = RMInitialize();
2239 if (result == OC_STACK_OK)
2241 result = InitializeKeepAlive(myStackMode);
2246 if(result != OC_STACK_OK)
2248 OIC_LOG(ERROR, TAG, "Stack initialization error");
2249 TerminateScheduleResourceList();
2250 deleteAllResources();
2252 stackState = OC_STACK_UNINITIALIZED;
2257 OCStackResult OCStop()
2259 OIC_LOG(INFO, TAG, "Entering OCStop");
2261 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2263 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2266 else if (stackState != OC_STACK_INITIALIZED)
2268 OIC_LOG(ERROR, TAG, "Stack not initialized");
2269 return OC_STACK_ERROR;
2272 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2274 CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2275 OCDefaultConnectionStateChangedHandler);
2277 #ifdef WITH_PRESENCE
2278 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2279 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2280 presenceResource.presenceTTL = 0;
2281 #endif // WITH_PRESENCE
2283 #ifdef ROUTING_GATEWAY
2284 if (OC_GATEWAY == myStackMode)
2291 TerminateKeepAlive(myStackMode);
2294 TerminateScheduleResourceList();
2295 // Remove all observers
2296 DeleteObserverList();
2297 // Free memory dynamically allocated for resources
2298 deleteAllResources();
2299 // Remove all the client callbacks
2300 DeleteClientCBList();
2301 // Terminate connectivity-abstraction layer.
2304 // De-init the SRM Policy Engine
2305 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2306 SRMDeInitPolicyEngine();
2308 stackState = OC_STACK_UNINITIALIZED;
2312 OCStackResult OCStartMulticastServer()
2314 if(stackState != OC_STACK_INITIALIZED)
2316 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2317 return OC_STACK_ERROR;
2319 CAResult_t ret = CAStartListeningServer();
2320 if (CA_STATUS_OK != ret)
2322 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2323 return OC_STACK_ERROR;
2328 OCStackResult OCStopMulticastServer()
2330 CAResult_t ret = CAStopListeningServer();
2331 if (CA_STATUS_OK != ret)
2333 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2334 return OC_STACK_ERROR;
2339 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2344 return CA_MSG_CONFIRM;
2349 return CA_MSG_NONCONFIRM;
2354 * A request uri consists of the following components in order:
2357 * CoAP over UDP prefix "coap://"
2358 * CoAP over TCP prefix "coap+tcp://"
2359 * CoAP over DTLS prefix "coaps://"
2360 * CoAP over TLS prefix "coaps+tcp://"
2362 * IPv6 address "[1234::5678]"
2363 * IPv4 address "192.168.1.1"
2364 * optional port ":5683"
2365 * resource uri "/oc/core..."
2367 * for PRESENCE requests, extract resource type.
2369 static OCStackResult ParseRequestUri(const char *fullUri,
2370 OCTransportAdapter adapter,
2371 OCTransportFlags flags,
2372 OCDevAddr **devAddr,
2374 char **resourceType)
2376 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2378 OCStackResult result = OC_STACK_OK;
2379 OCDevAddr *da = NULL;
2383 // provide defaults for all returned values
2390 *resourceUri = NULL;
2394 *resourceType = NULL;
2397 // delimit url prefix, if any
2398 const char *start = fullUri;
2399 char *slash2 = strstr(start, "//");
2404 char *slash = strchr(start, '/');
2407 return OC_STACK_INVALID_URI;
2410 // process url scheme
2411 size_t prefixLen = slash2 - fullUri;
2415 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2416 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2422 // TODO: this logic should come in with unit tests exercising the various strings
2423 // processs url prefix, if any
2424 size_t urlLen = slash - start;
2428 if (urlLen && devAddr)
2429 { // construct OCDevAddr
2430 if (start[0] == '[')
2432 char *close = strchr(++start, ']');
2433 if (!close || close > slash)
2435 return OC_STACK_INVALID_URI;
2438 if (close[1] == ':')
2445 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2449 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2451 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2455 char *dot = strchr(start, '.');
2456 if (dot && dot < slash)
2458 colon = strchr(start, ':');
2459 end = (colon && colon < slash) ? colon : slash;
2464 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2468 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2470 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2478 if (len >= sizeof(da->addr))
2480 return OC_STACK_INVALID_URI;
2482 // collect port, if any
2483 if (colon && colon < slash)
2485 for (colon++; colon < slash; colon++)
2488 if (c < '0' || c > '9')
2490 return OC_STACK_INVALID_URI;
2492 port = 10 * port + c - '0';
2497 if (len >= sizeof(da->addr))
2499 return OC_STACK_INVALID_URI;
2502 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2505 return OC_STACK_NO_MEMORY;
2508 // Decode address per RFC 6874.
2509 result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2510 if (result != OC_STACK_OK)
2517 da->adapter = adapter;
2519 if (!strncmp(fullUri, "coaps", 5))
2521 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2526 // process resource uri, if any
2528 { // request uri and query
2529 size_t ulen = strlen(slash); // resource uri length
2530 size_t tlen = 0; // resource type length
2533 static const char strPresence[] = "/oic/ad?rt=";
2534 static const size_t lenPresence = sizeof(strPresence) - 1;
2535 if (!strncmp(slash, strPresence, lenPresence))
2537 type = slash + lenPresence;
2538 tlen = ulen - lenPresence;
2543 *resourceUri = (char *)OICMalloc(ulen + 1);
2546 result = OC_STACK_NO_MEMORY;
2549 strcpy(*resourceUri, slash);
2552 if (type && resourceType)
2554 *resourceType = (char *)OICMalloc(tlen + 1);
2557 result = OC_STACK_NO_MEMORY;
2561 OICStrcpy(*resourceType, (tlen+1), type);
2568 // free all returned values
2575 OICFree(*resourceUri);
2579 OICFree(*resourceType);
2584 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2588 char uri[CA_MAX_URI_LENGTH];
2590 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2592 *requestUri = OICStrdup(uri);
2595 return OC_STACK_NO_MEMORY;
2602 * Discover or Perform requests on a specified resource
2604 OCStackResult OCDoResource(OCDoHandle *handle,
2606 const char *requestUri,
2607 const OCDevAddr *destination,
2609 OCConnectivityType connectivityType,
2610 OCQualityOfService qos,
2611 OCCallbackData *cbData,
2612 OCHeaderOption *options,
2615 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2617 // Validate input parameters
2618 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2619 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2621 OCStackResult result = OC_STACK_ERROR;
2622 CAResult_t caResult;
2623 CAToken_t token = NULL;
2624 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2625 ClientCB *clientCB = NULL;
2626 OCDoHandle resHandle = NULL;
2627 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2628 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2630 OCTransportAdapter adapter;
2631 OCTransportFlags flags;
2632 // the request contents are put here
2633 CARequestInfo_t requestInfo = {.method = CA_GET};
2634 // requestUri will be parsed into the following three variables
2635 OCDevAddr *devAddr = NULL;
2636 char *resourceUri = NULL;
2637 char *resourceType = NULL;
2640 * Support original behavior with address on resourceUri argument.
2642 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2643 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2647 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2648 if (result != OC_STACK_OK)
2650 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2654 else if (!checkProxyUri(options, numOptions))
2656 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2663 case OC_REST_OBSERVE:
2664 case OC_REST_OBSERVE_ALL:
2665 requestInfo.method = CA_GET;
2668 requestInfo.method = CA_PUT;
2671 requestInfo.method = CA_POST;
2673 case OC_REST_DELETE:
2674 requestInfo.method = CA_DELETE;
2676 case OC_REST_DISCOVER:
2678 #ifdef WITH_PRESENCE
2679 case OC_REST_PRESENCE:
2681 if (destination || devAddr)
2683 requestInfo.isMulticast = false;
2687 tmpDevAddr.adapter = adapter;
2688 tmpDevAddr.flags = flags;
2689 destination = &tmpDevAddr;
2690 requestInfo.isMulticast = true;
2692 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
2693 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
2694 // replacing method type with GET.
2695 requestInfo.method = CA_GET;
2698 result = OC_STACK_INVALID_METHOD;
2702 if (!devAddr && !destination)
2704 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2705 result = OC_STACK_INVALID_PARAM;
2709 /* If not original behavior, use destination argument */
2710 if (destination && !devAddr)
2712 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2715 result = OC_STACK_NO_MEMORY;
2718 *devAddr = *destination;
2721 resHandle = GenerateInvocationHandle();
2724 result = OC_STACK_NO_MEMORY;
2728 caResult = CAGenerateToken(&token, tokenLength);
2729 if (caResult != CA_STATUS_OK)
2731 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2732 result= OC_STACK_ERROR;
2736 // fill in request data
2737 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2738 requestInfo.info.token = token;
2739 requestInfo.info.tokenLength = tokenLength;
2741 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2743 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2744 options, numOptions, OC_OBSERVE_REGISTER);
2745 if (result != OC_STACK_OK)
2749 requestInfo.info.numOptions = numOptions + 1;
2753 requestInfo.info.numOptions = numOptions;
2754 requestInfo.info.options =
2755 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2756 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2757 numOptions * sizeof(CAHeaderOption_t));
2760 CopyDevAddrToEndpoint(devAddr, &endpoint);
2765 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2768 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2771 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2775 requestInfo.info.payload = NULL;
2776 requestInfo.info.payloadSize = 0;
2777 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2780 // prepare for response
2781 #ifdef WITH_PRESENCE
2782 if (method == OC_REST_PRESENCE)
2784 char *presenceUri = NULL;
2785 result = OCPreparePresence(&endpoint, &presenceUri,
2786 requestInfo.isMulticast);
2787 if (OC_STACK_OK != result)
2792 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2793 // Presence notification will form a canonical uri to
2794 // look for callbacks into the application.
2797 OICFree(resourceUri);
2799 resourceUri = presenceUri;
2803 // update resourceUri onto requestInfo after check presence uri
2804 requestInfo.info.resourceUri = resourceUri;
2806 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2807 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2808 method, devAddr, resourceUri, resourceType, ttl);
2809 if (OC_STACK_OK != result)
2814 devAddr = NULL; // Client CB list entry now owns it
2815 resourceUri = NULL; // Client CB list entry now owns it
2816 resourceType = NULL; // Client CB list entry now owns it
2818 #ifdef WITH_PRESENCE
2819 if (method == OC_REST_PRESENCE)
2821 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
2825 *handle = resHandle;
2833 result = OCSendRequest(&endpoint, &requestInfo);
2834 if (OC_STACK_OK != result)
2841 *handle = resHandle;
2845 if (result != OC_STACK_OK)
2847 OIC_LOG(ERROR, TAG, "OCDoResource error");
2848 FindAndDeleteClientCB(clientCB);
2849 CADestroyToken(token);
2857 // This is the owner of the payload object, so we free it
2858 OCPayloadDestroy(payload);
2859 OICFree(requestInfo.info.payload);
2861 OICFree(resourceUri);
2862 OICFree(resourceType);
2863 OICFree(requestInfo.info.options);
2867 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2871 * This ftn is implemented one of two ways in the case of observation:
2873 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2874 * Remove the callback associated on client side.
2875 * When the next notification comes in from server,
2876 * reply with RESET message to server.
2877 * Keep in mind that the server will react to RESET only
2878 * if the last notification was sent as CON
2880 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2881 * and it is associated with an observe request
2882 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2883 * Send CON Observe request to server with
2884 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2885 * Remove the callback associated on client side.
2887 OCStackResult ret = OC_STACK_OK;
2888 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2889 CARequestInfo_t requestInfo = {.method = CA_GET};
2893 return OC_STACK_INVALID_PARAM;
2896 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2899 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2900 return OC_STACK_ERROR;
2903 switch (clientCB->method)
2905 case OC_REST_OBSERVE:
2906 case OC_REST_OBSERVE_ALL:
2908 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2910 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2912 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2914 FindAndDeleteClientCB(clientCB);
2918 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2920 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2921 requestInfo.info.token = clientCB->token;
2922 requestInfo.info.tokenLength = clientCB->tokenLength;
2924 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2925 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2927 return OC_STACK_ERROR;
2929 requestInfo.info.numOptions = numOptions + 1;
2930 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2933 ret = OCSendRequest(&endpoint, &requestInfo);
2935 if (requestInfo.info.options)
2937 OICFree (requestInfo.info.options);
2939 if (requestInfo.info.resourceUri)
2941 OICFree (requestInfo.info.resourceUri);
2946 case OC_REST_DISCOVER:
2947 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2948 clientCB->requestUri);
2949 FindAndDeleteClientCB(clientCB);
2952 #ifdef WITH_PRESENCE
2953 case OC_REST_PRESENCE:
2954 FindAndDeleteClientCB(clientCB);
2959 ret = OC_STACK_INVALID_METHOD;
2967 * @brief Register Persistent storage callback.
2968 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2970 * OC_STACK_OK - No errors; Success
2971 * OC_STACK_INVALID_PARAM - Invalid parameter
2973 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2975 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2976 if(!persistentStorageHandler)
2978 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2979 return OC_STACK_INVALID_PARAM;
2983 if( !persistentStorageHandler->open ||
2984 !persistentStorageHandler->close ||
2985 !persistentStorageHandler->read ||
2986 !persistentStorageHandler->unlink ||
2987 !persistentStorageHandler->write)
2989 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2990 return OC_STACK_INVALID_PARAM;
2993 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2996 #ifdef WITH_PRESENCE
2998 OCStackResult OCProcessPresence()
3000 OCStackResult result = OC_STACK_OK;
3002 // the following line floods the log with messages that are irrelevant
3003 // to most purposes. Uncomment as needed.
3004 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3005 ClientCB* cbNode = NULL;
3006 OCClientResponse clientResponse;
3007 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3009 LL_FOREACH(cbList, cbNode)
3011 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3016 uint32_t now = GetTicks(0);
3017 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3018 cbNode->presence->TTLlevel);
3019 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3021 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3026 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3028 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3029 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3031 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3033 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3035 clientResponse.sequenceNumber = 0;
3036 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3037 clientResponse.devAddr = *cbNode->devAddr;
3038 FixUpClientResponse(&clientResponse);
3039 clientResponse.payload = NULL;
3041 // Increment the TTLLevel (going to a next state), so we don't keep
3042 // sending presence notification to client.
3043 cbNode->presence->TTLlevel++;
3044 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3045 cbNode->presence->TTLlevel);
3047 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3048 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3050 FindAndDeleteClientCB(cbNode);
3054 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3059 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3060 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3061 CARequestInfo_t requestInfo = {.method = CA_GET};
3063 OIC_LOG(DEBUG, TAG, "time to test server presence");
3065 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3067 requestData.type = CA_MSG_NONCONFIRM;
3068 requestData.token = cbNode->token;
3069 requestData.tokenLength = cbNode->tokenLength;
3070 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3071 requestInfo.method = CA_GET;
3072 requestInfo.info = requestData;
3074 result = OCSendRequest(&endpoint, &requestInfo);
3075 if (OC_STACK_OK != result)
3080 cbNode->presence->TTLlevel++;
3081 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3084 if (result != OC_STACK_OK)
3086 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3091 #endif // WITH_PRESENCE
3093 OCStackResult OCProcess()
3095 #ifdef WITH_PRESENCE
3096 OCProcessPresence();
3098 CAHandleRequestResponse();
3100 #ifdef ROUTING_GATEWAY
3110 #ifdef WITH_PRESENCE
3111 OCStackResult OCStartPresence(const uint32_t ttl)
3113 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3114 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3115 OCChangeResourceProperty(
3116 &(((OCResource *)presenceResource.handle)->resourceProperties),
3119 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3121 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3122 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3126 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3127 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3131 presenceResource.presenceTTL = ttl;
3133 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3135 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3137 presenceState = OC_PRESENCE_INITIALIZED;
3139 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3141 CAToken_t caToken = NULL;
3142 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3143 if (caResult != CA_STATUS_OK)
3145 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3146 CADestroyToken(caToken);
3147 return OC_STACK_ERROR;
3150 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3151 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3152 CADestroyToken(caToken);
3155 // Each time OCStartPresence is called
3156 // a different random 32-bit integer number is used
3157 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3159 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3160 OC_PRESENCE_TRIGGER_CREATE);
3163 OCStackResult OCStopPresence()
3165 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3166 OCStackResult result = OC_STACK_ERROR;
3168 if(presenceResource.handle)
3170 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3172 // make resource inactive
3173 result = OCChangeResourceProperty(
3174 &(((OCResource *) presenceResource.handle)->resourceProperties),
3178 if(result != OC_STACK_OK)
3181 "Changing the presence resource properties to ACTIVE not successful");
3185 return SendStopNotification();
3189 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3190 void* callbackParameter)
3192 defaultDeviceHandler = entityHandler;
3193 defaultDeviceHandlerCallbackParameter = callbackParameter;
3198 OCStackResult OCCreateResource(OCResourceHandle *handle,
3199 const char *resourceTypeName,
3200 const char *resourceInterfaceName,
3201 const char *uri, OCEntityHandler entityHandler,
3202 void* callbackParam,
3203 uint8_t resourceProperties)
3206 OCResource *pointer = NULL;
3207 OCStackResult result = OC_STACK_ERROR;
3209 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3211 if(myStackMode == OC_CLIENT)
3213 return OC_STACK_INVALID_PARAM;
3215 // Validate parameters
3216 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3218 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3219 return OC_STACK_INVALID_URI;
3221 // Is it presented during resource discovery?
3222 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3224 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3225 return OC_STACK_INVALID_PARAM;
3228 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3230 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3234 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3236 // Make sure resourceProperties bitmask has allowed properties specified
3237 if (resourceProperties
3238 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3239 OC_EXPLICIT_DISCOVERABLE
3248 OIC_LOG(ERROR, TAG, "Invalid property");
3249 return OC_STACK_INVALID_PARAM;
3252 // If the headResource is NULL, then no resources have been created...
3253 pointer = headResource;
3256 // At least one resources is in the resource list, so we need to search for
3257 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3260 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3262 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3263 return OC_STACK_INVALID_PARAM;
3265 pointer = pointer->next;
3268 // Create the pointer and insert it into the resource list
3269 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3272 result = OC_STACK_NO_MEMORY;
3275 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3277 insertResource(pointer);
3280 pointer->uri = OICStrdup(uri);
3283 result = OC_STACK_NO_MEMORY;
3287 // Set properties. Set OC_ACTIVE
3288 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3291 // Add the resourcetype to the resource
3292 result = BindResourceTypeToResource(pointer, resourceTypeName);
3293 if (result != OC_STACK_OK)
3295 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3299 // Add the resourceinterface to the resource
3300 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3301 if (result != OC_STACK_OK)
3303 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3307 // If an entity handler has been passed, attach it to the newly created
3308 // resource. Otherwise, set the default entity handler.
3311 pointer->entityHandler = entityHandler;
3312 pointer->entityHandlerCallbackParam = callbackParam;
3316 pointer->entityHandler = defaultResourceEHandler;
3317 pointer->entityHandlerCallbackParam = NULL;
3320 // Initialize a pointer indicating child resources in case of collection
3321 pointer->rsrcChildResourcesHead = NULL;
3324 result = OC_STACK_OK;
3326 #ifdef WITH_PRESENCE
3327 if (presenceResource.handle)
3329 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3330 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3334 if (result != OC_STACK_OK)
3336 // Deep delete of resource and other dynamic elements that it contains
3337 deleteResource(pointer);
3342 OCStackResult OCBindResource(
3343 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3345 OCResource *resource = NULL;
3346 OCChildResource *tempChildResource = NULL;
3347 OCChildResource *newChildResource = NULL;
3349 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3351 // Validate parameters
3352 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3353 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3354 // Container cannot contain itself
3355 if (collectionHandle == resourceHandle)
3357 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3358 return OC_STACK_INVALID_PARAM;
3361 // Use the handle to find the resource in the resource linked list
3362 resource = findResource((OCResource *) collectionHandle);
3365 OIC_LOG(ERROR, TAG, "Collection handle not found");
3366 return OC_STACK_INVALID_PARAM;
3369 // Look for an open slot to add add the child resource.
3370 // If found, add it and return success
3372 tempChildResource = resource->rsrcChildResourcesHead;
3374 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3376 // TODO: what if one of child resource was deregistered without unbinding?
3377 tempChildResource = tempChildResource->next;
3380 // Do memory allocation for child resource
3381 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3382 if(!newChildResource)
3384 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3385 return OC_STACK_ERROR;
3388 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3389 newChildResource->next = NULL;
3391 if(!resource->rsrcChildResourcesHead)
3393 resource->rsrcChildResourcesHead = newChildResource;
3396 tempChildResource->next = newChildResource;
3399 OIC_LOG(INFO, TAG, "resource bound");
3401 #ifdef WITH_PRESENCE
3402 if (presenceResource.handle)
3404 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3405 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3406 OC_PRESENCE_TRIGGER_CHANGE);
3413 OCStackResult OCUnBindResource(
3414 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3416 OCResource *resource = NULL;
3417 OCChildResource *tempChildResource = NULL;
3418 OCChildResource *tempLastChildResource = NULL;
3420 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3422 // Validate parameters
3423 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3424 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3425 // Container cannot contain itself
3426 if (collectionHandle == resourceHandle)
3428 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3429 return OC_STACK_INVALID_PARAM;
3432 // Use the handle to find the resource in the resource linked list
3433 resource = findResource((OCResource *) collectionHandle);
3436 OIC_LOG(ERROR, TAG, "Collection handle not found");
3437 return OC_STACK_INVALID_PARAM;
3440 // Look for an open slot to add add the child resource.
3441 // If found, add it and return success
3442 if(!resource->rsrcChildResourcesHead)
3444 OIC_LOG(INFO, TAG, "resource not found in collection");
3446 // Unable to add resourceHandle, so return error
3447 return OC_STACK_ERROR;
3451 tempChildResource = resource->rsrcChildResourcesHead;
3453 while (tempChildResource)
3455 if(tempChildResource->rsrcResource == resourceHandle)
3457 // if resource going to be unbinded is the head one.
3458 if( tempChildResource == resource->rsrcChildResourcesHead )
3460 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3461 OICFree(resource->rsrcChildResourcesHead);
3462 resource->rsrcChildResourcesHead = temp;
3467 OCChildResource *temp = tempChildResource->next;
3468 OICFree(tempChildResource);
3469 tempLastChildResource->next = temp;
3473 OIC_LOG(INFO, TAG, "resource unbound");
3475 // Send notification when resource is unbounded successfully.
3476 #ifdef WITH_PRESENCE
3477 if (presenceResource.handle)
3479 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3480 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3481 OC_PRESENCE_TRIGGER_CHANGE);
3484 tempChildResource = NULL;
3485 tempLastChildResource = NULL;
3491 tempLastChildResource = tempChildResource;
3492 tempChildResource = tempChildResource->next;
3495 OIC_LOG(INFO, TAG, "resource not found in collection");
3497 tempChildResource = NULL;
3498 tempLastChildResource = NULL;
3500 // Unable to add resourceHandle, so return error
3501 return OC_STACK_ERROR;
3504 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3506 if (!resourceItemName)
3510 // Per RFC 6690 only registered values must follow the first rule below.
3511 // At this point in time the only values registered begin with "core", and
3512 // all other values are specified as opaque strings where multiple values
3513 // are separated by a space.
3514 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3516 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3518 if (resourceItemName[index] != '.'
3519 && resourceItemName[index] != '-'
3520 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3521 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3529 for (size_t index = 0; resourceItemName[index]; ++index)
3531 if (resourceItemName[index] == ' '
3532 || resourceItemName[index] == '\t'
3533 || resourceItemName[index] == '\r'
3534 || resourceItemName[index] == '\n')
3544 OCStackResult BindResourceTypeToResource(OCResource* resource,
3545 const char *resourceTypeName)
3547 OCResourceType *pointer = NULL;
3549 OCStackResult result = OC_STACK_ERROR;
3551 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3553 if (!ValidateResourceTypeInterface(resourceTypeName))
3555 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3556 return OC_STACK_INVALID_PARAM;
3559 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3562 result = OC_STACK_NO_MEMORY;
3566 str = OICStrdup(resourceTypeName);
3569 result = OC_STACK_NO_MEMORY;
3572 pointer->resourcetypename = str;
3573 pointer->next = NULL;
3575 insertResourceType(resource, pointer);
3576 result = OC_STACK_OK;
3579 if (result != OC_STACK_OK)
3588 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3589 const char *resourceInterfaceName)
3591 OCResourceInterface *pointer = NULL;
3593 OCStackResult result = OC_STACK_ERROR;
3595 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3597 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3599 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3600 return OC_STACK_INVALID_PARAM;
3603 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3605 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3608 result = OC_STACK_NO_MEMORY;
3612 str = OICStrdup(resourceInterfaceName);
3615 result = OC_STACK_NO_MEMORY;
3618 pointer->name = str;
3620 // Bind the resourceinterface to the resource
3621 insertResourceInterface(resource, pointer);
3623 result = OC_STACK_OK;
3626 if (result != OC_STACK_OK)
3635 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3636 const char *resourceTypeName)
3639 OCStackResult result = OC_STACK_ERROR;
3640 OCResource *resource = NULL;
3642 resource = findResource((OCResource *) handle);
3645 OIC_LOG(ERROR, TAG, "Resource not found");
3646 return OC_STACK_ERROR;
3649 result = BindResourceTypeToResource(resource, resourceTypeName);
3651 #ifdef WITH_PRESENCE
3652 if(presenceResource.handle)
3654 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3655 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3662 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3663 const char *resourceInterfaceName)
3666 OCStackResult result = OC_STACK_ERROR;
3667 OCResource *resource = NULL;
3669 resource = findResource((OCResource *) handle);
3672 OIC_LOG(ERROR, TAG, "Resource not found");
3673 return OC_STACK_ERROR;
3676 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3678 #ifdef WITH_PRESENCE
3679 if (presenceResource.handle)
3681 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3682 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3689 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3691 OCResource *pointer = headResource;
3693 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3697 *numResources = *numResources + 1;
3698 pointer = pointer->next;
3703 OCResourceHandle OCGetResourceHandle(uint8_t index)
3705 OCResource *pointer = headResource;
3707 for( uint8_t i = 0; i < index && pointer; ++i)
3709 pointer = pointer->next;
3711 return (OCResourceHandle) pointer;
3714 OCStackResult OCDeleteResource(OCResourceHandle handle)
3718 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3719 return OC_STACK_INVALID_PARAM;
3722 OCResource *resource = findResource((OCResource *) handle);
3723 if (resource == NULL)
3725 OIC_LOG(ERROR, TAG, "Resource not found");
3726 return OC_STACK_NO_RESOURCE;
3729 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3731 OIC_LOG(ERROR, TAG, "Error deleting resource");
3732 return OC_STACK_ERROR;
3738 const char *OCGetResourceUri(OCResourceHandle handle)
3740 OCResource *resource = NULL;
3742 resource = findResource((OCResource *) handle);
3745 return resource->uri;
3747 return (const char *) NULL;
3750 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3752 OCResource *resource = NULL;
3754 resource = findResource((OCResource *) handle);
3757 return resource->resourceProperties;
3759 return (OCResourceProperty)-1;
3762 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3763 uint8_t *numResourceTypes)
3765 OCResource *resource = NULL;
3766 OCResourceType *pointer = NULL;
3768 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3769 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3771 *numResourceTypes = 0;
3773 resource = findResource((OCResource *) handle);
3776 pointer = resource->rsrcType;
3779 *numResourceTypes = *numResourceTypes + 1;
3780 pointer = pointer->next;
3786 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3788 OCResourceType *resourceType = NULL;
3790 resourceType = findResourceTypeAtIndex(handle, index);
3793 return resourceType->resourcetypename;
3795 return (const char *) NULL;
3798 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3799 uint8_t *numResourceInterfaces)
3801 OCResourceInterface *pointer = NULL;
3802 OCResource *resource = NULL;
3804 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3805 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3807 *numResourceInterfaces = 0;
3808 resource = findResource((OCResource *) handle);
3811 pointer = resource->rsrcInterface;
3814 *numResourceInterfaces = *numResourceInterfaces + 1;
3815 pointer = pointer->next;
3821 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3823 OCResourceInterface *resourceInterface = NULL;
3825 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3826 if (resourceInterface)
3828 return resourceInterface->name;
3830 return (const char *) NULL;
3833 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3836 OCResource *resource = NULL;
3837 OCChildResource *tempChildResource = NULL;
3840 resource = findResource((OCResource *) collectionHandle);
3846 tempChildResource = resource->rsrcChildResourcesHead;
3848 while(tempChildResource)
3852 return tempChildResource->rsrcResource;
3855 tempChildResource = tempChildResource->next;
3858 // In this case, the number of resource handles in the collection exceeds the index
3859 tempChildResource = NULL;
3863 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3864 OCEntityHandler entityHandler,
3865 void* callbackParam)
3867 OCResource *resource = NULL;
3869 // Validate parameters
3870 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3872 // Use the handle to find the resource in the resource linked list
3873 resource = findResource((OCResource *)handle);
3876 OIC_LOG(ERROR, TAG, "Resource not found");
3877 return OC_STACK_ERROR;
3881 resource->entityHandler = entityHandler;
3882 resource->entityHandlerCallbackParam = callbackParam;
3884 #ifdef WITH_PRESENCE
3885 if (presenceResource.handle)
3887 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3888 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3895 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3897 OCResource *resource = NULL;
3899 resource = findResource((OCResource *)handle);
3902 OIC_LOG(ERROR, TAG, "Resource not found");
3907 return resource->entityHandler;
3910 void incrementSequenceNumber(OCResource * resPtr)
3912 // Increment the sequence number
3913 resPtr->sequenceNum += 1;
3914 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3916 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3921 #ifdef WITH_PRESENCE
3922 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3923 OCPresenceTrigger trigger)
3925 OIC_LOG(INFO, TAG, "SendPresenceNotification");
3926 OCResource *resPtr = NULL;
3927 OCStackResult result = OC_STACK_ERROR;
3928 OCMethod method = OC_REST_PRESENCE;
3929 uint32_t maxAge = 0;
3930 resPtr = findResource((OCResource *) presenceResource.handle);
3933 return OC_STACK_NO_RESOURCE;
3936 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3938 maxAge = presenceResource.presenceTTL;
3940 result = SendAllObserverNotification(method, resPtr, maxAge,
3941 trigger, resourceType, OC_LOW_QOS);
3947 OCStackResult SendStopNotification()
3949 OIC_LOG(INFO, TAG, "SendStopNotification");
3950 OCResource *resPtr = NULL;
3951 OCStackResult result = OC_STACK_ERROR;
3952 OCMethod method = OC_REST_PRESENCE;
3953 resPtr = findResource((OCResource *) presenceResource.handle);
3956 return OC_STACK_NO_RESOURCE;
3959 // maxAge is 0. ResourceType is NULL.
3960 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3966 #endif // WITH_PRESENCE
3967 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3969 OCResource *resPtr = NULL;
3970 OCStackResult result = OC_STACK_ERROR;
3971 OCMethod method = OC_REST_NOMETHOD;
3972 uint32_t maxAge = 0;
3974 OIC_LOG(INFO, TAG, "Notifying all observers");
3975 #ifdef WITH_PRESENCE
3976 if(handle == presenceResource.handle)
3980 #endif // WITH_PRESENCE
3981 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3983 // Verify that the resource exists
3984 resPtr = findResource ((OCResource *) handle);
3987 return OC_STACK_NO_RESOURCE;
3991 //only increment in the case of regular observing (not presence)
3992 incrementSequenceNumber(resPtr);
3993 method = OC_REST_OBSERVE;
3994 maxAge = MAX_OBSERVE_AGE;
3995 #ifdef WITH_PRESENCE
3996 result = SendAllObserverNotification (method, resPtr, maxAge,
3997 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3999 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4006 OCNotifyListOfObservers (OCResourceHandle handle,
4007 OCObservationId *obsIdList,
4008 uint8_t numberOfIds,
4009 const OCRepPayload *payload,
4010 OCQualityOfService qos)
4012 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4014 OCResource *resPtr = NULL;
4015 //TODO: we should allow the server to define this
4016 uint32_t maxAge = MAX_OBSERVE_AGE;
4018 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4019 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4020 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4022 resPtr = findResource ((OCResource *) handle);
4023 if (NULL == resPtr || myStackMode == OC_CLIENT)
4025 return OC_STACK_NO_RESOURCE;
4029 incrementSequenceNumber(resPtr);
4031 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4032 payload, maxAge, qos));
4035 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4037 OCStackResult result = OC_STACK_ERROR;
4038 OCServerRequest *serverRequest = NULL;
4040 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4042 // Validate input parameters
4043 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4044 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4047 // Get pointer to request info
4048 serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
4051 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4052 result = serverRequest->ehResponseHandler(ehResponse);
4058 //#ifdef DIRECT_PAIRING
4059 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4061 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4062 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4064 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4068 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4071 const OCDPDev_t* OCGetDirectPairedDevices()
4073 return (const OCDPDev_t*)DPGetPairedDevices();
4076 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4077 OCDirectPairingCB resultCallback)
4079 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4080 if(NULL == peer || NULL == pinNumber)
4082 OIC_LOG(ERROR, TAG, "Invalid parameters");
4083 return OC_STACK_INVALID_PARAM;
4085 if (NULL == resultCallback)
4087 OIC_LOG(ERROR, TAG, "Invalid callback");
4088 return OC_STACK_INVALID_CALLBACK;
4091 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4092 pinNumber, (OCDirectPairingResultCB)resultCallback);
4094 //#endif // DIRECT_PAIRING
4096 //-----------------------------------------------------------------------------
4097 // Private internal function definitions
4098 //-----------------------------------------------------------------------------
4099 static OCDoHandle GenerateInvocationHandle()
4101 OCDoHandle handle = NULL;
4102 // Generate token here, it will be deleted when the transaction is deleted
4103 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4106 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4112 #ifdef WITH_PRESENCE
4113 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4114 OCResourceProperty resourceProperties, uint8_t enable)
4118 return OC_STACK_INVALID_PARAM;
4120 if (resourceProperties
4121 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4123 OIC_LOG(ERROR, TAG, "Invalid property");
4124 return OC_STACK_INVALID_PARAM;
4128 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4132 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4138 OCStackResult initResources()
4140 OCStackResult result = OC_STACK_OK;
4142 headResource = NULL;
4143 tailResource = NULL;
4144 // Init Virtual Resources
4145 #ifdef WITH_PRESENCE
4146 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4148 result = OCCreateResource(&presenceResource.handle,
4149 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4151 OC_RSRVD_PRESENCE_URI,
4155 //make resource inactive
4156 result = OCChangeResourceProperty(
4157 &(((OCResource *) presenceResource.handle)->resourceProperties),
4160 #ifndef WITH_ARDUINO
4161 if (result == OC_STACK_OK)
4163 result = SRMInitSecureResources();
4167 if(result == OC_STACK_OK)
4169 CreateResetProfile();
4170 result = OCCreateResource(&deviceResource,
4171 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4172 OC_RSRVD_INTERFACE_DEFAULT,
4173 OC_RSRVD_DEVICE_URI,
4177 if(result == OC_STACK_OK)
4179 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4180 OC_RSRVD_INTERFACE_READ);
4184 if(result == OC_STACK_OK)
4186 result = OCCreateResource(&platformResource,
4187 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4188 OC_RSRVD_INTERFACE_DEFAULT,
4189 OC_RSRVD_PLATFORM_URI,
4193 if(result == OC_STACK_OK)
4195 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4196 OC_RSRVD_INTERFACE_READ);
4203 void insertResource(OCResource *resource)
4207 headResource = resource;
4208 tailResource = resource;
4212 tailResource->next = resource;
4213 tailResource = resource;
4215 resource->next = NULL;
4218 OCResource *findResource(OCResource *resource)
4220 OCResource *pointer = headResource;
4224 if (pointer == resource)
4228 pointer = pointer->next;
4233 void deleteAllResources()
4235 OCResource *pointer = headResource;
4236 OCResource *temp = NULL;
4240 temp = pointer->next;
4241 #ifdef WITH_PRESENCE
4242 if (pointer != (OCResource *) presenceResource.handle)
4244 #endif // WITH_PRESENCE
4245 deleteResource(pointer);
4246 #ifdef WITH_PRESENCE
4248 #endif // WITH_PRESENCE
4251 memset(&platformResource, 0, sizeof(platformResource));
4252 memset(&deviceResource, 0, sizeof(deviceResource));
4254 memset(&brokerResource, 0, sizeof(brokerResource));
4257 SRMDeInitSecureResources();
4259 #ifdef WITH_PRESENCE
4260 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4261 // presence notification attributed to their deletion to be processed.
4262 deleteResource((OCResource *) presenceResource.handle);
4263 memset(&presenceResource, 0, sizeof(presenceResource));
4264 #endif // WITH_PRESENCE
4267 OCStackResult deleteResource(OCResource *resource)
4269 OCResource *prev = NULL;
4270 OCResource *temp = NULL;
4273 OIC_LOG(DEBUG,TAG,"resource is NULL");
4274 return OC_STACK_INVALID_PARAM;
4277 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4279 temp = headResource;
4282 if (temp == resource)
4284 // Invalidate all Resource Properties.
4285 resource->resourceProperties = (OCResourceProperty) 0;
4286 #ifdef WITH_PRESENCE
4287 if(resource != (OCResource *) presenceResource.handle)
4289 #endif // WITH_PRESENCE
4290 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4291 #ifdef WITH_PRESENCE
4294 if(presenceResource.handle)
4296 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4297 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4300 // Only resource in list.
4301 if (temp == headResource && temp == tailResource)
4303 headResource = NULL;
4304 tailResource = NULL;
4307 else if (temp == headResource)
4309 headResource = temp->next;
4312 else if (temp == tailResource)
4314 tailResource = prev;
4315 tailResource->next = NULL;
4319 prev->next = temp->next;
4322 deleteResourceElements(temp);
4333 return OC_STACK_ERROR;
4336 void deleteResourceElements(OCResource *resource)
4343 OICFree(resource->uri);
4344 deleteResourceType(resource->rsrcType);
4345 deleteResourceInterface(resource->rsrcInterface);
4346 OCDeleteResourceAttributes(resource->rsrcAttributes);
4349 void deleteResourceType(OCResourceType *resourceType)
4351 OCResourceType *pointer = resourceType;
4352 OCResourceType *next = NULL;
4356 next = pointer->next;
4357 OICFree(pointer->resourcetypename);
4363 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4365 OCResourceInterface *pointer = resourceInterface;
4366 OCResourceInterface *next = NULL;
4370 next = pointer->next;
4371 OICFree(pointer->name);
4377 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
4379 OCAttribute *next = NULL;
4380 for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
4382 next = pointer->next;
4383 if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
4385 OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
4389 OICFree(pointer->attrValue);
4391 OICFree(pointer->attrName);
4396 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4398 OCResourceType *pointer = NULL;
4399 OCResourceType *previous = NULL;
4400 if (!resource || !resourceType)
4404 // resource type list is empty.
4405 else if (!resource->rsrcType)
4407 resource->rsrcType = resourceType;
4411 pointer = resource->rsrcType;
4415 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4417 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4418 OICFree(resourceType->resourcetypename);
4419 OICFree(resourceType);
4423 pointer = pointer->next;
4428 previous->next = resourceType;
4431 resourceType->next = NULL;
4433 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4436 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4438 OCResource *resource = NULL;
4439 OCResourceType *pointer = NULL;
4441 // Find the specified resource
4442 resource = findResource((OCResource *) handle);
4448 // Make sure a resource has a resourcetype
4449 if (!resource->rsrcType)
4454 // Iterate through the list
4455 pointer = resource->rsrcType;
4456 for(uint8_t i = 0; i< index && pointer; ++i)
4458 pointer = pointer->next;
4463 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4465 if(resourceTypeList && resourceTypeName)
4467 OCResourceType * rtPointer = resourceTypeList;
4468 while(resourceTypeName && rtPointer)
4470 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4471 if(rtPointer->resourcetypename &&
4472 strcmp(resourceTypeName, (const char *)
4473 (rtPointer->resourcetypename)) == 0)
4477 rtPointer = rtPointer->next;
4485 * Insert a new interface into interface linked list only if not already present.
4486 * If alredy present, 2nd arg is free'd.
4487 * Default interface will always be first if present.
4489 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4491 OCResourceInterface *pointer = NULL;
4492 OCResourceInterface *previous = NULL;
4494 newInterface->next = NULL;
4496 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4498 if (!*firstInterface)
4500 // If first interface is not oic.if.baseline, by default add it as first interface type.
4501 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4503 *firstInterface = newInterface;
4507 OCStackResult result = BindResourceInterfaceToResource(resource,
4508 OC_RSRVD_INTERFACE_DEFAULT);
4509 if (result != OC_STACK_OK)
4511 OICFree(newInterface->name);
4512 OICFree(newInterface);
4515 if (*firstInterface)
4517 (*firstInterface)->next = newInterface;
4521 // If once add oic.if.baseline, later too below code take care of freeing memory.
4522 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4524 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4526 OICFree(newInterface->name);
4527 OICFree(newInterface);
4530 // This code will not hit anymore, keeping
4533 newInterface->next = *firstInterface;
4534 *firstInterface = newInterface;
4539 pointer = *firstInterface;
4542 if (strcmp(newInterface->name, pointer->name) == 0)
4544 OICFree(newInterface->name);
4545 OICFree(newInterface);
4549 pointer = pointer->next;
4554 previous->next = newInterface;
4559 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4562 OCResource *resource = NULL;
4563 OCResourceInterface *pointer = NULL;
4565 // Find the specified resource
4566 resource = findResource((OCResource *) handle);
4572 // Make sure a resource has a resourceinterface
4573 if (!resource->rsrcInterface)
4578 // Iterate through the list
4579 pointer = resource->rsrcInterface;
4581 for (uint8_t i = 0; i < index && pointer; ++i)
4583 pointer = pointer->next;
4589 * This function splits the uri using the '?' delimiter.
4590 * "uriWithoutQuery" is the block of characters between the beginning
4591 * till the delimiter or '\0' which ever comes first.
4592 * "query" is whatever is to the right of the delimiter if present.
4593 * No delimiter sets the query to NULL.
4594 * If either are present, they will be malloc'ed into the params 2, 3.
4595 * The first param, *uri is left untouched.
4597 * NOTE: This function does not account for whitespace at the end of the uri NOR
4598 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4599 * part of the query.
4601 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4605 return OC_STACK_INVALID_URI;
4607 if(!query || !uriWithoutQuery)
4609 return OC_STACK_INVALID_PARAM;
4613 *uriWithoutQuery = NULL;
4615 size_t uriWithoutQueryLen = 0;
4616 size_t queryLen = 0;
4617 size_t uriLen = strlen(uri);
4619 char *pointerToDelimiter = strstr(uri, "?");
4621 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4622 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4624 if (uriWithoutQueryLen)
4626 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4627 if (!*uriWithoutQuery)
4631 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4635 *query = (char *) OICCalloc(queryLen + 1, 1);
4638 OICFree(*uriWithoutQuery);
4639 *uriWithoutQuery = NULL;
4642 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4648 return OC_STACK_NO_MEMORY;
4651 static const OicUuid_t* OCGetServerInstanceID(void)
4653 static bool generated = false;
4654 static OicUuid_t sid;
4660 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4662 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4669 const char* OCGetServerInstanceIDString(void)
4671 static bool generated = false;
4672 static char sidStr[UUID_STRING_SIZE];
4679 const OicUuid_t *sid = OCGetServerInstanceID();
4680 if (sid && OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4682 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4690 CAResult_t OCSelectNetwork()
4692 CAResult_t retResult = CA_STATUS_FAILED;
4693 CAResult_t caResult = CA_STATUS_OK;
4695 CATransportAdapter_t connTypes[] = {
4697 CA_ADAPTER_RFCOMM_BTEDR,
4698 CA_ADAPTER_GATT_BTLE,
4701 ,CA_ADAPTER_REMOTE_ACCESS
4708 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4710 for(int i = 0; i < numConnTypes; i++)
4712 // If CA status is not initialized, CASelectNetwork() will not be called.
4713 if (caResult != CA_STATUS_NOT_INITIALIZED)
4715 caResult = CASelectNetwork(connTypes[i]);
4716 if (caResult == CA_STATUS_OK)
4718 retResult = CA_STATUS_OK;
4723 if (retResult != CA_STATUS_OK)
4725 return caResult; // Returns error of appropriate transport that failed fatally.
4731 OCStackResult CAResultToOCResult(CAResult_t caResult)
4737 case CA_STATUS_INVALID_PARAM:
4738 return OC_STACK_INVALID_PARAM;
4739 case CA_ADAPTER_NOT_ENABLED:
4740 return OC_STACK_ADAPTER_NOT_ENABLED;
4741 case CA_SERVER_STARTED_ALREADY:
4743 case CA_SERVER_NOT_STARTED:
4744 return OC_STACK_ERROR;
4745 case CA_DESTINATION_NOT_REACHABLE:
4746 return OC_STACK_COMM_ERROR;
4747 case CA_SOCKET_OPERATION_FAILED:
4748 return OC_STACK_COMM_ERROR;
4749 case CA_SEND_FAILED:
4750 return OC_STACK_COMM_ERROR;
4751 case CA_RECEIVE_FAILED:
4752 return OC_STACK_COMM_ERROR;
4753 case CA_MEMORY_ALLOC_FAILED:
4754 return OC_STACK_NO_MEMORY;
4755 case CA_REQUEST_TIMEOUT:
4756 return OC_STACK_TIMEOUT;
4757 case CA_DESTINATION_DISCONNECTED:
4758 return OC_STACK_COMM_ERROR;
4759 case CA_STATUS_FAILED:
4760 return OC_STACK_ERROR;
4761 case CA_NOT_SUPPORTED:
4762 return OC_STACK_NOTIMPL;
4764 return OC_STACK_ERROR;
4768 bool OCResultToSuccess(OCStackResult ocResult)
4773 case OC_STACK_RESOURCE_CREATED:
4774 case OC_STACK_RESOURCE_DELETED:
4775 case OC_STACK_CONTINUE:
4776 case OC_STACK_RESOURCE_CHANGED:
4777 case OC_STACK_SLOW_RESOURCE:
4785 OCStackResult OCSetProxyURI(const char *uri)
4787 return CAResultToOCResult(CASetProxyUri(uri));
4791 #if defined(RD_CLIENT) || defined(RD_SERVER)
4792 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
4794 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4796 OCResource *resource = NULL;
4798 resource = findResource((OCResource *) handle);
4801 OIC_LOG(ERROR, TAG, "Resource not found");
4802 return OC_STACK_ERROR;
4805 resource->ins = ins;
4811 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
4812 const OCClientResponse *response)
4814 // Validate input parameters
4815 VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
4816 VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
4818 char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
4821 return OC_STACK_NO_MEMORY;
4823 strncpy(targetUri, requestUri, strlen(requestUri) + 1);
4825 if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
4827 OIC_LOG(DEBUG, TAG, "update the ins of published resource");
4829 char rdPubUri[MAX_URI_LENGTH] = { 0 };
4830 snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
4831 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
4833 if (strcmp(rdPubUri, targetUri) == 0)
4835 // Update resource unique id in stack.
4838 if (response->payload)
4840 OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
4841 OCRepPayload **links = NULL;
4842 size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
4843 if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
4844 &links, dimensions))
4847 for (; i < dimensions[0]; i++)
4850 if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
4852 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
4854 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
4856 OCBindResourceInsToResource(handle, ins);
4865 else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
4867 OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
4869 uint8_t numResources = 0;
4870 OCGetNumberOfResources(&numResources);
4872 char *ins = strstr(targetUri, OC_RSRVD_INS);
4875 for (uint8_t i = 0; i < numResources; i++)
4877 OCResourceHandle resHandle = OCGetResourceHandle(i);
4880 OCBindResourceInsToResource(resHandle, 0);
4886 const char *token = "&";
4887 char *iterTokenPtr = NULL;
4888 char *start = strtok_r(targetUri, token, &iterTokenPtr);
4890 while (start != NULL)
4892 char *query = start;
4893 query = strstr(query, OC_RSRVD_INS);
4896 uint8_t queryIns = atoi(query + 4);
4897 for (uint8_t i = 0; i < numResources; i++)
4899 OCResourceHandle resHandle = OCGetResourceHandle(i);
4903 OCGetResourceIns(resHandle, &resIns);
4904 if (queryIns && queryIns == resIns)
4906 OCBindResourceInsToResource(resHandle, 0);
4912 start = strtok_r(NULL, token, &iterTokenPtr);
4921 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
4925 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
4929 OCResource *pointer = headResource;
4933 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
4935 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
4938 pointer = pointer->next;
4943 OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
4945 OCResource *resource = NULL;
4947 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4948 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
4950 resource = findResource((OCResource *) handle);
4953 *ins = resource->ins;
4956 return OC_STACK_ERROR;
4960 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
4961 void* optionData, size_t optionDataLength)
4965 OIC_LOG (INFO, TAG, "Header options are NULL");
4966 return OC_STACK_INVALID_PARAM;
4971 OIC_LOG (INFO, TAG, "optionData are NULL");
4972 return OC_STACK_INVALID_PARAM;
4977 OIC_LOG (INFO, TAG, "numOptions is NULL");
4978 return OC_STACK_INVALID_PARAM;
4981 if (*numOptions >= MAX_HEADER_OPTIONS)
4983 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
4984 return OC_STACK_NO_MEMORY;
4987 ocHdrOpt += *numOptions;
4988 ocHdrOpt->protocolID = OC_COAP_ID;
4989 ocHdrOpt->optionID = optionID;
4990 ocHdrOpt->optionLength =
4991 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
4992 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
4993 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
4999 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5000 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5002 if (!ocHdrOpt || !numOptions)
5004 OIC_LOG (INFO, TAG, "No options present");
5010 OIC_LOG (INFO, TAG, "optionData are NULL");
5011 return OC_STACK_INVALID_PARAM;
5014 if (!receivedDataLength)
5016 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5017 return OC_STACK_INVALID_PARAM;
5020 for (uint8_t i = 0; i < numOptions; i++)
5022 if (ocHdrOpt[i].optionID == optionID)
5024 if (optionDataLength >= ocHdrOpt->optionLength)
5026 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5027 *receivedDataLength = ocHdrOpt->optionLength;
5032 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5033 return OC_STACK_ERROR;
5040 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5042 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5043 if (g_adapterHandler)
5045 g_adapterHandler(adapter, enabled);
5049 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5051 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5052 if (g_connectionHandler)
5054 g_connectionHandler(info, isConnected);
5058 * If the client observes one or more resources over a reliable connection,
5059 * then the CoAP server (or intermediary in the role of the CoAP server)
5060 * MUST remove all entries associated with the client endpoint from the lists
5061 * of observers when the connection is either closed or times out.
5065 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5066 CopyEndpointToDevAddr(info, &devAddr);
5068 // remove observer list with remote device address.
5069 DeleteObserverUsingDevAddr(&devAddr);
5073 void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
5074 CAConnectionStateChangedCB connectionHandler)
5076 OIC_LOG(DEBUG, TAG, "OCSetNetworkMonitorHandler");
5077 g_adapterHandler = adapterHandler;
5078 g_connectionHandler = connectionHandler;
5081 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5084 OCStackResult ret = OC_STACK_ERROR;
5086 ret = GetDoxmDeviceID(&oicUuid);
5087 if (OC_STACK_OK == ret)
5089 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5093 OIC_LOG(ERROR, TAG, "Device ID Get error");
5098 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5101 OCStackResult ret = OC_STACK_ERROR;
5103 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5104 for (int i = 0; i < UUID_LENGTH; i++)
5106 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5108 ret = SetDoxmDeviceID(&oicUuid);