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"
62 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
63 #include "routingutility.h"
64 #ifdef ROUTING_GATEWAY
65 #include "routingmanager.h"
70 #include "oickeepalive.h"
73 //#ifdef DIRECT_PAIRING
74 #include "directpairing.h"
77 #ifdef HAVE_ARDUINO_TIME_H
80 #ifdef HAVE_SYS_TIME_H
83 #include <coap/coap.h>
85 #ifdef HAVE_ARPA_INET_H
86 #include <arpa/inet.h>
90 #define UINT32_MAX (0xFFFFFFFFUL)
93 //-----------------------------------------------------------------------------
95 //-----------------------------------------------------------------------------
98 OC_STACK_UNINITIALIZED = 0,
100 OC_STACK_UNINIT_IN_PROGRESS
106 OC_PRESENCE_UNINITIALIZED = 0,
107 OC_PRESENCE_INITIALIZED
111 //-----------------------------------------------------------------------------
113 //-----------------------------------------------------------------------------
114 static OCStackState stackState = OC_STACK_UNINITIALIZED;
116 OCResource *headResource = NULL;
117 static OCResource *tailResource = NULL;
118 static OCResourceHandle platformResource = {0};
119 static OCResourceHandle deviceResource = {0};
121 static OCResourceHandle brokerResource = {0};
125 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
126 static PresenceResource presenceResource = {0};
127 static uint8_t PresenceTimeOutSize = 0;
128 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
131 static OCMode myStackMode;
133 //TODO: revisit this design
134 static bool gRASetInfo = false;
136 OCDeviceEntityHandler defaultDeviceHandler;
137 void* defaultDeviceHandlerCallbackParameter = NULL;
138 static const char COAP_TCP_SCHEME[] = "coap+tcp:";
139 static const char COAPS_TCP_SCHEME[] = "coaps+tcp:";
140 static const char CORESPEC[] = "core";
142 //-----------------------------------------------------------------------------
144 //-----------------------------------------------------------------------------
145 #define TAG "OIC_RI_STACK"
146 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
147 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
148 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
149 TAG, #arg " is NULL"); return (retVal); } }
150 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
151 TAG, #arg " is NULL"); return; } }
152 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
155 //TODO: we should allow the server to define this
156 #define MAX_OBSERVE_AGE (0x2FFFFUL)
158 #define MILLISECONDS_PER_SECOND (1000)
160 //-----------------------------------------------------------------------------
161 // Private internal function prototypes
162 //-----------------------------------------------------------------------------
165 * Generate handle of OCDoResource invocation for callback management.
167 * @return Generated OCDoResource handle.
169 static OCDoHandle GenerateInvocationHandle();
172 * Initialize resource data structures, variables, etc.
174 * @return ::OC_STACK_OK on success, some other value upon failure.
176 static OCStackResult initResources();
179 * Add a resource to the end of the linked list of resources.
181 * @param resource Resource to be added
183 static void insertResource(OCResource *resource);
186 * Find a resource in the linked list of resources.
188 * @param resource Resource to be found.
189 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
192 static OCResource *findResource(OCResource *resource);
195 * Insert a resource type into a resource's resource type linked list.
196 * If resource type already exists, it will not be inserted and the
197 * resourceType will be free'd.
198 * resourceType->next should be null to avoid memory leaks.
199 * Function returns silently for null args.
201 * @param resource Resource where resource type is to be inserted.
202 * @param resourceType Resource type to be inserted.
204 static void insertResourceType(OCResource *resource,
205 OCResourceType *resourceType);
208 * Get a resource type at the specified index within a resource.
210 * @param handle Handle of resource.
211 * @param index Index of resource type.
213 * @return Pointer to resource type if found, NULL otherwise.
215 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
219 * Insert a resource interface into a resource's resource interface linked list.
220 * If resource interface already exists, it will not be inserted and the
221 * resourceInterface will be free'd.
222 * resourceInterface->next should be null to avoid memory leaks.
224 * @param resource Resource where resource interface is to be inserted.
225 * @param resourceInterface Resource interface to be inserted.
227 static void insertResourceInterface(OCResource *resource,
228 OCResourceInterface *resourceInterface);
231 * Get a resource interface at the specified index within a resource.
233 * @param handle Handle of resource.
234 * @param index Index of resource interface.
236 * @return Pointer to resource interface if found, NULL otherwise.
238 static OCResourceInterface *findResourceInterfaceAtIndex(
239 OCResourceHandle handle, uint8_t index);
242 * Delete all of the dynamically allocated elements that were created for the resource type.
244 * @param resourceType Specified resource type.
246 static void deleteResourceType(OCResourceType *resourceType);
249 * Delete all of the dynamically allocated elements that were created for the resource interface.
251 * @param resourceInterface Specified resource interface.
253 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
256 * Delete all of the dynamically allocated elements that were created for the resource.
258 * @param resource Specified resource.
260 static void deleteResourceElements(OCResource *resource);
263 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
266 * @param handle Handle of resource to be deleted.
268 * @return ::OC_STACK_OK on success, some other value upon failure.
270 static OCStackResult deleteResource(OCResource *resource);
273 * Delete all of the resources in the resource list.
275 static void deleteAllResources();
278 * Increment resource sequence number. Handles rollover.
280 * @param resPtr Pointer to resource.
282 static void incrementSequenceNumber(OCResource * resPtr);
285 * Attempts to initialize every network interface that the CA Layer might have compiled in.
287 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
288 * return something other than @ref CA_STATUS_OK, then this function fails.
290 * @return ::CA_STATUS_OK on success, some other value upon failure.
292 static CAResult_t OCSelectNetwork();
295 * Get the CoAP ticks after the specified number of milli-seconds.
297 * @param afterMilliSeconds Milli-seconds.
301 static uint32_t GetTicks(uint32_t afterMilliSeconds);
304 * Convert CAResult_t to OCStackResult.
306 * @param caResult CAResult_t code.
307 * @return ::OC_STACK_OK on success, some other value upon failure.
309 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
312 * Convert CAResponseResult_t to OCStackResult.
314 * @param caCode CAResponseResult_t code.
315 * @return ::OC_STACK_OK on success, some other value upon failure.
317 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
320 * Convert OCStackResult to CAResponseResult_t.
322 * @param caCode OCStackResult code.
323 * @param method OCMethod method the return code replies to.
324 * @return ::CA_CONTENT on OK, some other value upon failure.
326 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
329 * Convert OCTransportFlags_t to CATransportModifiers_t.
331 * @param ocConType OCTransportFlags_t input.
332 * @return CATransportFlags
334 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
337 * Convert CATransportFlags_t to OCTransportModifiers_t.
339 * @param caConType CATransportFlags_t input.
340 * @return OCTransportFlags
342 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
345 * Handle response from presence request.
347 * @param endPoint CA remote endpoint.
348 * @param responseInfo CA response info.
349 * @return ::OC_STACK_OK on success, some other value upon failure.
351 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
352 const CAResponseInfo_t *responseInfo);
355 * This function will be called back by CA layer when a response is received.
357 * @param endPoint CA remote endpoint.
358 * @param responseInfo CA response info.
360 static void HandleCAResponses(const CAEndpoint_t* endPoint,
361 const CAResponseInfo_t* responseInfo);
364 * This function will be called back by CA layer when a request is received.
366 * @param endPoint CA remote endpoint.
367 * @param requestInfo CA request info.
369 static void HandleCARequests(const CAEndpoint_t* endPoint,
370 const CARequestInfo_t* requestInfo);
373 * Extract query from a URI.
375 * @param uri Full URI with query.
376 * @param query Pointer to string that will contain query.
377 * @param newURI Pointer to string that will contain URI.
378 * @return ::OC_STACK_OK on success, some other value upon failure.
380 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
383 * Finds a resource type in an OCResourceType link-list.
385 * @param resourceTypeList The link-list to be searched through.
386 * @param resourceTypeName The key to search for.
388 * @return Resource type that matches the key (ie. resourceTypeName) or
389 * NULL if there is either an invalid parameter or this function was unable to find the key.
391 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
392 const char * resourceTypeName);
395 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
396 * TTL will be set to maxAge.
398 * @param cbNode Callback Node for which presence ttl is to be reset.
399 * @param maxAge New value of ttl in seconds.
401 * @return ::OC_STACK_OK on success, some other value upon failure.
403 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
406 * Ensure the accept header option is set appropriatly before sending the requests and routing
407 * header option is updated with destination.
409 * @param object CA remote endpoint.
410 * @param requestInfo CA request info.
412 * @return ::OC_STACK_OK on success, some other value upon failure.
414 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
416 //-----------------------------------------------------------------------------
417 // Internal functions
418 //-----------------------------------------------------------------------------
420 bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
422 if (!options || 0 == numOptions)
424 OIC_LOG (INFO, TAG, "No options present");
428 for (uint8_t i = 0; i < numOptions; i++)
430 if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
432 OIC_LOG(DEBUG, TAG, "Proxy URI is present");
439 uint32_t GetTicks(uint32_t afterMilliSeconds)
444 // Guard against overflow of uint32_t
445 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
446 COAP_TICKS_PER_SECOND)
448 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
456 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
458 VERIFY_NON_NULL_NR(in, FATAL);
459 VERIFY_NON_NULL_NR(out, FATAL);
461 out->adapter = (OCTransportAdapter)in->adapter;
462 out->flags = CAToOCTransportFlags(in->flags);
463 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
464 out->port = in->port;
465 out->ifindex = in->ifindex;
466 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
467 /* This assert is to prevent accidental mismatch between address size macros defined in
468 * RI and CA and cause crash here. */
469 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
470 "Address size mismatch between RI and CA");
471 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
475 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
477 VERIFY_NON_NULL_NR(in, FATAL);
478 VERIFY_NON_NULL_NR(out, FATAL);
480 out->adapter = (CATransportAdapter_t)in->adapter;
481 out->flags = OCToCATransportFlags(in->flags);
482 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
483 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
484 /* This assert is to prevent accidental mismatch between address size macros defined in
485 * RI and CA and cause crash here. */
486 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
487 "Address size mismatch between RI and CA");
488 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
490 out->port = in->port;
491 out->ifindex = in->ifindex;
494 void FixUpClientResponse(OCClientResponse *cr)
496 VERIFY_NON_NULL_NR(cr, FATAL);
498 cr->addr = &cr->devAddr;
499 cr->connType = (OCConnectivityType)
500 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
503 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
505 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
506 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
508 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
509 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
510 if (OC_STACK_OK != rmResult)
512 OIC_LOG(ERROR, TAG, "Add destination option failed");
517 // OC stack prefer CBOR encoded payloads.
518 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
519 CAResult_t result = CASendRequest(object, requestInfo);
520 if(CA_STATUS_OK != result)
522 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
523 return CAResultToOCResult(result);
527 //-----------------------------------------------------------------------------
528 // Internal API function
529 //-----------------------------------------------------------------------------
531 // This internal function is called to update the stack with the status of
532 // observers and communication failures
533 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
535 OCStackResult result = OC_STACK_ERROR;
536 ResourceObserver * observer = NULL;
537 OCEntityHandlerRequest ehRequest = {0};
541 case OC_OBSERVER_NOT_INTERESTED:
542 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
543 observer = GetObserverUsingToken (token, tokenLength);
546 result = FormOCEntityHandlerRequest(&ehRequest,
547 (OCRequestHandle)NULL,
550 (OCResourceHandle)NULL,
551 NULL, PAYLOAD_TYPE_REPRESENTATION,
553 OC_OBSERVE_DEREGISTER,
556 if(result != OC_STACK_OK)
560 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
561 observer->resource->entityHandlerCallbackParam);
564 result = DeleteObserverUsingToken (token, tokenLength);
565 if(result == OC_STACK_OK)
567 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
571 result = OC_STACK_OK;
572 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
576 case OC_OBSERVER_STILL_INTERESTED:
577 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
578 observer = GetObserverUsingToken (token, tokenLength);
581 observer->forceHighQos = 0;
582 observer->failedCommCount = 0;
583 result = OC_STACK_OK;
587 result = OC_STACK_OBSERVER_NOT_FOUND;
591 case OC_OBSERVER_FAILED_COMM:
592 OIC_LOG(DEBUG, TAG, "observer is unreachable");
593 observer = GetObserverUsingToken (token, tokenLength);
596 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
598 result = FormOCEntityHandlerRequest(&ehRequest,
599 (OCRequestHandle)NULL,
602 (OCResourceHandle)NULL,
603 NULL, PAYLOAD_TYPE_REPRESENTATION,
605 OC_OBSERVE_DEREGISTER,
608 if(result != OC_STACK_OK)
610 return OC_STACK_ERROR;
612 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
613 observer->resource->entityHandlerCallbackParam);
615 result = DeleteObserverUsingToken (token, tokenLength);
616 if(result == OC_STACK_OK)
618 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
622 result = OC_STACK_OK;
623 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
628 observer->failedCommCount++;
629 result = OC_STACK_CONTINUE;
631 observer->forceHighQos = 1;
632 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
636 OIC_LOG(ERROR, TAG, "Unknown status");
637 result = OC_STACK_ERROR;
643 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
645 OCStackResult ret = OC_STACK_ERROR;
649 case CA_ADAPTER_NOT_ENABLED:
650 case CA_SERVER_NOT_STARTED:
651 ret = OC_STACK_ADAPTER_NOT_ENABLED;
653 case CA_MEMORY_ALLOC_FAILED:
654 ret = OC_STACK_NO_MEMORY;
656 case CA_STATUS_INVALID_PARAM:
657 ret = OC_STACK_INVALID_PARAM;
665 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
667 OCStackResult ret = OC_STACK_ERROR;
671 ret = OC_STACK_RESOURCE_CREATED;
674 ret = OC_STACK_RESOURCE_DELETED;
677 ret = OC_STACK_RESOURCE_CHANGED;
684 ret = OC_STACK_INVALID_QUERY;
686 case CA_UNAUTHORIZED_REQ:
687 ret = OC_STACK_UNAUTHORIZED_REQ;
690 ret = OC_STACK_INVALID_OPTION;
693 ret = OC_STACK_NO_RESOURCE;
695 case CA_RETRANSMIT_TIMEOUT:
696 ret = OC_STACK_COMM_ERROR;
698 case CA_REQUEST_ENTITY_TOO_LARGE:
699 ret = OC_STACK_TOO_LARGE_REQ;
707 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
709 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
718 // This Response Code is like HTTP 204 "No Content" but only used in
719 // response to POST and PUT requests.
723 // This Response Code is like HTTP 200 "OK" but only used in response to
728 // This should not happen but,
729 // give it a value just in case but output an error
731 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
735 case OC_STACK_RESOURCE_CREATED:
738 case OC_STACK_RESOURCE_DELETED:
741 case OC_STACK_RESOURCE_CHANGED:
744 case OC_STACK_INVALID_QUERY:
747 case OC_STACK_INVALID_OPTION:
750 case OC_STACK_NO_RESOURCE:
753 case OC_STACK_COMM_ERROR:
754 ret = CA_RETRANSMIT_TIMEOUT;
756 case OC_STACK_UNAUTHORIZED_REQ:
757 ret = CA_UNAUTHORIZED_REQ;
765 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
767 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
769 // supply default behavior.
770 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
772 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
774 if ((caFlags & OC_MASK_SCOPE) == 0)
776 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
781 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
783 return (OCTransportFlags)caFlags;
786 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
788 uint32_t lowerBound = 0;
789 uint32_t higherBound = 0;
791 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
793 return OC_STACK_INVALID_PARAM;
796 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
798 cbNode->presence->TTL = maxAgeSeconds;
800 for (int index = 0; index < PresenceTimeOutSize; index++)
802 // Guard against overflow
803 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
806 lowerBound = GetTicks((PresenceTimeOut[index] *
807 cbNode->presence->TTL *
808 MILLISECONDS_PER_SECOND)/100);
812 lowerBound = GetTicks(UINT32_MAX);
815 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
818 higherBound = GetTicks((PresenceTimeOut[index + 1] *
819 cbNode->presence->TTL *
820 MILLISECONDS_PER_SECOND)/100);
824 higherBound = GetTicks(UINT32_MAX);
827 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
829 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
830 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
831 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
834 cbNode->presence->TTLlevel = 0;
836 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
840 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
842 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
844 return OC_RSRVD_TRIGGER_CREATE;
846 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
848 return OC_RSRVD_TRIGGER_CHANGE;
852 return OC_RSRVD_TRIGGER_DELETE;
856 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
860 return OC_PRESENCE_TRIGGER_CREATE;
862 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
864 return OC_PRESENCE_TRIGGER_CREATE;
866 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
868 return OC_PRESENCE_TRIGGER_CHANGE;
872 return OC_PRESENCE_TRIGGER_DELETE;
877 * Encode an address string to match RFC 6874.
879 * @param outputAddress a char array to be written with the encoded string.
881 * @param outputSize size of outputAddress buffer.
883 * @param inputAddress a char array of size <= CA_MAX_URI_LENGTH
884 * containing a valid IPv6 address string.
886 * @return OC_STACK_OK if encoding succeeded.
887 * Else an error occured.
889 OCStackResult encodeAddressForRFC6874(char *outputAddress,
891 const char *inputAddress)
893 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
894 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
896 size_t inputLength = strnlen(inputAddress, outputSize);
898 // inputSize includes the null terminator
899 size_t inputSize = inputLength + 1;
901 if (inputSize > outputSize)
903 OIC_LOG_V(ERROR, TAG,
904 "encodeAddressForRFC6874 failed: "
905 "outputSize (%zu) < inputSize (%zu)",
906 outputSize, inputSize);
908 return OC_STACK_ERROR;
911 char* percentChar = strchr(inputAddress, '%');
913 // If there is no '%' character, then no change is required to the string.
914 if (NULL == percentChar)
916 OICStrcpy(outputAddress, outputSize, inputAddress);
920 const char* addressPart = &inputAddress[0];
921 const char* scopeIdPart = percentChar + 1;
923 // Sanity check to make sure this string doesn't have more '%' characters
924 if (NULL != strchr(scopeIdPart, '%'))
926 return OC_STACK_ERROR;
929 // If no string follows the first '%', then the input was invalid.
930 if (scopeIdPart[0] == '\0')
932 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
933 return OC_STACK_ERROR;
936 // Check to see if the string is already encoded
937 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
939 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
940 return OC_STACK_ERROR;
943 // Fail if we don't have room for encoded string's two additional chars
944 if (outputSize < (inputSize + 2))
946 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: encoded output will not fit!");
947 return OC_STACK_ERROR;
950 // Restore the null terminator with an escaped '%' character, per RFC 6874
951 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
952 strcat(outputAddress, "%25");
953 strcat(outputAddress, scopeIdPart);
959 * The cononical presence allows constructed URIs to be string compared.
961 * requestUri must be a char array of size CA_MAX_URI_LENGTH
963 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
964 char *presenceUri, bool isMulticast)
966 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
967 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
968 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
972 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
973 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
976 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
977 if (ep->adapter == CA_ADAPTER_IP)
979 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
981 if ('\0' == ep->addr[0]) // multicast
983 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
987 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
989 OCStackResult result = encodeAddressForRFC6874(addressEncoded,
990 sizeof(addressEncoded),
993 if (OC_STACK_OK != result)
998 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
999 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1004 if ('\0' == ep->addr[0]) // multicast
1006 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1007 ep->port = OC_MULTICAST_PORT;
1009 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1010 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1014 // might work for other adapters (untested, but better than nothing)
1015 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1016 OC_RSRVD_PRESENCE_URI);
1020 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1021 const CAResponseInfo_t *responseInfo)
1023 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1024 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1026 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1027 ClientCB * cbNode = NULL;
1028 char *resourceTypeName = NULL;
1029 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1030 OCStackResult result = OC_STACK_ERROR;
1031 uint32_t maxAge = 0;
1033 char presenceUri[CA_MAX_URI_LENGTH];
1035 int presenceSubscribe = 0;
1036 int multicastPresenceSubscribe = 0;
1038 if (responseInfo->result != CA_CONTENT)
1040 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1041 return OC_STACK_ERROR;
1044 response.payload = NULL;
1045 response.result = OC_STACK_OK;
1047 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1048 FixUpClientResponse(&response);
1050 if (responseInfo->info.payload)
1052 result = OCParsePayload(&response.payload,
1053 PAYLOAD_TYPE_PRESENCE,
1054 responseInfo->info.payload,
1055 responseInfo->info.payloadSize);
1057 if(result != OC_STACK_OK)
1059 OIC_LOG(ERROR, TAG, "Presence parse failed");
1062 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1064 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1065 result = OC_STACK_ERROR;
1068 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1069 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1070 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1073 // check for unicast presence
1074 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri,
1075 responseInfo->isMulticast);
1076 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1078 return OC_STACK_INVALID_URI;
1080 OIC_LOG(ERROR, TAG, "check for unicast presence");
1081 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1084 presenceSubscribe = 1;
1088 // check for multicast presence
1089 OIC_LOG(ERROR, TAG, "check for multicast presence");
1090 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1093 multicastPresenceSubscribe = 1;
1097 if (!presenceSubscribe && !multicastPresenceSubscribe)
1099 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1103 if (presenceSubscribe)
1105 if(cbNode->sequenceNumber == response.sequenceNumber)
1107 OIC_LOG(INFO, TAG, "No presence change");
1108 ResetPresenceTTL(cbNode, maxAge);
1109 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1115 OIC_LOG(INFO, TAG, "Stopping presence");
1116 response.result = OC_STACK_PRESENCE_STOPPED;
1117 if(cbNode->presence)
1119 OICFree(cbNode->presence->timeOut);
1120 OICFree(cbNode->presence);
1121 cbNode->presence = NULL;
1126 if(!cbNode->presence)
1128 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1130 if(!(cbNode->presence))
1132 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1133 result = OC_STACK_NO_MEMORY;
1137 VERIFY_NON_NULL_V(cbNode->presence);
1138 cbNode->presence->timeOut = NULL;
1139 cbNode->presence->timeOut = (uint32_t *)
1140 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1141 if(!(cbNode->presence->timeOut)){
1143 "Could not allocate memory for cbNode->presence->timeOut");
1144 OICFree(cbNode->presence);
1145 result = OC_STACK_NO_MEMORY;
1150 ResetPresenceTTL(cbNode, maxAge);
1152 cbNode->sequenceNumber = response.sequenceNumber;
1154 // Ensure that a filter is actually applied.
1155 if( resourceTypeName && cbNode->filterResourceType)
1157 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1166 // This is the multicast case
1167 OCMulticastNode* mcNode = NULL;
1168 mcNode = GetMCPresenceNode(presenceUri);
1172 if(mcNode->nonce == response.sequenceNumber)
1174 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1177 mcNode->nonce = response.sequenceNumber;
1181 OIC_LOG(INFO, TAG, "Stopping presence");
1182 response.result = OC_STACK_PRESENCE_STOPPED;
1187 char* uri = OICStrdup(presenceUri);
1191 "No Memory for URI to store in the presence node");
1192 result = OC_STACK_NO_MEMORY;
1196 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1197 if(result == OC_STACK_NO_MEMORY)
1200 "No Memory for Multicast Presence Node");
1204 // presence node now owns uri
1209 // Ensure that a filter is actually applied.
1210 if(resourceTypeName && cbNode->filterResourceType)
1212 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1213 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1219 OIC_LOG(INFO, TAG, "Callback for presence");
1221 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1223 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1225 FindAndDeleteClientCB(cbNode);
1229 OCPayloadDestroy(response.payload);
1233 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1235 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1237 if(responseInfo->info.resourceUri &&
1238 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1240 HandlePresenceResponse(endPoint, responseInfo);
1244 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1245 responseInfo->info.tokenLength, NULL, NULL);
1247 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1248 responseInfo->info.tokenLength);
1252 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1253 if(responseInfo->result == CA_EMPTY)
1255 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1256 // We do not have a case for the client to receive a RESET
1257 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1259 //This is the case of receiving an ACK on a request to a slow resource!
1260 OIC_LOG(INFO, TAG, "This is a pure ACK");
1261 //TODO: should we inform the client
1262 // app that at least the request was received at the server?
1265 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1267 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1268 OIC_LOG(INFO, TAG, "Calling into application address space");
1270 OCClientResponse response =
1271 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1272 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1273 FixUpClientResponse(&response);
1274 response.resourceUri = responseInfo->info.resourceUri;
1275 memcpy(response.identity.id, responseInfo->info.identity.id,
1276 sizeof (response.identity.id));
1277 response.identity.id_length = responseInfo->info.identity.id_length;
1279 response.result = CAResponseToOCStackResult(responseInfo->result);
1280 cbNode->callBack(cbNode->context,
1281 cbNode->handle, &response);
1282 FindAndDeleteClientCB(cbNode);
1286 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1287 OIC_LOG(INFO, TAG, "Calling into application address space");
1289 OCClientResponse response =
1290 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1291 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1292 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1293 FixUpClientResponse(&response);
1294 response.resourceUri = responseInfo->info.resourceUri;
1295 memcpy(response.identity.id, responseInfo->info.identity.id,
1296 sizeof (response.identity.id));
1297 response.identity.id_length = responseInfo->info.identity.id_length;
1299 response.result = CAResponseToOCStackResult(responseInfo->result);
1301 if(responseInfo->info.payload &&
1302 responseInfo->info.payloadSize)
1304 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1305 // check the security resource
1306 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1308 type = PAYLOAD_TYPE_SECURITY;
1310 else if (cbNode->method == OC_REST_DISCOVER)
1312 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1313 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1315 type = PAYLOAD_TYPE_DISCOVERY;
1318 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1320 type = PAYLOAD_TYPE_DISCOVERY;
1323 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1325 type = PAYLOAD_TYPE_DEVICE;
1327 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1329 type = PAYLOAD_TYPE_PLATFORM;
1331 #ifdef ROUTING_GATEWAY
1332 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1334 type = PAYLOAD_TYPE_REPRESENTATION;
1337 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1339 type = PAYLOAD_TYPE_RD;
1342 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1344 type = PAYLOAD_TYPE_REPRESENTATION;
1349 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1350 cbNode->method, cbNode->requestUri);
1354 else if (cbNode->method == OC_REST_GET ||
1355 cbNode->method == OC_REST_PUT ||
1356 cbNode->method == OC_REST_POST ||
1357 cbNode->method == OC_REST_OBSERVE ||
1358 cbNode->method == OC_REST_OBSERVE_ALL ||
1359 cbNode->method == OC_REST_DELETE)
1361 if (cbNode->requestUri)
1363 char targetUri[MAX_URI_LENGTH];
1364 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1365 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1366 if (strcmp(targetUri, cbNode->requestUri) == 0)
1368 type = PAYLOAD_TYPE_RD;
1370 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1372 type = PAYLOAD_TYPE_PLATFORM;
1374 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1376 type = PAYLOAD_TYPE_DEVICE;
1378 if (type == PAYLOAD_TYPE_INVALID)
1380 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1381 cbNode->method, cbNode->requestUri);
1382 type = PAYLOAD_TYPE_REPRESENTATION;
1387 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1388 type = PAYLOAD_TYPE_REPRESENTATION;
1393 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1394 cbNode->method, cbNode->requestUri);
1398 if(OC_STACK_OK != OCParsePayload(&response.payload,
1400 responseInfo->info.payload,
1401 responseInfo->info.payloadSize))
1403 OIC_LOG(ERROR, TAG, "Error converting payload");
1404 OCPayloadDestroy(response.payload);
1409 response.numRcvdVendorSpecificHeaderOptions = 0;
1410 if(responseInfo->info.numOptions > 0)
1413 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1414 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1417 uint32_t observationOption;
1418 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1419 for (observationOption=0, i=0;
1420 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1424 (observationOption << 8) | optionData[i];
1426 response.sequenceNumber = observationOption;
1427 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1432 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1435 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1437 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1438 OCPayloadDestroy(response.payload);
1442 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1444 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1445 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1449 if (cbNode->method == OC_REST_OBSERVE &&
1450 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1451 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1452 response.sequenceNumber <= cbNode->sequenceNumber)
1454 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1455 response.sequenceNumber);
1459 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1462 cbNode->sequenceNumber = response.sequenceNumber;
1464 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1466 FindAndDeleteClientCB(cbNode);
1470 // To keep discovery callbacks active.
1471 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1472 MILLISECONDS_PER_SECOND);
1476 //Need to send ACK when the response is CON
1477 if(responseInfo->info.type == CA_MSG_CONFIRM)
1479 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1480 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1483 OCPayloadDestroy(response.payload);
1490 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1491 if(responseInfo->result == CA_EMPTY)
1493 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1494 if(responseInfo->info.type == CA_MSG_RESET)
1496 OIC_LOG(INFO, TAG, "This is a RESET");
1497 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1498 OC_OBSERVER_NOT_INTERESTED);
1500 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1502 OIC_LOG(INFO, TAG, "This is a pure ACK");
1503 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1504 OC_OBSERVER_STILL_INTERESTED);
1507 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1509 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1510 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1511 OC_OBSERVER_FAILED_COMM);
1516 if(!cbNode && !observer)
1518 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1519 || myStackMode == OC_GATEWAY)
1521 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1522 if(responseInfo->result == CA_EMPTY)
1524 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1528 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1529 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1530 CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1534 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1535 || myStackMode == OC_GATEWAY)
1537 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1538 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1540 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1541 responseInfo->info.messageId);
1543 if (responseInfo->info.type == CA_MSG_RESET)
1545 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1546 responseInfo->info.messageId);
1554 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1556 VERIFY_NON_NULL_NR(endPoint, FATAL);
1557 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1559 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1561 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1562 #ifdef ROUTING_GATEWAY
1563 bool needRIHandling = false;
1565 * Routing manager is going to update either of endpoint or response or both.
1566 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1567 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1570 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1572 if(ret != OC_STACK_OK || !needRIHandling)
1574 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1580 * Put source in sender endpoint so that the next packet from application can be routed to
1581 * proper destination and remove "RM" coap header option before passing request / response to
1582 * RI as this option will make no sense to either RI or application.
1584 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1585 (uint8_t *) &(responseInfo->info.numOptions),
1586 (CAEndpoint_t *) endPoint);
1589 OCHandleResponse(endPoint, responseInfo);
1591 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1595 * This function handles error response from CA
1596 * code shall be added to handle the errors
1598 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1600 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1602 if (NULL == endPoint)
1604 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1608 if (NULL == errorInfo)
1610 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1614 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1615 errorInfo->info.tokenLength, NULL, NULL);
1618 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1619 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1620 FixUpClientResponse(&response);
1621 response.resourceUri = errorInfo->info.resourceUri;
1622 memcpy(response.identity.id, errorInfo->info.identity.id,
1623 sizeof (response.identity.id));
1624 response.identity.id_length = errorInfo->info.identity.id_length;
1625 response.result = CAResultToOCStackResult(errorInfo->result);
1627 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1630 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1634 * This function sends out Direct Stack Responses. These are responses that are not coming
1635 * from the application entity handler. These responses have no payload and are usually ACKs,
1636 * RESETs or some error conditions that were caught by the stack.
1638 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1639 const CAResponseResult_t responseResult, const CAMessageType_t type,
1640 const uint8_t numOptions, const CAHeaderOption_t *options,
1641 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1642 CADataType_t dataType)
1644 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1645 CAResponseInfo_t respInfo = {
1646 .result = responseResult
1648 respInfo.info.messageId = coapID;
1649 respInfo.info.numOptions = numOptions;
1651 if (respInfo.info.numOptions)
1653 respInfo.info.options =
1654 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1655 memcpy (respInfo.info.options, options,
1656 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1660 respInfo.info.payload = NULL;
1661 respInfo.info.token = token;
1662 respInfo.info.tokenLength = tokenLength;
1663 respInfo.info.type = type;
1664 respInfo.info.resourceUri = OICStrdup (resourceUri);
1665 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1666 respInfo.info.dataType = dataType;
1668 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1669 // Add the destination to route option from the endpoint->routeData.
1670 bool doPost = false;
1671 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1672 if(OC_STACK_OK != result)
1674 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1679 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1680 CARequestInfo_t reqInfo = {.method = CA_POST };
1681 /* The following initialization is not done in a single initializer block as in
1682 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1683 * does not have designated initalizers. This is a work-around for now.
1685 reqInfo.info.type = CA_MSG_NONCONFIRM;
1686 reqInfo.info.messageId = coapID;
1687 reqInfo.info.tokenLength = tokenLength;
1688 reqInfo.info.token = token;
1689 reqInfo.info.numOptions = respInfo.info.numOptions;
1690 reqInfo.info.payload = NULL;
1691 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1692 if (reqInfo.info.numOptions)
1694 reqInfo.info.options =
1695 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1696 if (NULL == reqInfo.info.options)
1698 OIC_LOG(ERROR, TAG, "Calloc failed");
1699 return OC_STACK_NO_MEMORY;
1701 memcpy (reqInfo.info.options, respInfo.info.options,
1702 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1705 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1706 OICFree (reqInfo.info.resourceUri);
1707 OICFree (reqInfo.info.options);
1708 OICFree (respInfo.info.resourceUri);
1709 OICFree (respInfo.info.options);
1710 if (CA_STATUS_OK != caResult)
1712 OIC_LOG(ERROR, TAG, "CASendRequest error");
1713 return CAResultToOCResult(caResult);
1719 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1721 // resourceUri in the info field is cloned in the CA layer and
1722 // thus ownership is still here.
1723 OICFree (respInfo.info.resourceUri);
1724 OICFree (respInfo.info.options);
1725 if(CA_STATUS_OK != caResult)
1727 OIC_LOG(ERROR, TAG, "CASendResponse error");
1728 return CAResultToOCResult(caResult);
1731 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1735 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1737 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1738 OCStackResult result = OC_STACK_ERROR;
1739 if(!protocolRequest)
1741 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1742 return OC_STACK_INVALID_PARAM;
1745 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1746 protocolRequest->tokenLength);
1749 OIC_LOG(INFO, TAG, "This is a new Server Request");
1750 result = AddServerRequest(&request, protocolRequest->coapID,
1751 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1752 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1753 protocolRequest->observationOption, protocolRequest->qos,
1754 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1755 protocolRequest->payload, protocolRequest->requestToken,
1756 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1757 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1758 &protocolRequest->devAddr);
1759 if (OC_STACK_OK != result)
1761 OIC_LOG(ERROR, TAG, "Error adding server request");
1767 OIC_LOG(ERROR, TAG, "Out of Memory");
1768 return OC_STACK_NO_MEMORY;
1771 if(!protocolRequest->reqMorePacket)
1773 request->requestComplete = 1;
1778 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1781 if(request->requestComplete)
1783 OIC_LOG(INFO, TAG, "This Server Request is complete");
1784 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1785 OCResource *resource = NULL;
1786 result = DetermineResourceHandling (request, &resHandling, &resource);
1787 if (result == OC_STACK_OK)
1789 result = ProcessRequest(resHandling, resource, request);
1794 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1795 result = OC_STACK_CONTINUE;
1800 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1802 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1805 if (requestInfo->info.resourceUri &&
1806 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1808 HandleKeepAliveRequest(endPoint, requestInfo);
1813 OCStackResult requestResult = OC_STACK_ERROR;
1815 if(myStackMode == OC_CLIENT)
1817 //TODO: should the client be responding to requests?
1821 OCServerProtocolRequest serverRequest = {0};
1823 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1825 char * uriWithoutQuery = NULL;
1826 char * query = NULL;
1828 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1830 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1832 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1835 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1836 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1838 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1840 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1841 OICFree(uriWithoutQuery);
1845 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1846 OICFree(uriWithoutQuery);
1853 if(strlen(query) < MAX_QUERY_LENGTH)
1855 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1860 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1866 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1868 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1869 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1870 if (!serverRequest.payload)
1872 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1875 memcpy (serverRequest.payload, requestInfo->info.payload,
1876 requestInfo->info.payloadSize);
1880 serverRequest.reqTotalSize = 0;
1883 switch (requestInfo->method)
1886 serverRequest.method = OC_REST_GET;
1889 serverRequest.method = OC_REST_PUT;
1892 serverRequest.method = OC_REST_POST;
1895 serverRequest.method = OC_REST_DELETE;
1898 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1899 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1900 requestInfo->info.type, requestInfo->info.numOptions,
1901 requestInfo->info.options, requestInfo->info.token,
1902 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1904 OICFree(serverRequest.payload);
1908 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1909 requestInfo->info.tokenLength);
1911 serverRequest.tokenLength = requestInfo->info.tokenLength;
1912 if (serverRequest.tokenLength) {
1914 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1916 if (!serverRequest.requestToken)
1918 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1919 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1920 requestInfo->info.type, requestInfo->info.numOptions,
1921 requestInfo->info.options, requestInfo->info.token,
1922 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1924 OICFree(serverRequest.payload);
1927 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1930 switch (requestInfo->info.acceptFormat)
1932 case CA_FORMAT_APPLICATION_CBOR:
1933 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1935 case CA_FORMAT_UNDEFINED:
1936 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1939 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1942 if (requestInfo->info.type == CA_MSG_CONFIRM)
1944 serverRequest.qos = OC_HIGH_QOS;
1948 serverRequest.qos = OC_LOW_QOS;
1950 // CA does not need the following field
1951 // Are we sure CA does not need them? how is it responding to multicast
1952 serverRequest.delayedResNeeded = 0;
1954 serverRequest.coapID = requestInfo->info.messageId;
1956 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1958 // copy vendor specific header options
1959 uint8_t tempNum = (requestInfo->info.numOptions);
1961 // Assume no observation requested and it is a pure GET.
1962 // If obs registration/de-registration requested it'll be fetched from the
1963 // options in GetObserveHeaderOption()
1964 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1966 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1967 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1970 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1971 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1972 requestInfo->info.type, requestInfo->info.numOptions,
1973 requestInfo->info.options, requestInfo->info.token,
1974 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1976 OICFree(serverRequest.payload);
1977 OICFree(serverRequest.requestToken);
1980 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1981 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1983 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1984 sizeof(CAHeaderOption_t)*tempNum);
1987 requestResult = HandleStackRequests (&serverRequest);
1989 // Send ACK to client as precursor to slow response
1990 if (requestResult == OC_STACK_SLOW_RESOURCE)
1992 if (requestInfo->info.type == CA_MSG_CONFIRM)
1994 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1995 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
1999 if (requestResult == OC_STACK_RESOURCE_ERROR
2000 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2002 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2004 else if(!OCResultToSuccess(requestResult))
2006 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2008 CAResponseResult_t stackResponse =
2009 OCToCAStackResult(requestResult, serverRequest.method);
2011 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2012 requestInfo->info.type, requestInfo->info.numOptions,
2013 requestInfo->info.options, requestInfo->info.token,
2014 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2017 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2018 // The token is copied in there, and is thus still owned by this function.
2019 OICFree(serverRequest.payload);
2020 OICFree(serverRequest.requestToken);
2021 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2024 //This function will be called back by CA layer when a request is received
2025 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2027 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2030 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2036 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2040 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2041 #ifdef ROUTING_GATEWAY
2042 bool needRIHandling = false;
2043 bool isEmptyMsg = false;
2045 * Routing manager is going to update either of endpoint or request or both.
2046 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2047 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2048 * destination. It can also remove "RM" coap header option before passing request / response to
2049 * RI as this option will make no sense to either RI or application.
2051 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2052 &needRIHandling, &isEmptyMsg);
2053 if(OC_STACK_OK != ret || !needRIHandling)
2055 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2061 * Put source in sender endpoint so that the next packet from application can be routed to
2062 * proper destination and remove RM header option.
2064 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2065 (uint8_t *) &(requestInfo->info.numOptions),
2066 (CAEndpoint_t *) endPoint);
2068 #ifdef ROUTING_GATEWAY
2072 * In Gateways, the MSGType in route option is used to check if the actual
2073 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2074 * EMPTY response is sent in the form of POST request which need to be changed
2075 * to a EMPTY response by RM. This translation is done in this part of the code.
2077 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2078 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2079 .info.messageId = requestInfo->info.messageId,
2080 .info.type = CA_MSG_ACKNOWLEDGE};
2081 OCHandleResponse(endPoint, &respInfo);
2087 // Normal handling of the packet
2088 OCHandleRequests(endPoint, requestInfo);
2090 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2093 bool validatePlatformInfo(OCPlatformInfo info)
2096 if (!info.platformID)
2098 OIC_LOG(ERROR, TAG, "No platform ID found.");
2102 if (info.manufacturerName)
2104 size_t lenManufacturerName = strlen(info.manufacturerName);
2106 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2108 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2114 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2118 if (info.manufacturerUrl)
2120 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2122 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2129 //-----------------------------------------------------------------------------
2131 //-----------------------------------------------------------------------------
2133 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2136 !raInfo->username ||
2137 !raInfo->hostname ||
2138 !raInfo->xmpp_domain)
2141 return OC_STACK_INVALID_PARAM;
2143 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2144 gRASetInfo = (result == OC_STACK_OK)? true : false;
2150 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2154 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2157 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2159 if(stackState == OC_STACK_INITIALIZED)
2161 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2162 OCStop() between them are ignored.");
2166 #ifndef ROUTING_GATEWAY
2167 if (OC_GATEWAY == mode)
2169 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2170 return OC_STACK_INVALID_PARAM;
2177 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2178 return OC_STACK_ERROR;
2182 OCStackResult result = OC_STACK_ERROR;
2183 OIC_LOG(INFO, TAG, "Entering OCInit");
2186 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2187 || (mode == OC_GATEWAY)))
2189 OIC_LOG(ERROR, TAG, "Invalid mode");
2190 return OC_STACK_ERROR;
2194 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2196 caglobals.client = true;
2198 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2200 caglobals.server = true;
2203 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2204 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2206 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2208 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2209 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2211 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2214 defaultDeviceHandler = NULL;
2215 defaultDeviceHandlerCallbackParameter = NULL;
2217 result = CAResultToOCResult(CAInitialize());
2218 VERIFY_SUCCESS(result, OC_STACK_OK);
2220 result = CAResultToOCResult(OCSelectNetwork());
2221 VERIFY_SUCCESS(result, OC_STACK_OK);
2223 switch (myStackMode)
2226 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2227 result = CAResultToOCResult(CAStartDiscoveryServer());
2228 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2231 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2232 result = CAResultToOCResult(CAStartListeningServer());
2233 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2235 case OC_CLIENT_SERVER:
2237 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2238 result = CAResultToOCResult(CAStartListeningServer());
2239 if(result == OC_STACK_OK)
2241 result = CAResultToOCResult(CAStartDiscoveryServer());
2245 VERIFY_SUCCESS(result, OC_STACK_OK);
2248 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2251 #ifdef WITH_PRESENCE
2252 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2253 #endif // WITH_PRESENCE
2255 //Update Stack state to initialized
2256 stackState = OC_STACK_INITIALIZED;
2258 // Initialize resource
2259 if(myStackMode != OC_CLIENT)
2261 result = initResources();
2264 // Initialize the SRM Policy Engine
2265 if(result == OC_STACK_OK)
2267 result = SRMInitPolicyEngine();
2268 // TODO after BeachHead delivery: consolidate into single SRMInit()
2270 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2271 RMSetStackMode(mode);
2272 #ifdef ROUTING_GATEWAY
2273 if (OC_GATEWAY == myStackMode)
2275 result = RMInitialize();
2281 if (result == OC_STACK_OK)
2283 result = InitializeKeepAlive(myStackMode);
2288 if(result != OC_STACK_OK)
2290 OIC_LOG(ERROR, TAG, "Stack initialization error");
2291 deleteAllResources();
2293 stackState = OC_STACK_UNINITIALIZED;
2298 OCStackResult OCStop()
2300 OIC_LOG(INFO, TAG, "Entering OCStop");
2302 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2304 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2307 else if (stackState != OC_STACK_INITIALIZED)
2309 OIC_LOG(ERROR, TAG, "Stack not initialized");
2310 return OC_STACK_ERROR;
2313 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2315 #ifdef WITH_PRESENCE
2316 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2317 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2318 presenceResource.presenceTTL = 0;
2319 #endif // WITH_PRESENCE
2321 #ifdef ROUTING_GATEWAY
2322 if (OC_GATEWAY == myStackMode)
2329 TerminateKeepAlive(myStackMode);
2332 // Free memory dynamically allocated for resources
2333 deleteAllResources();
2335 DeletePlatformInfo();
2337 // Remove all observers
2338 DeleteObserverList();
2339 // Remove all the client callbacks
2340 DeleteClientCBList();
2342 // De-init the SRM Policy Engine
2343 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2344 SRMDeInitPolicyEngine();
2347 stackState = OC_STACK_UNINITIALIZED;
2351 OCStackResult OCStartMulticastServer()
2353 if(stackState != OC_STACK_INITIALIZED)
2355 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2356 return OC_STACK_ERROR;
2358 CAResult_t ret = CAStartListeningServer();
2359 if (CA_STATUS_OK != ret)
2361 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2362 return OC_STACK_ERROR;
2367 OCStackResult OCStopMulticastServer()
2369 CAResult_t ret = CAStopListeningServer();
2370 if (CA_STATUS_OK != ret)
2372 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2373 return OC_STACK_ERROR;
2378 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2383 return CA_MSG_CONFIRM;
2388 return CA_MSG_NONCONFIRM;
2393 * A request uri consists of the following components in order:
2396 * CoAP over UDP prefix "coap://"
2397 * CoAP over TCP prefix "coap+tcp://"
2398 * CoAP over DTLS prefix "coaps://"
2399 * CoAP over TLS prefix "coaps+tcp://"
2401 * IPv6 address "[1234::5678]"
2402 * IPv4 address "192.168.1.1"
2403 * optional port ":5683"
2404 * resource uri "/oc/core..."
2406 * for PRESENCE requests, extract resource type.
2408 static OCStackResult ParseRequestUri(const char *fullUri,
2409 OCTransportAdapter adapter,
2410 OCTransportFlags flags,
2411 OCDevAddr **devAddr,
2413 char **resourceType)
2415 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2417 OCStackResult result = OC_STACK_OK;
2418 OCDevAddr *da = NULL;
2422 // provide defaults for all returned values
2429 *resourceUri = NULL;
2433 *resourceType = NULL;
2436 // delimit url prefix, if any
2437 const char *start = fullUri;
2438 char *slash2 = strstr(start, "//");
2443 char *slash = strchr(start, '/');
2446 return OC_STACK_INVALID_URI;
2449 // process url scheme
2450 size_t prefixLen = slash2 - fullUri;
2454 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2455 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2461 // TODO: this logic should come in with unit tests exercising the various strings
2462 // processs url prefix, if any
2463 size_t urlLen = slash - start;
2467 if (urlLen && devAddr)
2468 { // construct OCDevAddr
2469 if (start[0] == '[')
2471 char *close = strchr(++start, ']');
2472 if (!close || close > slash)
2474 return OC_STACK_INVALID_URI;
2477 if (close[1] == ':')
2484 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2488 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2490 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2494 char *dot = strchr(start, '.');
2495 if (dot && dot < slash)
2497 colon = strchr(start, ':');
2498 end = (colon && colon < slash) ? colon : slash;
2503 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2507 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2509 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2517 if (len >= sizeof(da->addr))
2519 return OC_STACK_INVALID_URI;
2521 // collect port, if any
2522 if (colon && colon < slash)
2524 for (colon++; colon < slash; colon++)
2527 if (c < '0' || c > '9')
2529 return OC_STACK_INVALID_URI;
2531 port = 10 * port + c - '0';
2536 if (len >= sizeof(da->addr))
2538 return OC_STACK_INVALID_URI;
2541 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2544 return OC_STACK_NO_MEMORY;
2546 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2548 da->adapter = adapter;
2550 if (!strncmp(fullUri, "coaps", 5))
2552 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2557 // process resource uri, if any
2559 { // request uri and query
2560 size_t ulen = strlen(slash); // resource uri length
2561 size_t tlen = 0; // resource type length
2564 static const char strPresence[] = "/oic/ad?rt=";
2565 static const size_t lenPresence = sizeof(strPresence) - 1;
2566 if (!strncmp(slash, strPresence, lenPresence))
2568 type = slash + lenPresence;
2569 tlen = ulen - lenPresence;
2574 *resourceUri = (char *)OICMalloc(ulen + 1);
2577 result = OC_STACK_NO_MEMORY;
2580 strcpy(*resourceUri, slash);
2583 if (type && resourceType)
2585 *resourceType = (char *)OICMalloc(tlen + 1);
2588 result = OC_STACK_NO_MEMORY;
2592 OICStrcpy(*resourceType, (tlen+1), type);
2599 // free all returned values
2606 OICFree(*resourceUri);
2610 OICFree(*resourceType);
2615 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2620 char uri[CA_MAX_URI_LENGTH];
2622 FormCanonicalPresenceUri(endpoint, resourceUri, uri, isMulticast);
2624 *requestUri = OICStrdup(uri);
2627 return OC_STACK_NO_MEMORY;
2634 * Discover or Perform requests on a specified resource
2636 OCStackResult OCDoResource(OCDoHandle *handle,
2638 const char *requestUri,
2639 const OCDevAddr *destination,
2641 OCConnectivityType connectivityType,
2642 OCQualityOfService qos,
2643 OCCallbackData *cbData,
2644 OCHeaderOption *options,
2647 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2649 // Validate input parameters
2650 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2651 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2653 OCStackResult result = OC_STACK_ERROR;
2654 CAResult_t caResult;
2655 CAToken_t token = NULL;
2656 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2657 ClientCB *clientCB = NULL;
2658 OCDoHandle resHandle = NULL;
2659 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2660 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2662 OCTransportAdapter adapter;
2663 OCTransportFlags flags;
2664 // the request contents are put here
2665 CARequestInfo_t requestInfo = {.method = CA_GET};
2666 // requestUri will be parsed into the following three variables
2667 OCDevAddr *devAddr = NULL;
2668 char *resourceUri = NULL;
2669 char *resourceType = NULL;
2672 * Support original behavior with address on resourceUri argument.
2674 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2675 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2679 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2680 if (result != OC_STACK_OK)
2682 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2686 else if (!checkProxyUri(options, numOptions))
2688 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2695 case OC_REST_OBSERVE:
2696 case OC_REST_OBSERVE_ALL:
2697 case OC_REST_CANCEL_OBSERVE:
2698 requestInfo.method = CA_GET;
2701 requestInfo.method = CA_PUT;
2704 requestInfo.method = CA_POST;
2706 case OC_REST_DELETE:
2707 requestInfo.method = CA_DELETE;
2709 case OC_REST_DISCOVER:
2711 #ifdef WITH_PRESENCE
2712 case OC_REST_PRESENCE:
2714 if (destination || devAddr)
2716 requestInfo.isMulticast = false;
2720 tmpDevAddr.adapter = adapter;
2721 tmpDevAddr.flags = flags;
2722 destination = &tmpDevAddr;
2723 requestInfo.isMulticast = true;
2725 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
2726 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
2727 // replacing method type with GET.
2728 requestInfo.method = CA_GET;
2731 result = OC_STACK_INVALID_METHOD;
2735 if (!devAddr && !destination)
2737 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2738 result = OC_STACK_INVALID_PARAM;
2742 /* If not original behavior, use destination argument */
2743 if (destination && !devAddr)
2745 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2748 result = OC_STACK_NO_MEMORY;
2751 *devAddr = *destination;
2754 resHandle = GenerateInvocationHandle();
2757 result = OC_STACK_NO_MEMORY;
2761 caResult = CAGenerateToken(&token, tokenLength);
2762 if (caResult != CA_STATUS_OK)
2764 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2765 result= OC_STACK_ERROR;
2769 // fill in request data
2770 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2771 requestInfo.info.token = token;
2772 requestInfo.info.tokenLength = tokenLength;
2773 requestInfo.info.resourceUri = resourceUri;
2775 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2777 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2778 options, numOptions, OC_OBSERVE_REGISTER);
2779 if (result != OC_STACK_OK)
2783 requestInfo.info.numOptions = numOptions + 1;
2787 requestInfo.info.numOptions = numOptions;
2788 requestInfo.info.options =
2789 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2790 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2791 numOptions * sizeof(CAHeaderOption_t));
2794 CopyDevAddrToEndpoint(devAddr, &endpoint);
2799 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2802 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2805 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2809 requestInfo.info.payload = NULL;
2810 requestInfo.info.payloadSize = 0;
2811 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2814 // prepare for response
2815 #ifdef WITH_PRESENCE
2816 if (method == OC_REST_PRESENCE)
2818 char *presenceUri = NULL;
2819 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri,
2820 requestInfo.isMulticast);
2821 if (OC_STACK_OK != result)
2826 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2827 // Presence notification will form a canonical uri to
2828 // look for callbacks into the application.
2829 resourceUri = presenceUri;
2833 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2834 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2835 method, devAddr, resourceUri, resourceType, ttl);
2836 if (OC_STACK_OK != result)
2841 devAddr = NULL; // Client CB list entry now owns it
2842 resourceUri = NULL; // Client CB list entry now owns it
2843 resourceType = NULL; // Client CB list entry now owns it
2846 result = OCSendRequest(&endpoint, &requestInfo);
2847 if (OC_STACK_OK != result)
2854 *handle = resHandle;
2858 if (result != OC_STACK_OK)
2860 OIC_LOG(ERROR, TAG, "OCDoResource error");
2861 FindAndDeleteClientCB(clientCB);
2862 CADestroyToken(token);
2870 // This is the owner of the payload object, so we free it
2871 OCPayloadDestroy(payload);
2872 OICFree(requestInfo.info.payload);
2874 OICFree(resourceUri);
2875 OICFree(resourceType);
2876 OICFree(requestInfo.info.options);
2880 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2884 * This ftn is implemented one of two ways in the case of observation:
2886 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2887 * Remove the callback associated on client side.
2888 * When the next notification comes in from server,
2889 * reply with RESET message to server.
2890 * Keep in mind that the server will react to RESET only
2891 * if the last notification was sent as CON
2893 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2894 * and it is associated with an observe request
2895 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2896 * Send CON Observe request to server with
2897 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2898 * Remove the callback associated on client side.
2900 OCStackResult ret = OC_STACK_OK;
2901 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2902 CARequestInfo_t requestInfo = {.method = CA_GET};
2906 return OC_STACK_INVALID_PARAM;
2909 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2912 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2913 return OC_STACK_ERROR;
2916 switch (clientCB->method)
2918 case OC_REST_OBSERVE:
2919 case OC_REST_OBSERVE_ALL:
2921 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2923 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2925 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2927 FindAndDeleteClientCB(clientCB);
2931 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2933 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2934 requestInfo.info.token = clientCB->token;
2935 requestInfo.info.tokenLength = clientCB->tokenLength;
2937 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2938 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2940 return OC_STACK_ERROR;
2942 requestInfo.info.numOptions = numOptions + 1;
2943 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2946 ret = OCSendRequest(&endpoint, &requestInfo);
2948 if (requestInfo.info.options)
2950 OICFree (requestInfo.info.options);
2952 if (requestInfo.info.resourceUri)
2954 OICFree (requestInfo.info.resourceUri);
2959 case OC_REST_DISCOVER:
2960 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2961 clientCB->requestUri);
2962 FindAndDeleteClientCB(clientCB);
2965 #ifdef WITH_PRESENCE
2966 case OC_REST_PRESENCE:
2967 FindAndDeleteClientCB(clientCB);
2972 ret = OC_STACK_INVALID_METHOD;
2980 * @brief Register Persistent storage callback.
2981 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2983 * OC_STACK_OK - No errors; Success
2984 * OC_STACK_INVALID_PARAM - Invalid parameter
2986 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2988 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2989 if(!persistentStorageHandler)
2991 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2992 return OC_STACK_INVALID_PARAM;
2996 if( !persistentStorageHandler->open ||
2997 !persistentStorageHandler->close ||
2998 !persistentStorageHandler->read ||
2999 !persistentStorageHandler->unlink ||
3000 !persistentStorageHandler->write)
3002 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3003 return OC_STACK_INVALID_PARAM;
3006 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3009 #ifdef WITH_PRESENCE
3011 OCStackResult OCProcessPresence()
3013 OCStackResult result = OC_STACK_OK;
3015 // the following line floods the log with messages that are irrelevant
3016 // to most purposes. Uncomment as needed.
3017 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3018 ClientCB* cbNode = NULL;
3019 OCClientResponse clientResponse;
3020 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3022 LL_FOREACH(cbList, cbNode)
3024 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3029 uint32_t now = GetTicks(0);
3030 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3031 cbNode->presence->TTLlevel);
3032 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3034 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3039 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3041 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3042 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3044 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3046 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3048 clientResponse.sequenceNumber = 0;
3049 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3050 clientResponse.devAddr = *cbNode->devAddr;
3051 FixUpClientResponse(&clientResponse);
3052 clientResponse.payload = NULL;
3054 // Increment the TTLLevel (going to a next state), so we don't keep
3055 // sending presence notification to client.
3056 cbNode->presence->TTLlevel++;
3057 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3058 cbNode->presence->TTLlevel);
3060 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3061 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3063 FindAndDeleteClientCB(cbNode);
3067 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3072 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3073 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3074 CARequestInfo_t requestInfo = {.method = CA_GET};
3076 OIC_LOG(DEBUG, TAG, "time to test server presence");
3078 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3080 requestData.type = CA_MSG_NONCONFIRM;
3081 requestData.token = cbNode->token;
3082 requestData.tokenLength = cbNode->tokenLength;
3083 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3084 requestInfo.method = CA_GET;
3085 requestInfo.info = requestData;
3087 result = OCSendRequest(&endpoint, &requestInfo);
3088 if (OC_STACK_OK != result)
3093 cbNode->presence->TTLlevel++;
3094 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3097 if (result != OC_STACK_OK)
3099 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3104 #endif // WITH_PRESENCE
3106 OCStackResult OCProcess()
3108 #ifdef WITH_PRESENCE
3109 OCProcessPresence();
3111 CAHandleRequestResponse();
3113 #ifdef ROUTING_GATEWAY
3123 #ifdef WITH_PRESENCE
3124 OCStackResult OCStartPresence(const uint32_t ttl)
3126 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3127 OCChangeResourceProperty(
3128 &(((OCResource *)presenceResource.handle)->resourceProperties),
3131 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3133 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3134 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3138 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3139 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3143 presenceResource.presenceTTL = ttl;
3145 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3147 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3149 presenceState = OC_PRESENCE_INITIALIZED;
3151 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3153 CAToken_t caToken = NULL;
3154 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3155 if (caResult != CA_STATUS_OK)
3157 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3158 CADestroyToken(caToken);
3159 return OC_STACK_ERROR;
3162 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3163 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3164 CADestroyToken(caToken);
3167 // Each time OCStartPresence is called
3168 // a different random 32-bit integer number is used
3169 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3171 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3172 OC_PRESENCE_TRIGGER_CREATE);
3175 OCStackResult OCStopPresence()
3177 OCStackResult result = OC_STACK_ERROR;
3179 if(presenceResource.handle)
3181 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3183 // make resource inactive
3184 result = OCChangeResourceProperty(
3185 &(((OCResource *) presenceResource.handle)->resourceProperties),
3189 if(result != OC_STACK_OK)
3192 "Changing the presence resource properties to ACTIVE not successful");
3196 return SendStopNotification();
3200 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3201 void* callbackParameter)
3203 defaultDeviceHandler = entityHandler;
3204 defaultDeviceHandlerCallbackParameter = callbackParameter;
3209 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3211 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3213 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3215 if (validatePlatformInfo(platformInfo))
3217 return SavePlatformInfo(platformInfo);
3221 return OC_STACK_INVALID_PARAM;
3226 return OC_STACK_ERROR;
3230 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3232 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3234 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3236 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3237 return OC_STACK_INVALID_PARAM;
3240 if (deviceInfo.types)
3242 OCStringLL *type = deviceInfo.types;
3243 OCResource *resource = findResource((OCResource *) deviceResource);
3246 return OC_STACK_INVALID_PARAM;
3251 OCBindResourceTypeToResource(deviceResource, type->value);
3255 return SaveDeviceInfo(deviceInfo);
3258 OCStackResult OCCreateResource(OCResourceHandle *handle,
3259 const char *resourceTypeName,
3260 const char *resourceInterfaceName,
3261 const char *uri, OCEntityHandler entityHandler,
3262 void* callbackParam,
3263 uint8_t resourceProperties)
3266 OCResource *pointer = NULL;
3267 OCStackResult result = OC_STACK_ERROR;
3269 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3271 if(myStackMode == OC_CLIENT)
3273 return OC_STACK_INVALID_PARAM;
3275 // Validate parameters
3276 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3278 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3279 return OC_STACK_INVALID_URI;
3281 // Is it presented during resource discovery?
3282 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3284 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3285 return OC_STACK_INVALID_PARAM;
3288 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3290 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3294 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3296 // Make sure resourceProperties bitmask has allowed properties specified
3297 if (resourceProperties
3298 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3299 OC_EXPLICIT_DISCOVERABLE
3308 OIC_LOG(ERROR, TAG, "Invalid property");
3309 return OC_STACK_INVALID_PARAM;
3312 // If the headResource is NULL, then no resources have been created...
3313 pointer = headResource;
3316 // At least one resources is in the resource list, so we need to search for
3317 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3320 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3322 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3323 return OC_STACK_INVALID_PARAM;
3325 pointer = pointer->next;
3328 // Create the pointer and insert it into the resource list
3329 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3332 result = OC_STACK_NO_MEMORY;
3335 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3337 insertResource(pointer);
3340 pointer->uri = OICStrdup(uri);
3343 result = OC_STACK_NO_MEMORY;
3347 // Set properties. Set OC_ACTIVE
3348 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3351 // Add the resourcetype to the resource
3352 result = BindResourceTypeToResource(pointer, resourceTypeName);
3353 if (result != OC_STACK_OK)
3355 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3359 // Add the resourceinterface to the resource
3360 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3361 if (result != OC_STACK_OK)
3363 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3367 // If an entity handler has been passed, attach it to the newly created
3368 // resource. Otherwise, set the default entity handler.
3371 pointer->entityHandler = entityHandler;
3372 pointer->entityHandlerCallbackParam = callbackParam;
3376 pointer->entityHandler = defaultResourceEHandler;
3377 pointer->entityHandlerCallbackParam = NULL;
3380 // Initialize a pointer indicating child resources in case of collection
3381 pointer->rsrcChildResourcesHead = NULL;
3384 result = OC_STACK_OK;
3386 #ifdef WITH_PRESENCE
3387 if (presenceResource.handle)
3389 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3390 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3394 if (result != OC_STACK_OK)
3396 // Deep delete of resource and other dynamic elements that it contains
3397 deleteResource(pointer);
3402 OCStackResult OCBindResource(
3403 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3405 OCResource *resource = NULL;
3406 OCChildResource *tempChildResource = NULL;
3407 OCChildResource *newChildResource = NULL;
3409 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3411 // Validate parameters
3412 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3413 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3414 // Container cannot contain itself
3415 if (collectionHandle == resourceHandle)
3417 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3418 return OC_STACK_INVALID_PARAM;
3421 // Use the handle to find the resource in the resource linked list
3422 resource = findResource((OCResource *) collectionHandle);
3425 OIC_LOG(ERROR, TAG, "Collection handle not found");
3426 return OC_STACK_INVALID_PARAM;
3429 // Look for an open slot to add add the child resource.
3430 // If found, add it and return success
3432 tempChildResource = resource->rsrcChildResourcesHead;
3434 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3436 // TODO: what if one of child resource was deregistered without unbinding?
3437 tempChildResource = tempChildResource->next;
3440 // Do memory allocation for child resource
3441 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3442 if(!newChildResource)
3444 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3445 return OC_STACK_ERROR;
3448 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3449 newChildResource->next = NULL;
3451 if(!resource->rsrcChildResourcesHead)
3453 resource->rsrcChildResourcesHead = newChildResource;
3456 tempChildResource->next = newChildResource;
3459 OIC_LOG(INFO, TAG, "resource bound");
3461 #ifdef WITH_PRESENCE
3462 if (presenceResource.handle)
3464 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3465 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3466 OC_PRESENCE_TRIGGER_CHANGE);
3473 OCStackResult OCUnBindResource(
3474 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3476 OCResource *resource = NULL;
3477 OCChildResource *tempChildResource = NULL;
3478 OCChildResource *tempLastChildResource = NULL;
3480 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3482 // Validate parameters
3483 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3484 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3485 // Container cannot contain itself
3486 if (collectionHandle == resourceHandle)
3488 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3489 return OC_STACK_INVALID_PARAM;
3492 // Use the handle to find the resource in the resource linked list
3493 resource = findResource((OCResource *) collectionHandle);
3496 OIC_LOG(ERROR, TAG, "Collection handle not found");
3497 return OC_STACK_INVALID_PARAM;
3500 // Look for an open slot to add add the child resource.
3501 // If found, add it and return success
3502 if(!resource->rsrcChildResourcesHead)
3504 OIC_LOG(INFO, TAG, "resource not found in collection");
3506 // Unable to add resourceHandle, so return error
3507 return OC_STACK_ERROR;
3511 tempChildResource = resource->rsrcChildResourcesHead;
3513 while (tempChildResource)
3515 if(tempChildResource->rsrcResource == resourceHandle)
3517 // if resource going to be unbinded is the head one.
3518 if( tempChildResource == resource->rsrcChildResourcesHead )
3520 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3521 OICFree(resource->rsrcChildResourcesHead);
3522 resource->rsrcChildResourcesHead = temp;
3527 OCChildResource *temp = tempChildResource->next;
3528 OICFree(tempChildResource);
3529 tempLastChildResource->next = temp;
3533 OIC_LOG(INFO, TAG, "resource unbound");
3535 // Send notification when resource is unbounded successfully.
3536 #ifdef WITH_PRESENCE
3537 if (presenceResource.handle)
3539 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3540 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3541 OC_PRESENCE_TRIGGER_CHANGE);
3544 tempChildResource = NULL;
3545 tempLastChildResource = NULL;
3551 tempLastChildResource = tempChildResource;
3552 tempChildResource = tempChildResource->next;
3555 OIC_LOG(INFO, TAG, "resource not found in collection");
3557 tempChildResource = NULL;
3558 tempLastChildResource = NULL;
3560 // Unable to add resourceHandle, so return error
3561 return OC_STACK_ERROR;
3564 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3566 if (!resourceItemName)
3570 // Per RFC 6690 only registered values must follow the first rule below.
3571 // At this point in time the only values registered begin with "core", and
3572 // all other values are specified as opaque strings where multiple values
3573 // are separated by a space.
3574 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3576 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3578 if (resourceItemName[index] != '.'
3579 && resourceItemName[index] != '-'
3580 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3581 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3589 for (size_t index = 0; resourceItemName[index]; ++index)
3591 if (resourceItemName[index] == ' '
3592 || resourceItemName[index] == '\t'
3593 || resourceItemName[index] == '\r'
3594 || resourceItemName[index] == '\n')
3604 OCStackResult BindResourceTypeToResource(OCResource* resource,
3605 const char *resourceTypeName)
3607 OCResourceType *pointer = NULL;
3609 OCStackResult result = OC_STACK_ERROR;
3611 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3613 if (!ValidateResourceTypeInterface(resourceTypeName))
3615 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3616 return OC_STACK_INVALID_PARAM;
3619 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3622 result = OC_STACK_NO_MEMORY;
3626 str = OICStrdup(resourceTypeName);
3629 result = OC_STACK_NO_MEMORY;
3632 pointer->resourcetypename = str;
3633 pointer->next = NULL;
3635 insertResourceType(resource, pointer);
3636 result = OC_STACK_OK;
3639 if (result != OC_STACK_OK)
3648 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3649 const char *resourceInterfaceName)
3651 OCResourceInterface *pointer = NULL;
3653 OCStackResult result = OC_STACK_ERROR;
3655 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3657 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3659 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3660 return OC_STACK_INVALID_PARAM;
3663 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3665 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3668 result = OC_STACK_NO_MEMORY;
3672 str = OICStrdup(resourceInterfaceName);
3675 result = OC_STACK_NO_MEMORY;
3678 pointer->name = str;
3680 // Bind the resourceinterface to the resource
3681 insertResourceInterface(resource, pointer);
3683 result = OC_STACK_OK;
3686 if (result != OC_STACK_OK)
3695 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3696 const char *resourceTypeName)
3699 OCStackResult result = OC_STACK_ERROR;
3700 OCResource *resource = NULL;
3702 resource = findResource((OCResource *) handle);
3705 OIC_LOG(ERROR, TAG, "Resource not found");
3706 return OC_STACK_ERROR;
3709 result = BindResourceTypeToResource(resource, resourceTypeName);
3711 #ifdef WITH_PRESENCE
3712 if(presenceResource.handle)
3714 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3715 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3722 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3723 const char *resourceInterfaceName)
3726 OCStackResult result = OC_STACK_ERROR;
3727 OCResource *resource = NULL;
3729 resource = findResource((OCResource *) handle);
3732 OIC_LOG(ERROR, TAG, "Resource not found");
3733 return OC_STACK_ERROR;
3736 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3738 #ifdef WITH_PRESENCE
3739 if (presenceResource.handle)
3741 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3742 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3749 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3751 OCResource *pointer = headResource;
3753 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3757 *numResources = *numResources + 1;
3758 pointer = pointer->next;
3763 OCResourceHandle OCGetResourceHandle(uint8_t index)
3765 OCResource *pointer = headResource;
3767 for( uint8_t i = 0; i < index && pointer; ++i)
3769 pointer = pointer->next;
3771 return (OCResourceHandle) pointer;
3774 OCStackResult OCDeleteResource(OCResourceHandle handle)
3778 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3779 return OC_STACK_INVALID_PARAM;
3782 OCResource *resource = findResource((OCResource *) handle);
3783 if (resource == NULL)
3785 OIC_LOG(ERROR, TAG, "Resource not found");
3786 return OC_STACK_NO_RESOURCE;
3789 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3791 OIC_LOG(ERROR, TAG, "Error deleting resource");
3792 return OC_STACK_ERROR;
3798 const char *OCGetResourceUri(OCResourceHandle handle)
3800 OCResource *resource = NULL;
3802 resource = findResource((OCResource *) handle);
3805 return resource->uri;
3807 return (const char *) NULL;
3810 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3812 OCResource *resource = NULL;
3814 resource = findResource((OCResource *) handle);
3817 return resource->resourceProperties;
3819 return (OCResourceProperty)-1;
3822 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3823 uint8_t *numResourceTypes)
3825 OCResource *resource = NULL;
3826 OCResourceType *pointer = NULL;
3828 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3829 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3831 *numResourceTypes = 0;
3833 resource = findResource((OCResource *) handle);
3836 pointer = resource->rsrcType;
3839 *numResourceTypes = *numResourceTypes + 1;
3840 pointer = pointer->next;
3846 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3848 OCResourceType *resourceType = NULL;
3850 resourceType = findResourceTypeAtIndex(handle, index);
3853 return resourceType->resourcetypename;
3855 return (const char *) NULL;
3858 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3859 uint8_t *numResourceInterfaces)
3861 OCResourceInterface *pointer = NULL;
3862 OCResource *resource = NULL;
3864 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3865 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3867 *numResourceInterfaces = 0;
3868 resource = findResource((OCResource *) handle);
3871 pointer = resource->rsrcInterface;
3874 *numResourceInterfaces = *numResourceInterfaces + 1;
3875 pointer = pointer->next;
3881 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3883 OCResourceInterface *resourceInterface = NULL;
3885 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3886 if (resourceInterface)
3888 return resourceInterface->name;
3890 return (const char *) NULL;
3893 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3896 OCResource *resource = NULL;
3897 OCChildResource *tempChildResource = NULL;
3900 resource = findResource((OCResource *) collectionHandle);
3906 tempChildResource = resource->rsrcChildResourcesHead;
3908 while(tempChildResource)
3912 return tempChildResource->rsrcResource;
3915 tempChildResource = tempChildResource->next;
3918 // In this case, the number of resource handles in the collection exceeds the index
3919 tempChildResource = NULL;
3923 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3924 OCEntityHandler entityHandler,
3925 void* callbackParam)
3927 OCResource *resource = NULL;
3929 // Validate parameters
3930 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3932 // Use the handle to find the resource in the resource linked list
3933 resource = findResource((OCResource *)handle);
3936 OIC_LOG(ERROR, TAG, "Resource not found");
3937 return OC_STACK_ERROR;
3941 resource->entityHandler = entityHandler;
3942 resource->entityHandlerCallbackParam = callbackParam;
3944 #ifdef WITH_PRESENCE
3945 if (presenceResource.handle)
3947 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3948 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3955 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3957 OCResource *resource = NULL;
3959 resource = findResource((OCResource *)handle);
3962 OIC_LOG(ERROR, TAG, "Resource not found");
3967 return resource->entityHandler;
3970 void incrementSequenceNumber(OCResource * resPtr)
3972 // Increment the sequence number
3973 resPtr->sequenceNum += 1;
3974 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3976 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3981 #ifdef WITH_PRESENCE
3982 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3983 OCPresenceTrigger trigger)
3985 OCResource *resPtr = NULL;
3986 OCStackResult result = OC_STACK_ERROR;
3987 OCMethod method = OC_REST_PRESENCE;
3988 uint32_t maxAge = 0;
3989 resPtr = findResource((OCResource *) presenceResource.handle);
3992 return OC_STACK_NO_RESOURCE;
3995 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3997 maxAge = presenceResource.presenceTTL;
3999 result = SendAllObserverNotification(method, resPtr, maxAge,
4000 trigger, resourceType, OC_LOW_QOS);
4006 OCStackResult SendStopNotification()
4008 OCResource *resPtr = NULL;
4009 OCStackResult result = OC_STACK_ERROR;
4010 OCMethod method = OC_REST_PRESENCE;
4011 resPtr = findResource((OCResource *) presenceResource.handle);
4014 return OC_STACK_NO_RESOURCE;
4017 // maxAge is 0. ResourceType is NULL.
4018 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4024 #endif // WITH_PRESENCE
4025 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4027 OCResource *resPtr = NULL;
4028 OCStackResult result = OC_STACK_ERROR;
4029 OCMethod method = OC_REST_NOMETHOD;
4030 uint32_t maxAge = 0;
4032 OIC_LOG(INFO, TAG, "Notifying all observers");
4033 #ifdef WITH_PRESENCE
4034 if(handle == presenceResource.handle)
4038 #endif // WITH_PRESENCE
4039 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4041 // Verify that the resource exists
4042 resPtr = findResource ((OCResource *) handle);
4045 return OC_STACK_NO_RESOURCE;
4049 //only increment in the case of regular observing (not presence)
4050 incrementSequenceNumber(resPtr);
4051 method = OC_REST_OBSERVE;
4052 maxAge = MAX_OBSERVE_AGE;
4053 #ifdef WITH_PRESENCE
4054 result = SendAllObserverNotification (method, resPtr, maxAge,
4055 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4057 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4064 OCNotifyListOfObservers (OCResourceHandle handle,
4065 OCObservationId *obsIdList,
4066 uint8_t numberOfIds,
4067 const OCRepPayload *payload,
4068 OCQualityOfService qos)
4070 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4072 OCResource *resPtr = NULL;
4073 //TODO: we should allow the server to define this
4074 uint32_t maxAge = MAX_OBSERVE_AGE;
4076 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4077 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4078 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4080 resPtr = findResource ((OCResource *) handle);
4081 if (NULL == resPtr || myStackMode == OC_CLIENT)
4083 return OC_STACK_NO_RESOURCE;
4087 incrementSequenceNumber(resPtr);
4089 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4090 payload, maxAge, qos));
4093 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4095 OCStackResult result = OC_STACK_ERROR;
4096 OCServerRequest *serverRequest = NULL;
4098 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4100 // Validate input parameters
4101 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4102 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4105 // Get pointer to request info
4106 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4109 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4110 result = serverRequest->ehResponseHandler(ehResponse);
4116 //#ifdef DIRECT_PAIRING
4117 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4119 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4120 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4122 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4126 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4129 const OCDPDev_t* OCGetDirectPairedDevices()
4131 return (const OCDPDev_t*)DPGetPairedDevices();
4134 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4135 OCDirectPairingCB resultCallback)
4137 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4138 if(NULL == peer || NULL == pinNumber)
4140 OIC_LOG(ERROR, TAG, "Invalid parameters");
4141 return OC_STACK_INVALID_PARAM;
4143 if (NULL == resultCallback)
4145 OIC_LOG(ERROR, TAG, "Invalid callback");
4146 return OC_STACK_INVALID_CALLBACK;
4149 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4150 pinNumber, (OCDirectPairingResultCB)resultCallback);
4152 //#endif // DIRECT_PAIRING
4154 //-----------------------------------------------------------------------------
4155 // Private internal function definitions
4156 //-----------------------------------------------------------------------------
4157 static OCDoHandle GenerateInvocationHandle()
4159 OCDoHandle handle = NULL;
4160 // Generate token here, it will be deleted when the transaction is deleted
4161 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4164 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4170 #ifdef WITH_PRESENCE
4171 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4172 OCResourceProperty resourceProperties, uint8_t enable)
4176 return OC_STACK_INVALID_PARAM;
4178 if (resourceProperties
4179 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4181 OIC_LOG(ERROR, TAG, "Invalid property");
4182 return OC_STACK_INVALID_PARAM;
4186 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4190 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4196 OCStackResult initResources()
4198 OCStackResult result = OC_STACK_OK;
4200 headResource = NULL;
4201 tailResource = NULL;
4202 // Init Virtual Resources
4203 #ifdef WITH_PRESENCE
4204 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4206 result = OCCreateResource(&presenceResource.handle,
4207 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4209 OC_RSRVD_PRESENCE_URI,
4213 //make resource inactive
4214 result = OCChangeResourceProperty(
4215 &(((OCResource *) presenceResource.handle)->resourceProperties),
4218 #ifndef WITH_ARDUINO
4219 if (result == OC_STACK_OK)
4221 result = SRMInitSecureResources();
4225 if(result == OC_STACK_OK)
4227 CreateResetProfile();
4228 result = OCCreateResource(&deviceResource,
4229 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4230 OC_RSRVD_INTERFACE_DEFAULT,
4231 OC_RSRVD_DEVICE_URI,
4235 if(result == OC_STACK_OK)
4237 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4238 OC_RSRVD_INTERFACE_READ);
4242 if(result == OC_STACK_OK)
4244 result = OCCreateResource(&platformResource,
4245 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4246 OC_RSRVD_INTERFACE_DEFAULT,
4247 OC_RSRVD_PLATFORM_URI,
4251 if(result == OC_STACK_OK)
4253 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4254 OC_RSRVD_INTERFACE_READ);
4261 void insertResource(OCResource *resource)
4265 headResource = resource;
4266 tailResource = resource;
4270 tailResource->next = resource;
4271 tailResource = resource;
4273 resource->next = NULL;
4276 OCResource *findResource(OCResource *resource)
4278 OCResource *pointer = headResource;
4282 if (pointer == resource)
4286 pointer = pointer->next;
4291 void deleteAllResources()
4293 OCResource *pointer = headResource;
4294 OCResource *temp = NULL;
4298 temp = pointer->next;
4299 #ifdef WITH_PRESENCE
4300 if (pointer != (OCResource *) presenceResource.handle)
4302 #endif // WITH_PRESENCE
4303 deleteResource(pointer);
4304 #ifdef WITH_PRESENCE
4306 #endif // WITH_PRESENCE
4309 memset(&platformResource, 0, sizeof(platformResource));
4310 memset(&deviceResource, 0, sizeof(deviceResource));
4312 memset(&brokerResource, 0, sizeof(brokerResource));
4315 SRMDeInitSecureResources();
4317 #ifdef WITH_PRESENCE
4318 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4319 // presence notification attributed to their deletion to be processed.
4320 deleteResource((OCResource *) presenceResource.handle);
4321 memset(&presenceResource, 0, sizeof(presenceResource));
4322 #endif // WITH_PRESENCE
4325 OCStackResult deleteResource(OCResource *resource)
4327 OCResource *prev = NULL;
4328 OCResource *temp = NULL;
4331 OIC_LOG(DEBUG,TAG,"resource is NULL");
4332 return OC_STACK_INVALID_PARAM;
4335 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4337 temp = headResource;
4340 if (temp == resource)
4342 // Invalidate all Resource Properties.
4343 resource->resourceProperties = (OCResourceProperty) 0;
4344 #ifdef WITH_PRESENCE
4345 if(resource != (OCResource *) presenceResource.handle)
4347 #endif // WITH_PRESENCE
4348 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4349 #ifdef WITH_PRESENCE
4352 if(presenceResource.handle)
4354 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4355 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4358 // Only resource in list.
4359 if (temp == headResource && temp == tailResource)
4361 headResource = NULL;
4362 tailResource = NULL;
4365 else if (temp == headResource)
4367 headResource = temp->next;
4370 else if (temp == tailResource)
4372 tailResource = prev;
4373 tailResource->next = NULL;
4377 prev->next = temp->next;
4380 deleteResourceElements(temp);
4391 return OC_STACK_ERROR;
4394 void deleteResourceElements(OCResource *resource)
4401 OICFree(resource->uri);
4402 deleteResourceType(resource->rsrcType);
4403 deleteResourceInterface(resource->rsrcInterface);
4406 void deleteResourceType(OCResourceType *resourceType)
4408 OCResourceType *pointer = resourceType;
4409 OCResourceType *next = NULL;
4413 next = pointer->next;
4414 OICFree(pointer->resourcetypename);
4420 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4422 OCResourceInterface *pointer = resourceInterface;
4423 OCResourceInterface *next = NULL;
4427 next = pointer->next;
4428 OICFree(pointer->name);
4434 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4436 OCResourceType *pointer = NULL;
4437 OCResourceType *previous = NULL;
4438 if (!resource || !resourceType)
4442 // resource type list is empty.
4443 else if (!resource->rsrcType)
4445 resource->rsrcType = resourceType;
4449 pointer = resource->rsrcType;
4453 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4455 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4456 OICFree(resourceType->resourcetypename);
4457 OICFree(resourceType);
4461 pointer = pointer->next;
4466 previous->next = resourceType;
4469 resourceType->next = NULL;
4471 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4474 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4476 OCResource *resource = NULL;
4477 OCResourceType *pointer = NULL;
4479 // Find the specified resource
4480 resource = findResource((OCResource *) handle);
4486 // Make sure a resource has a resourcetype
4487 if (!resource->rsrcType)
4492 // Iterate through the list
4493 pointer = resource->rsrcType;
4494 for(uint8_t i = 0; i< index && pointer; ++i)
4496 pointer = pointer->next;
4501 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4503 if(resourceTypeList && resourceTypeName)
4505 OCResourceType * rtPointer = resourceTypeList;
4506 while(resourceTypeName && rtPointer)
4508 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4509 if(rtPointer->resourcetypename &&
4510 strcmp(resourceTypeName, (const char *)
4511 (rtPointer->resourcetypename)) == 0)
4515 rtPointer = rtPointer->next;
4523 * Insert a new interface into interface linked list only if not already present.
4524 * If alredy present, 2nd arg is free'd.
4525 * Default interface will always be first if present.
4527 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4529 OCResourceInterface *pointer = NULL;
4530 OCResourceInterface *previous = NULL;
4532 newInterface->next = NULL;
4534 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4536 if (!*firstInterface)
4538 // If first interface is not oic.if.baseline, by default add it as first interface type.
4539 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4541 *firstInterface = newInterface;
4545 OCStackResult result = BindResourceInterfaceToResource(resource,
4546 OC_RSRVD_INTERFACE_DEFAULT);
4547 if (result != OC_STACK_OK)
4549 OICFree(newInterface->name);
4550 OICFree(newInterface);
4553 if (*firstInterface)
4555 (*firstInterface)->next = newInterface;
4559 // If once add oic.if.baseline, later too below code take care of freeing memory.
4560 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4562 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4564 OICFree(newInterface->name);
4565 OICFree(newInterface);
4568 // This code will not hit anymore, keeping
4571 newInterface->next = *firstInterface;
4572 *firstInterface = newInterface;
4577 pointer = *firstInterface;
4580 if (strcmp(newInterface->name, pointer->name) == 0)
4582 OICFree(newInterface->name);
4583 OICFree(newInterface);
4587 pointer = pointer->next;
4592 previous->next = newInterface;
4597 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4600 OCResource *resource = NULL;
4601 OCResourceInterface *pointer = NULL;
4603 // Find the specified resource
4604 resource = findResource((OCResource *) handle);
4610 // Make sure a resource has a resourceinterface
4611 if (!resource->rsrcInterface)
4616 // Iterate through the list
4617 pointer = resource->rsrcInterface;
4619 for (uint8_t i = 0; i < index && pointer; ++i)
4621 pointer = pointer->next;
4627 * This function splits the uri using the '?' delimiter.
4628 * "uriWithoutQuery" is the block of characters between the beginning
4629 * till the delimiter or '\0' which ever comes first.
4630 * "query" is whatever is to the right of the delimiter if present.
4631 * No delimiter sets the query to NULL.
4632 * If either are present, they will be malloc'ed into the params 2, 3.
4633 * The first param, *uri is left untouched.
4635 * NOTE: This function does not account for whitespace at the end of the uri NOR
4636 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4637 * part of the query.
4639 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4643 return OC_STACK_INVALID_URI;
4645 if(!query || !uriWithoutQuery)
4647 return OC_STACK_INVALID_PARAM;
4651 *uriWithoutQuery = NULL;
4653 size_t uriWithoutQueryLen = 0;
4654 size_t queryLen = 0;
4655 size_t uriLen = strlen(uri);
4657 char *pointerToDelimiter = strstr(uri, "?");
4659 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4660 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4662 if (uriWithoutQueryLen)
4664 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4665 if (!*uriWithoutQuery)
4669 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4673 *query = (char *) OICCalloc(queryLen + 1, 1);
4676 OICFree(*uriWithoutQuery);
4677 *uriWithoutQuery = NULL;
4680 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4686 return OC_STACK_NO_MEMORY;
4689 static const OicUuid_t* OCGetServerInstanceID(void)
4691 static bool generated = false;
4692 static OicUuid_t sid;
4698 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4700 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4707 const char* OCGetServerInstanceIDString(void)
4709 static bool generated = false;
4710 static char sidStr[UUID_STRING_SIZE];
4717 const OicUuid_t *sid = OCGetServerInstanceID();
4718 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4720 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4728 CAResult_t OCSelectNetwork()
4730 CAResult_t retResult = CA_STATUS_FAILED;
4731 CAResult_t caResult = CA_STATUS_OK;
4733 CATransportAdapter_t connTypes[] = {
4735 CA_ADAPTER_RFCOMM_BTEDR,
4736 CA_ADAPTER_GATT_BTLE,
4739 ,CA_ADAPTER_REMOTE_ACCESS
4746 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4748 for(int i = 0; i < numConnTypes; i++)
4750 // If CA status is not initialized, CASelectNetwork() will not be called.
4751 if (caResult != CA_STATUS_NOT_INITIALIZED)
4753 caResult = CASelectNetwork(connTypes[i]);
4754 if (caResult == CA_STATUS_OK)
4756 retResult = CA_STATUS_OK;
4761 if (retResult != CA_STATUS_OK)
4763 return caResult; // Returns error of appropriate transport that failed fatally.
4769 OCStackResult CAResultToOCResult(CAResult_t caResult)
4775 case CA_STATUS_INVALID_PARAM:
4776 return OC_STACK_INVALID_PARAM;
4777 case CA_ADAPTER_NOT_ENABLED:
4778 return OC_STACK_ADAPTER_NOT_ENABLED;
4779 case CA_SERVER_STARTED_ALREADY:
4781 case CA_SERVER_NOT_STARTED:
4782 return OC_STACK_ERROR;
4783 case CA_DESTINATION_NOT_REACHABLE:
4784 return OC_STACK_COMM_ERROR;
4785 case CA_SOCKET_OPERATION_FAILED:
4786 return OC_STACK_COMM_ERROR;
4787 case CA_SEND_FAILED:
4788 return OC_STACK_COMM_ERROR;
4789 case CA_RECEIVE_FAILED:
4790 return OC_STACK_COMM_ERROR;
4791 case CA_MEMORY_ALLOC_FAILED:
4792 return OC_STACK_NO_MEMORY;
4793 case CA_REQUEST_TIMEOUT:
4794 return OC_STACK_TIMEOUT;
4795 case CA_DESTINATION_DISCONNECTED:
4796 return OC_STACK_COMM_ERROR;
4797 case CA_STATUS_FAILED:
4798 return OC_STACK_ERROR;
4799 case CA_NOT_SUPPORTED:
4800 return OC_STACK_NOTIMPL;
4802 return OC_STACK_ERROR;
4806 bool OCResultToSuccess(OCStackResult ocResult)
4811 case OC_STACK_RESOURCE_CREATED:
4812 case OC_STACK_RESOURCE_DELETED:
4813 case OC_STACK_CONTINUE:
4814 case OC_STACK_RESOURCE_CHANGED:
4815 case OC_STACK_SLOW_RESOURCE:
4823 OCStackResult OCSetProxyURI(const char *uri)
4825 return CAResultToOCResult(CASetProxyUri(uri));
4829 #if defined(RD_CLIENT) || defined(RD_SERVER)
4830 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
4832 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4834 OCResource *resource = NULL;
4836 resource = findResource((OCResource *) handle);
4839 OIC_LOG(ERROR, TAG, "Resource not found");
4840 return OC_STACK_ERROR;
4843 resource->ins = ins;
4848 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
4852 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
4856 OCResource *pointer = headResource;
4860 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
4862 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
4865 pointer = pointer->next;
4870 OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
4872 OCResource *resource = NULL;
4874 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4875 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
4877 resource = findResource((OCResource *) handle);
4880 *ins = resource->ins;
4883 return OC_STACK_ERROR;