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
44 #include "ocstackinternal.h"
45 #include "ocresourcehandler.h"
46 #include "occlientcb.h"
47 #include "ocobserve.h"
49 #include "oic_malloc.h"
50 #include "oic_string.h"
52 #include "ocserverrequest.h"
53 #include "secureresourcemanager.h"
54 #include "psinterface.h"
55 #include "doxmresource.h"
57 #include "cainterface.h"
58 #include "ocpayload.h"
59 #include "ocpayloadcbor.h"
60 #include "platform_features.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_time.h"
87 #ifdef HAVE_ARPA_INET_H
88 #include <arpa/inet.h>
92 #define UINT32_MAX (0xFFFFFFFFUL)
95 //-----------------------------------------------------------------------------
97 //-----------------------------------------------------------------------------
100 OC_STACK_UNINITIALIZED = 0,
101 OC_STACK_INITIALIZED,
102 OC_STACK_UNINIT_IN_PROGRESS
108 OC_PRESENCE_UNINITIALIZED = 0,
109 OC_PRESENCE_INITIALIZED
113 //-----------------------------------------------------------------------------
115 //-----------------------------------------------------------------------------
116 static OCStackState stackState = OC_STACK_UNINITIALIZED;
118 OCResource *headResource = NULL;
119 static OCResource *tailResource = NULL;
120 static OCResourceHandle platformResource = {0};
121 static OCResourceHandle deviceResource = {0};
123 static OCResourceHandle brokerResource = {0};
127 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
128 static PresenceResource presenceResource = {0};
129 static uint8_t PresenceTimeOutSize = 0;
130 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
133 static OCMode myStackMode;
135 //TODO: revisit this design
136 static bool gRASetInfo = false;
138 OCDeviceEntityHandler defaultDeviceHandler;
139 void* defaultDeviceHandlerCallbackParameter = NULL;
140 static const char COAP_TCP[] = "coap+tcp:";
141 static const char CORESPEC[] = "core";
143 //-----------------------------------------------------------------------------
145 //-----------------------------------------------------------------------------
146 #define TAG "OIC_RI_STACK"
147 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
148 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
149 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
150 TAG, #arg " is NULL"); return (retVal); } }
151 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
152 TAG, #arg " is NULL"); return; } }
153 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
156 //TODO: we should allow the server to define this
157 #define MAX_OBSERVE_AGE (0x2FFFFUL)
159 #define MILLISECONDS_PER_SECOND (1000)
161 //-----------------------------------------------------------------------------
162 // Private internal function prototypes
163 //-----------------------------------------------------------------------------
166 * Generate handle of OCDoResource invocation for callback management.
168 * @return Generated OCDoResource handle.
170 static OCDoHandle GenerateInvocationHandle();
173 * Initialize resource data structures, variables, etc.
175 * @return ::OC_STACK_OK on success, some other value upon failure.
177 static OCStackResult initResources();
180 * Add a resource to the end of the linked list of resources.
182 * @param resource Resource to be added
184 static void insertResource(OCResource *resource);
187 * Find a resource in the linked list of resources.
189 * @param resource Resource to be found.
190 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
193 static OCResource *findResource(OCResource *resource);
196 * Insert a resource type into a resource's resource type linked list.
197 * If resource type already exists, it will not be inserted and the
198 * resourceType will be free'd.
199 * resourceType->next should be null to avoid memory leaks.
200 * Function returns silently for null args.
202 * @param resource Resource where resource type is to be inserted.
203 * @param resourceType Resource type to be inserted.
205 static void insertResourceType(OCResource *resource,
206 OCResourceType *resourceType);
209 * Get a resource type at the specified index within a resource.
211 * @param handle Handle of resource.
212 * @param index Index of resource type.
214 * @return Pointer to resource type if found, NULL otherwise.
216 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
220 * Insert a resource interface into a resource's resource interface linked list.
221 * If resource interface already exists, it will not be inserted and the
222 * resourceInterface will be free'd.
223 * resourceInterface->next should be null to avoid memory leaks.
225 * @param resource Resource where resource interface is to be inserted.
226 * @param resourceInterface Resource interface to be inserted.
228 static void insertResourceInterface(OCResource *resource,
229 OCResourceInterface *resourceInterface);
232 * Get a resource interface at the specified index within a resource.
234 * @param handle Handle of resource.
235 * @param index Index of resource interface.
237 * @return Pointer to resource interface if found, NULL otherwise.
239 static OCResourceInterface *findResourceInterfaceAtIndex(
240 OCResourceHandle handle, uint8_t index);
243 * Delete all of the dynamically allocated elements that were created for the resource type.
245 * @param resourceType Specified resource type.
247 static void deleteResourceType(OCResourceType *resourceType);
250 * Delete all of the dynamically allocated elements that were created for the resource interface.
252 * @param resourceInterface Specified resource interface.
254 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
257 * Delete all of the dynamically allocated elements that were created for the resource.
259 * @param resource Specified resource.
261 static void deleteResourceElements(OCResource *resource);
264 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
267 * @param handle Handle of resource to be deleted.
269 * @return ::OC_STACK_OK on success, some other value upon failure.
271 static OCStackResult deleteResource(OCResource *resource);
274 * Delete all of the resources in the resource list.
276 static void deleteAllResources();
279 * Increment resource sequence number. Handles rollover.
281 * @param resPtr Pointer to resource.
283 static void incrementSequenceNumber(OCResource * resPtr);
286 * Attempts to initialize every network interface that the CA Layer might have compiled in.
288 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
289 * return something other than @ref CA_STATUS_OK, then this function fails.
291 * @return ::CA_STATUS_OK on success, some other value upon failure.
293 static CAResult_t OCSelectNetwork();
296 * Get the CoAP ticks after the specified number of milli-seconds.
298 * @param afterMilliSeconds Milli-seconds.
302 static uint32_t GetTicks(uint32_t afterMilliSeconds);
305 * Convert CAResult_t to OCStackResult.
307 * @param caResult CAResult_t code.
308 * @return ::OC_STACK_OK on success, some other value upon failure.
310 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
313 * Convert CAResponseResult_t to OCStackResult.
315 * @param caCode CAResponseResult_t code.
316 * @return ::OC_STACK_OK on success, some other value upon failure.
318 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
321 * Convert OCStackResult to CAResponseResult_t.
323 * @param caCode OCStackResult code.
324 * @param method OCMethod method the return code replies to.
325 * @return ::CA_CONTENT on OK, some other value upon failure.
327 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
330 * Convert OCTransportFlags_t to CATransportModifiers_t.
332 * @param ocConType OCTransportFlags_t input.
333 * @return CATransportFlags
335 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
338 * Convert CATransportFlags_t to OCTransportModifiers_t.
340 * @param caConType CATransportFlags_t input.
341 * @return OCTransportFlags
343 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
346 * Handle response from presence request.
348 * @param endPoint CA remote endpoint.
349 * @param responseInfo CA response info.
350 * @return ::OC_STACK_OK on success, some other value upon failure.
352 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
353 const CAResponseInfo_t *responseInfo);
356 * This function will be called back by CA layer when a response is received.
358 * @param endPoint CA remote endpoint.
359 * @param responseInfo CA response info.
361 static void HandleCAResponses(const CAEndpoint_t* endPoint,
362 const CAResponseInfo_t* responseInfo);
365 * This function will be called back by CA layer when a request is received.
367 * @param endPoint CA remote endpoint.
368 * @param requestInfo CA request info.
370 static void HandleCARequests(const CAEndpoint_t* endPoint,
371 const CARequestInfo_t* requestInfo);
374 * Extract query from a URI.
376 * @param uri Full URI with query.
377 * @param query Pointer to string that will contain query.
378 * @param newURI Pointer to string that will contain URI.
379 * @return ::OC_STACK_OK on success, some other value upon failure.
381 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
384 * Finds a resource type in an OCResourceType link-list.
386 * @param resourceTypeList The link-list to be searched through.
387 * @param resourceTypeName The key to search for.
389 * @return Resource type that matches the key (ie. resourceTypeName) or
390 * NULL if there is either an invalid parameter or this function was unable to find the key.
392 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
393 const char * resourceTypeName);
396 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
397 * TTL will be set to maxAge.
399 * @param cbNode Callback Node for which presence ttl is to be reset.
400 * @param maxAge New value of ttl in seconds.
402 * @return ::OC_STACK_OK on success, some other value upon failure.
404 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
407 * Ensure the accept header option is set appropriatly before sending the requests and routing
408 * header option is updated with destination.
410 * @param object CA remote endpoint.
411 * @param requestInfo CA request info.
413 * @return ::OC_STACK_OK on success, some other value upon failure.
415 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
417 //-----------------------------------------------------------------------------
418 // Internal functions
419 //-----------------------------------------------------------------------------
421 uint32_t GetTicks(uint32_t afterMilliSeconds)
426 // Guard against overflow of uint32_t
427 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
428 COAP_TICKS_PER_SECOND)
430 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
438 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
440 VERIFY_NON_NULL_NR(in, FATAL);
441 VERIFY_NON_NULL_NR(out, FATAL);
443 out->adapter = (OCTransportAdapter)in->adapter;
444 out->flags = CAToOCTransportFlags(in->flags);
445 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
446 out->port = in->port;
447 out->ifindex = in->ifindex;
448 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
449 /* This assert is to prevent accidental mismatch between address size macros defined in
450 * RI and CA and cause crash here. */
451 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
452 "Address size mismatch between RI and CA");
453 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
457 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
459 VERIFY_NON_NULL_NR(in, FATAL);
460 VERIFY_NON_NULL_NR(out, FATAL);
462 out->adapter = (CATransportAdapter_t)in->adapter;
463 out->flags = OCToCATransportFlags(in->flags);
464 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
465 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
466 /* This assert is to prevent accidental mismatch between address size macros defined in
467 * RI and CA and cause crash here. */
468 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
469 "Address size mismatch between RI and CA");
470 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
472 out->port = in->port;
473 out->ifindex = in->ifindex;
476 void FixUpClientResponse(OCClientResponse *cr)
478 VERIFY_NON_NULL_NR(cr, FATAL);
480 cr->addr = &cr->devAddr;
481 cr->connType = (OCConnectivityType)
482 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
485 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
487 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
488 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
490 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
491 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
492 if (OC_STACK_OK != rmResult)
494 OIC_LOG(ERROR, TAG, "Add destination option failed");
499 // OC stack prefer CBOR encoded payloads.
500 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
501 CAResult_t result = CASendRequest(object, requestInfo);
502 if(CA_STATUS_OK != result)
504 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
505 return CAResultToOCResult(result);
509 //-----------------------------------------------------------------------------
510 // Internal API function
511 //-----------------------------------------------------------------------------
513 // This internal function is called to update the stack with the status of
514 // observers and communication failures
515 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
517 OCStackResult result = OC_STACK_ERROR;
518 ResourceObserver * observer = NULL;
519 OCEntityHandlerRequest ehRequest = {0};
523 case OC_OBSERVER_NOT_INTERESTED:
524 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
525 observer = GetObserverUsingToken (token, tokenLength);
528 result = FormOCEntityHandlerRequest(&ehRequest,
529 (OCRequestHandle)NULL,
532 (OCResourceHandle)NULL,
533 NULL, PAYLOAD_TYPE_REPRESENTATION,
535 OC_OBSERVE_DEREGISTER,
538 if(result != OC_STACK_OK)
542 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
543 observer->resource->entityHandlerCallbackParam);
546 result = DeleteObserverUsingToken (token, tokenLength);
547 if(result == OC_STACK_OK)
549 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
553 result = OC_STACK_OK;
554 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
558 case OC_OBSERVER_STILL_INTERESTED:
559 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
560 observer = GetObserverUsingToken (token, tokenLength);
563 observer->forceHighQos = 0;
564 observer->failedCommCount = 0;
565 result = OC_STACK_OK;
569 result = OC_STACK_OBSERVER_NOT_FOUND;
573 case OC_OBSERVER_FAILED_COMM:
574 OIC_LOG(DEBUG, TAG, "observer is unreachable");
575 observer = GetObserverUsingToken (token, tokenLength);
578 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
580 result = FormOCEntityHandlerRequest(&ehRequest,
581 (OCRequestHandle)NULL,
584 (OCResourceHandle)NULL,
585 NULL, PAYLOAD_TYPE_REPRESENTATION,
587 OC_OBSERVE_DEREGISTER,
590 if(result != OC_STACK_OK)
592 return OC_STACK_ERROR;
594 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
595 observer->resource->entityHandlerCallbackParam);
597 result = DeleteObserverUsingToken (token, tokenLength);
598 if(result == OC_STACK_OK)
600 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
604 result = OC_STACK_OK;
605 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
610 observer->failedCommCount++;
611 result = OC_STACK_CONTINUE;
613 observer->forceHighQos = 1;
614 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
618 OIC_LOG(ERROR, TAG, "Unknown status");
619 result = OC_STACK_ERROR;
625 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
627 OCStackResult ret = OC_STACK_ERROR;
631 case CA_ADAPTER_NOT_ENABLED:
632 case CA_SERVER_NOT_STARTED:
633 ret = OC_STACK_ADAPTER_NOT_ENABLED;
635 case CA_MEMORY_ALLOC_FAILED:
636 ret = OC_STACK_NO_MEMORY;
638 case CA_STATUS_INVALID_PARAM:
639 ret = OC_STACK_INVALID_PARAM;
647 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
649 OCStackResult ret = OC_STACK_ERROR;
653 ret = OC_STACK_RESOURCE_CREATED;
656 ret = OC_STACK_RESOURCE_DELETED;
659 ret = OC_STACK_RESOURCE_CHANGED;
666 ret = OC_STACK_INVALID_QUERY;
668 case CA_UNAUTHORIZED_REQ:
669 ret = OC_STACK_UNAUTHORIZED_REQ;
672 ret = OC_STACK_INVALID_OPTION;
675 ret = OC_STACK_NO_RESOURCE;
677 case CA_RETRANSMIT_TIMEOUT:
678 ret = OC_STACK_COMM_ERROR;
680 case CA_REQUEST_ENTITY_TOO_LARGE:
681 ret = OC_STACK_TOO_LARGE_REQ;
689 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
691 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
700 // This Response Code is like HTTP 204 "No Content" but only used in
701 // response to POST and PUT requests.
705 // This Response Code is like HTTP 200 "OK" but only used in response to
710 // This should not happen but,
711 // give it a value just in case but output an error
713 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
717 case OC_STACK_RESOURCE_CREATED:
720 case OC_STACK_RESOURCE_DELETED:
723 case OC_STACK_RESOURCE_CHANGED:
726 case OC_STACK_INVALID_QUERY:
729 case OC_STACK_INVALID_OPTION:
732 case OC_STACK_NO_RESOURCE:
735 case OC_STACK_COMM_ERROR:
736 ret = CA_RETRANSMIT_TIMEOUT;
738 case OC_STACK_UNAUTHORIZED_REQ:
739 ret = CA_UNAUTHORIZED_REQ;
747 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
749 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
751 // supply default behavior.
752 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
754 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
756 if ((caFlags & OC_MASK_SCOPE) == 0)
758 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
763 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
765 return (OCTransportFlags)caFlags;
768 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
770 uint32_t lowerBound = 0;
771 uint32_t higherBound = 0;
773 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
775 return OC_STACK_INVALID_PARAM;
778 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
780 cbNode->presence->TTL = maxAgeSeconds;
782 for (int index = 0; index < PresenceTimeOutSize; index++)
784 // Guard against overflow
785 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
788 lowerBound = GetTicks((PresenceTimeOut[index] *
789 cbNode->presence->TTL *
790 MILLISECONDS_PER_SECOND)/100);
794 lowerBound = GetTicks(UINT32_MAX);
797 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
800 higherBound = GetTicks((PresenceTimeOut[index + 1] *
801 cbNode->presence->TTL *
802 MILLISECONDS_PER_SECOND)/100);
806 higherBound = GetTicks(UINT32_MAX);
809 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
811 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
812 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
813 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
816 cbNode->presence->TTLlevel = 0;
818 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
822 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
824 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
826 return OC_RSRVD_TRIGGER_CREATE;
828 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
830 return OC_RSRVD_TRIGGER_CHANGE;
834 return OC_RSRVD_TRIGGER_DELETE;
838 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
842 return OC_PRESENCE_TRIGGER_CREATE;
844 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
846 return OC_PRESENCE_TRIGGER_CREATE;
848 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
850 return OC_PRESENCE_TRIGGER_CHANGE;
854 return OC_PRESENCE_TRIGGER_DELETE;
859 * Encode an address string to match RFC 6874.
861 * @param outputAddress a char array to be written with the encoded string.
863 * @param outputSize size of outputAddress buffer.
865 * @param inputAddress a char array of size <= CA_MAX_URI_LENGTH
866 * containing a valid IPv6 address string.
868 * @return OC_STACK_OK if encoding succeeded.
869 * Else an error occured.
871 OCStackResult encodeAddressForRFC6874(char *outputAddress,
873 const char *inputAddress)
875 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
876 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
878 size_t inputLength = strnlen(inputAddress, outputSize);
880 // inputSize includes the null terminator
881 size_t inputSize = inputLength + 1;
883 if (inputSize > outputSize)
885 OIC_LOG_V(ERROR, TAG,
886 "encodeAddressForRFC6874 failed: "
887 "outputSize (%d) < inputSize (%d)",
888 outputSize, inputSize);
890 return OC_STACK_ERROR;
893 char* percentChar = strchr(inputAddress, '%');
895 // If there is no '%' character, then no change is required to the string.
896 if (NULL == percentChar)
898 OICStrcpy(outputAddress, outputSize, inputAddress);
902 const char* addressPart = &inputAddress[0];
903 const char* scopeIdPart = percentChar + 1;
905 // Sanity check to make sure this string doesn't have more '%' characters
906 if (NULL != strchr(scopeIdPart, '%'))
908 return OC_STACK_ERROR;
911 // If no string follows the first '%', then the input was invalid.
912 if (scopeIdPart[0] == '\0')
914 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
915 return OC_STACK_ERROR;
918 // Check to see if the string is already encoded
919 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
921 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
922 return OC_STACK_ERROR;
925 // Fail if we don't have room for encoded string's two additional chars
926 if (outputSize < (inputSize + 2))
928 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: encoded output will not fit!");
929 return OC_STACK_ERROR;
932 // Restore the null terminator with an escaped '%' character, per RFC 6874
933 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
934 strcat(outputAddress, "%25");
935 strcat(outputAddress, scopeIdPart);
941 * The cononical presence allows constructed URIs to be string compared.
943 * requestUri must be a char array of size CA_MAX_URI_LENGTH
945 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
948 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
949 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
950 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
952 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
954 if (ep->adapter == CA_ADAPTER_IP)
956 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
958 if ('\0' == ep->addr[0]) // multicast
960 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
964 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
966 OCStackResult result = encodeAddressForRFC6874(addressEncoded,
967 sizeof(addressEncoded),
970 if (OC_STACK_OK != result)
975 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
976 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
981 if ('\0' == ep->addr[0]) // multicast
983 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
984 ep->port = OC_MULTICAST_PORT;
986 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
987 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
991 // might work for other adapters (untested, but better than nothing)
992 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
993 OC_RSRVD_PRESENCE_URI);
997 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
998 const CAResponseInfo_t *responseInfo)
1000 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1001 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1003 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1004 ClientCB * cbNode = NULL;
1005 char *resourceTypeName = NULL;
1006 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1007 OCStackResult result = OC_STACK_ERROR;
1008 uint32_t maxAge = 0;
1010 char presenceUri[CA_MAX_URI_LENGTH];
1012 int presenceSubscribe = 0;
1013 int multicastPresenceSubscribe = 0;
1015 if (responseInfo->result != CA_CONTENT)
1017 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1018 return OC_STACK_ERROR;
1021 // check for unicast presence
1022 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
1023 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1025 return OC_STACK_INVALID_URI;
1028 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1031 presenceSubscribe = 1;
1035 // check for multiicast presence
1036 CAEndpoint_t ep = { .adapter = endpoint->adapter,
1037 .flags = endpoint->flags };
1039 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
1041 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1044 multicastPresenceSubscribe = 1;
1048 if (!presenceSubscribe && !multicastPresenceSubscribe)
1050 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1054 response.payload = NULL;
1055 response.result = OC_STACK_OK;
1057 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1058 FixUpClientResponse(&response);
1060 if (responseInfo->info.payload)
1062 result = OCParsePayload(&response.payload,
1063 PAYLOAD_TYPE_PRESENCE,
1064 responseInfo->info.payload,
1065 responseInfo->info.payloadSize);
1067 if(result != OC_STACK_OK)
1069 OIC_LOG(ERROR, TAG, "Presence parse failed");
1072 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1074 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1075 result = OC_STACK_ERROR;
1078 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1079 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1080 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1083 if (presenceSubscribe)
1085 if(cbNode->sequenceNumber == response.sequenceNumber)
1087 OIC_LOG(INFO, TAG, "No presence change");
1088 ResetPresenceTTL(cbNode, maxAge);
1089 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1095 OIC_LOG(INFO, TAG, "Stopping presence");
1096 response.result = OC_STACK_PRESENCE_STOPPED;
1097 if(cbNode->presence)
1099 OICFree(cbNode->presence->timeOut);
1100 OICFree(cbNode->presence);
1101 cbNode->presence = NULL;
1106 if(!cbNode->presence)
1108 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1110 if(!(cbNode->presence))
1112 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1113 result = OC_STACK_NO_MEMORY;
1117 VERIFY_NON_NULL_V(cbNode->presence);
1118 cbNode->presence->timeOut = NULL;
1119 cbNode->presence->timeOut = (uint32_t *)
1120 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1121 if(!(cbNode->presence->timeOut)){
1123 "Could not allocate memory for cbNode->presence->timeOut");
1124 OICFree(cbNode->presence);
1125 result = OC_STACK_NO_MEMORY;
1130 ResetPresenceTTL(cbNode, maxAge);
1132 cbNode->sequenceNumber = response.sequenceNumber;
1134 // Ensure that a filter is actually applied.
1135 if( resourceTypeName && cbNode->filterResourceType)
1137 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1146 // This is the multicast case
1147 OCMulticastNode* mcNode = NULL;
1148 mcNode = GetMCPresenceNode(presenceUri);
1152 if(mcNode->nonce == response.sequenceNumber)
1154 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1157 mcNode->nonce = response.sequenceNumber;
1161 OIC_LOG(INFO, TAG, "Stopping presence");
1162 response.result = OC_STACK_PRESENCE_STOPPED;
1167 char* uri = OICStrdup(presenceUri);
1171 "No Memory for URI to store in the presence node");
1172 result = OC_STACK_NO_MEMORY;
1176 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1177 if(result == OC_STACK_NO_MEMORY)
1180 "No Memory for Multicast Presence Node");
1184 // presence node now owns uri
1187 // Ensure that a filter is actually applied.
1188 if(resourceTypeName && cbNode->filterResourceType)
1190 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1197 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1199 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1201 FindAndDeleteClientCB(cbNode);
1205 OCPayloadDestroy(response.payload);
1209 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1211 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1213 if(responseInfo->info.resourceUri &&
1214 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1216 HandlePresenceResponse(endPoint, responseInfo);
1220 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1221 responseInfo->info.tokenLength, NULL, NULL);
1223 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1224 responseInfo->info.tokenLength);
1228 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1229 if(responseInfo->result == CA_EMPTY)
1231 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1232 // We do not have a case for the client to receive a RESET
1233 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1235 //This is the case of receiving an ACK on a request to a slow resource!
1236 OIC_LOG(INFO, TAG, "This is a pure ACK");
1237 //TODO: should we inform the client
1238 // app that at least the request was received at the server?
1241 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1243 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1244 OIC_LOG(INFO, TAG, "Calling into application address space");
1246 OCClientResponse response =
1247 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1248 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1249 FixUpClientResponse(&response);
1250 response.resourceUri = responseInfo->info.resourceUri;
1251 memcpy(response.identity.id, responseInfo->info.identity.id,
1252 sizeof (response.identity.id));
1253 response.identity.id_length = responseInfo->info.identity.id_length;
1255 response.result = CAResponseToOCStackResult(responseInfo->result);
1256 cbNode->callBack(cbNode->context,
1257 cbNode->handle, &response);
1258 FindAndDeleteClientCB(cbNode);
1262 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1263 OIC_LOG(INFO, TAG, "Calling into application address space");
1265 OCClientResponse response =
1266 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1267 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1268 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1269 FixUpClientResponse(&response);
1270 response.resourceUri = responseInfo->info.resourceUri;
1271 memcpy(response.identity.id, responseInfo->info.identity.id,
1272 sizeof (response.identity.id));
1273 response.identity.id_length = responseInfo->info.identity.id_length;
1275 response.result = CAResponseToOCStackResult(responseInfo->result);
1277 if(responseInfo->info.payload &&
1278 responseInfo->info.payloadSize)
1280 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1281 // check the security resource
1282 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1284 type = PAYLOAD_TYPE_SECURITY;
1286 else if (cbNode->method == OC_REST_DISCOVER)
1288 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1289 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1291 type = PAYLOAD_TYPE_DISCOVERY;
1294 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1296 type = PAYLOAD_TYPE_DISCOVERY;
1299 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1301 type = PAYLOAD_TYPE_DEVICE;
1303 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1305 type = PAYLOAD_TYPE_PLATFORM;
1307 #ifdef ROUTING_GATEWAY
1308 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1310 type = PAYLOAD_TYPE_REPRESENTATION;
1313 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1315 type = PAYLOAD_TYPE_RD;
1318 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1320 type = PAYLOAD_TYPE_REPRESENTATION;
1325 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1326 cbNode->method, cbNode->requestUri);
1330 else if (cbNode->method == OC_REST_GET ||
1331 cbNode->method == OC_REST_PUT ||
1332 cbNode->method == OC_REST_POST ||
1333 cbNode->method == OC_REST_OBSERVE ||
1334 cbNode->method == OC_REST_OBSERVE_ALL ||
1335 cbNode->method == OC_REST_DELETE)
1337 char targetUri[MAX_URI_LENGTH];
1338 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1339 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1340 if (strcmp(targetUri, cbNode->requestUri) == 0)
1342 type = PAYLOAD_TYPE_RD;
1344 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1346 type = PAYLOAD_TYPE_PLATFORM;
1348 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1350 type = PAYLOAD_TYPE_DEVICE;
1352 if (type == PAYLOAD_TYPE_INVALID)
1354 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1355 cbNode->method, cbNode->requestUri);
1356 type = PAYLOAD_TYPE_REPRESENTATION;
1361 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1362 cbNode->method, cbNode->requestUri);
1366 if(OC_STACK_OK != OCParsePayload(&response.payload,
1368 responseInfo->info.payload,
1369 responseInfo->info.payloadSize))
1371 OIC_LOG(ERROR, TAG, "Error converting payload");
1372 OCPayloadDestroy(response.payload);
1377 response.numRcvdVendorSpecificHeaderOptions = 0;
1378 if(responseInfo->info.numOptions > 0)
1381 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1382 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1385 uint32_t observationOption;
1386 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1387 for (observationOption=0, i=0;
1388 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1392 (observationOption << 8) | optionData[i];
1394 response.sequenceNumber = observationOption;
1395 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1400 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1403 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1405 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1406 OCPayloadDestroy(response.payload);
1410 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1412 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1413 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1417 if (cbNode->method == OC_REST_OBSERVE &&
1418 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1419 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1420 response.sequenceNumber <= cbNode->sequenceNumber)
1422 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1423 response.sequenceNumber);
1427 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1430 cbNode->sequenceNumber = response.sequenceNumber;
1432 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1434 FindAndDeleteClientCB(cbNode);
1438 // To keep discovery callbacks active.
1439 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1440 MILLISECONDS_PER_SECOND);
1444 //Need to send ACK when the response is CON
1445 if(responseInfo->info.type == CA_MSG_CONFIRM)
1447 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1448 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1451 OCPayloadDestroy(response.payload);
1458 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1459 if(responseInfo->result == CA_EMPTY)
1461 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1462 if(responseInfo->info.type == CA_MSG_RESET)
1464 OIC_LOG(INFO, TAG, "This is a RESET");
1465 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1466 OC_OBSERVER_NOT_INTERESTED);
1468 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1470 OIC_LOG(INFO, TAG, "This is a pure ACK");
1471 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1472 OC_OBSERVER_STILL_INTERESTED);
1475 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1477 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1478 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1479 OC_OBSERVER_FAILED_COMM);
1484 if(!cbNode && !observer)
1486 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1487 || myStackMode == OC_GATEWAY)
1489 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1490 if(responseInfo->result == CA_EMPTY)
1492 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1496 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1497 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1498 CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1502 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1503 || myStackMode == OC_GATEWAY)
1505 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1506 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1508 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1509 responseInfo->info.messageId);
1511 if (responseInfo->info.type == CA_MSG_RESET)
1513 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1514 responseInfo->info.messageId);
1521 OIC_LOG(INFO, TAG, "Exit OCHandleResponse");
1524 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1526 VERIFY_NON_NULL_NR(endPoint, FATAL);
1527 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1529 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1531 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1532 #ifdef ROUTING_GATEWAY
1533 bool needRIHandling = false;
1535 * Routing manager is going to update either of endpoint or response or both.
1536 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1537 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1540 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1542 if(ret != OC_STACK_OK || !needRIHandling)
1544 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1550 * Put source in sender endpoint so that the next packet from application can be routed to
1551 * proper destination and remove "RM" coap header option before passing request / response to
1552 * RI as this option will make no sense to either RI or application.
1554 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1555 (uint8_t *) &(responseInfo->info.numOptions),
1556 (CAEndpoint_t *) endPoint);
1559 OCHandleResponse(endPoint, responseInfo);
1561 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1565 * This function handles error response from CA
1566 * code shall be added to handle the errors
1568 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1570 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1572 if (NULL == endPoint)
1574 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1578 if (NULL == errorInfo)
1580 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1584 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1585 errorInfo->info.tokenLength, NULL, NULL);
1588 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1589 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1590 FixUpClientResponse(&response);
1591 response.resourceUri = errorInfo->info.resourceUri;
1592 memcpy(response.identity.id, errorInfo->info.identity.id,
1593 sizeof (response.identity.id));
1594 response.identity.id_length = errorInfo->info.identity.id_length;
1595 response.result = CAResultToOCStackResult(errorInfo->result);
1597 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1598 FindAndDeleteClientCB(cbNode);
1601 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1605 * This function sends out Direct Stack Responses. These are responses that are not coming
1606 * from the application entity handler. These responses have no payload and are usually ACKs,
1607 * RESETs or some error conditions that were caught by the stack.
1609 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1610 const CAResponseResult_t responseResult, const CAMessageType_t type,
1611 const uint8_t numOptions, const CAHeaderOption_t *options,
1612 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1613 CADataType_t dataType)
1615 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1616 CAResponseInfo_t respInfo = {
1617 .result = responseResult
1619 respInfo.info.messageId = coapID;
1620 respInfo.info.numOptions = numOptions;
1622 if (respInfo.info.numOptions)
1624 respInfo.info.options =
1625 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1626 memcpy (respInfo.info.options, options,
1627 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1631 respInfo.info.payload = NULL;
1632 respInfo.info.token = token;
1633 respInfo.info.tokenLength = tokenLength;
1634 respInfo.info.type = type;
1635 respInfo.info.resourceUri = OICStrdup (resourceUri);
1636 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1637 respInfo.info.dataType = dataType;
1639 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1640 // Add the destination to route option from the endpoint->routeData.
1641 bool doPost = false;
1642 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1643 if(OC_STACK_OK != result)
1645 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1650 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1651 CARequestInfo_t reqInfo = {.method = CA_POST };
1652 /* The following initialization is not done in a single initializer block as in
1653 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1654 * does not have designated initalizers. This is a work-around for now.
1656 reqInfo.info.type = CA_MSG_NONCONFIRM;
1657 reqInfo.info.messageId = coapID;
1658 reqInfo.info.tokenLength = tokenLength;
1659 reqInfo.info.token = token;
1660 reqInfo.info.numOptions = respInfo.info.numOptions;
1661 reqInfo.info.payload = NULL;
1662 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1663 if (reqInfo.info.numOptions)
1665 reqInfo.info.options =
1666 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1667 if (NULL == reqInfo.info.options)
1669 OIC_LOG(ERROR, TAG, "Calloc failed");
1670 return OC_STACK_NO_MEMORY;
1672 memcpy (reqInfo.info.options, respInfo.info.options,
1673 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1676 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1677 OICFree (reqInfo.info.resourceUri);
1678 OICFree (reqInfo.info.options);
1679 OICFree (respInfo.info.resourceUri);
1680 OICFree (respInfo.info.options);
1681 if (CA_STATUS_OK != caResult)
1683 OIC_LOG(ERROR, TAG, "CASendRequest error");
1684 return CAResultToOCResult(caResult);
1690 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1692 // resourceUri in the info field is cloned in the CA layer and
1693 // thus ownership is still here.
1694 OICFree (respInfo.info.resourceUri);
1695 OICFree (respInfo.info.options);
1696 if(CA_STATUS_OK != caResult)
1698 OIC_LOG(ERROR, TAG, "CASendResponse error");
1699 return CAResultToOCResult(caResult);
1702 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1706 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1708 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1709 OCStackResult result = OC_STACK_ERROR;
1710 if(!protocolRequest)
1712 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1713 return OC_STACK_INVALID_PARAM;
1716 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1717 protocolRequest->tokenLength);
1720 OIC_LOG(INFO, TAG, "This is a new Server Request");
1721 result = AddServerRequest(&request, protocolRequest->coapID,
1722 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1723 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1724 protocolRequest->observationOption, protocolRequest->qos,
1725 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1726 protocolRequest->payload, protocolRequest->requestToken,
1727 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1728 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1729 &protocolRequest->devAddr);
1730 if (OC_STACK_OK != result)
1732 OIC_LOG(ERROR, TAG, "Error adding server request");
1738 OIC_LOG(ERROR, TAG, "Out of Memory");
1739 return OC_STACK_NO_MEMORY;
1742 if(!protocolRequest->reqMorePacket)
1744 request->requestComplete = 1;
1749 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1752 if(request->requestComplete)
1754 OIC_LOG(INFO, TAG, "This Server Request is complete");
1755 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1756 OCResource *resource = NULL;
1757 result = DetermineResourceHandling (request, &resHandling, &resource);
1758 if (result == OC_STACK_OK)
1760 result = ProcessRequest(resHandling, resource, request);
1765 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1766 result = OC_STACK_CONTINUE;
1771 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1773 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1776 if (requestInfo->info.resourceUri &&
1777 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1779 HandleKeepAliveRequest(endPoint, requestInfo);
1784 OCStackResult requestResult = OC_STACK_ERROR;
1786 if(myStackMode == OC_CLIENT)
1788 //TODO: should the client be responding to requests?
1792 OCServerProtocolRequest serverRequest = {0};
1794 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1796 char * uriWithoutQuery = NULL;
1797 char * query = NULL;
1799 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1801 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1803 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1806 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1807 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1809 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1811 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1812 OICFree(uriWithoutQuery);
1816 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1817 OICFree(uriWithoutQuery);
1824 if(strlen(query) < MAX_QUERY_LENGTH)
1826 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1831 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1837 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1839 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1840 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1841 if (!serverRequest.payload)
1843 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1846 memcpy (serverRequest.payload, requestInfo->info.payload,
1847 requestInfo->info.payloadSize);
1851 serverRequest.reqTotalSize = 0;
1854 switch (requestInfo->method)
1857 serverRequest.method = OC_REST_GET;
1860 serverRequest.method = OC_REST_PUT;
1863 serverRequest.method = OC_REST_POST;
1866 serverRequest.method = OC_REST_DELETE;
1869 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1870 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1871 requestInfo->info.type, requestInfo->info.numOptions,
1872 requestInfo->info.options, requestInfo->info.token,
1873 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1875 OICFree(serverRequest.payload);
1879 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1880 requestInfo->info.tokenLength);
1882 serverRequest.tokenLength = requestInfo->info.tokenLength;
1883 if (serverRequest.tokenLength) {
1885 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1887 if (!serverRequest.requestToken)
1889 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1890 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1891 requestInfo->info.type, requestInfo->info.numOptions,
1892 requestInfo->info.options, requestInfo->info.token,
1893 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1895 OICFree(serverRequest.payload);
1898 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1901 switch (requestInfo->info.acceptFormat)
1903 case CA_FORMAT_APPLICATION_CBOR:
1904 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1906 case CA_FORMAT_UNDEFINED:
1907 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1910 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1913 if (requestInfo->info.type == CA_MSG_CONFIRM)
1915 serverRequest.qos = OC_HIGH_QOS;
1919 serverRequest.qos = OC_LOW_QOS;
1921 // CA does not need the following field
1922 // Are we sure CA does not need them? how is it responding to multicast
1923 serverRequest.delayedResNeeded = 0;
1925 serverRequest.coapID = requestInfo->info.messageId;
1927 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1929 // copy vendor specific header options
1930 uint8_t tempNum = (requestInfo->info.numOptions);
1932 // Assume no observation requested and it is a pure GET.
1933 // If obs registration/de-registration requested it'll be fetched from the
1934 // options in GetObserveHeaderOption()
1935 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1937 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1938 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1941 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1942 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1943 requestInfo->info.type, requestInfo->info.numOptions,
1944 requestInfo->info.options, requestInfo->info.token,
1945 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1947 OICFree(serverRequest.payload);
1948 OICFree(serverRequest.requestToken);
1951 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1952 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1954 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1955 sizeof(CAHeaderOption_t)*tempNum);
1958 requestResult = HandleStackRequests (&serverRequest);
1960 // Send ACK to client as precursor to slow response
1961 if (requestResult == OC_STACK_SLOW_RESOURCE)
1963 if (requestInfo->info.type == CA_MSG_CONFIRM)
1965 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1966 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
1970 else if(!OCResultToSuccess(requestResult))
1972 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1974 CAResponseResult_t stackResponse =
1975 OCToCAStackResult(requestResult, serverRequest.method);
1977 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1978 requestInfo->info.type, requestInfo->info.numOptions,
1979 requestInfo->info.options, requestInfo->info.token,
1980 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1983 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1984 // The token is copied in there, and is thus still owned by this function.
1985 OICFree(serverRequest.payload);
1986 OICFree(serverRequest.requestToken);
1987 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1990 //This function will be called back by CA layer when a request is received
1991 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1993 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1996 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2002 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2006 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2007 #ifdef ROUTING_GATEWAY
2008 bool needRIHandling = false;
2009 bool isEmptyMsg = false;
2011 * Routing manager is going to update either of endpoint or request or both.
2012 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2013 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2014 * destination. It can also remove "RM" coap header option before passing request / response to
2015 * RI as this option will make no sense to either RI or application.
2017 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2018 &needRIHandling, &isEmptyMsg);
2019 if(OC_STACK_OK != ret || !needRIHandling)
2021 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2027 * Put source in sender endpoint so that the next packet from application can be routed to
2028 * proper destination and remove RM header option.
2030 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2031 (uint8_t *) &(requestInfo->info.numOptions),
2032 (CAEndpoint_t *) endPoint);
2034 #ifdef ROUTING_GATEWAY
2038 * In Gateways, the MSGType in route option is used to check if the actual
2039 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2040 * EMPTY response is sent in the form of POST request which need to be changed
2041 * to a EMPTY response by RM. This translation is done in this part of the code.
2043 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2044 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2045 .info.messageId = requestInfo->info.messageId,
2046 .info.type = CA_MSG_ACKNOWLEDGE};
2047 OCHandleResponse(endPoint, &respInfo);
2053 // Normal handling of the packet
2054 OCHandleRequests(endPoint, requestInfo);
2056 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2059 bool validatePlatformInfo(OCPlatformInfo info)
2062 if (!info.platformID)
2064 OIC_LOG(ERROR, TAG, "No platform ID found.");
2068 if (info.manufacturerName)
2070 size_t lenManufacturerName = strlen(info.manufacturerName);
2072 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2074 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2080 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2084 if (info.manufacturerUrl)
2086 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2088 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2095 //-----------------------------------------------------------------------------
2097 //-----------------------------------------------------------------------------
2099 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2102 !raInfo->username ||
2103 !raInfo->hostname ||
2104 !raInfo->xmpp_domain)
2107 return OC_STACK_INVALID_PARAM;
2109 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2110 gRASetInfo = (result == OC_STACK_OK)? true : false;
2116 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2120 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2123 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2125 if(stackState == OC_STACK_INITIALIZED)
2127 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2128 OCStop() between them are ignored.");
2132 #ifndef ROUTING_GATEWAY
2133 if (OC_GATEWAY == mode)
2135 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2136 return OC_STACK_INVALID_PARAM;
2143 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2144 return OC_STACK_ERROR;
2148 OCStackResult result = OC_STACK_ERROR;
2149 OIC_LOG(INFO, TAG, "Entering OCInit");
2152 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2153 || (mode == OC_GATEWAY)))
2155 OIC_LOG(ERROR, TAG, "Invalid mode");
2156 return OC_STACK_ERROR;
2160 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2162 caglobals.client = true;
2164 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2166 caglobals.server = true;
2169 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2170 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2172 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2174 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2175 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2177 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2180 defaultDeviceHandler = NULL;
2181 defaultDeviceHandlerCallbackParameter = NULL;
2183 result = CAResultToOCResult(CAInitialize());
2184 VERIFY_SUCCESS(result, OC_STACK_OK);
2186 result = CAResultToOCResult(OCSelectNetwork());
2187 VERIFY_SUCCESS(result, OC_STACK_OK);
2189 switch (myStackMode)
2192 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2193 result = CAResultToOCResult(CAStartDiscoveryServer());
2194 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2197 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2198 result = CAResultToOCResult(CAStartListeningServer());
2199 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2201 case OC_CLIENT_SERVER:
2203 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2204 result = CAResultToOCResult(CAStartListeningServer());
2205 if(result == OC_STACK_OK)
2207 result = CAResultToOCResult(CAStartDiscoveryServer());
2211 VERIFY_SUCCESS(result, OC_STACK_OK);
2214 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2217 #ifdef WITH_PRESENCE
2218 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2219 #endif // WITH_PRESENCE
2221 //Update Stack state to initialized
2222 stackState = OC_STACK_INITIALIZED;
2224 // Initialize resource
2225 if(myStackMode != OC_CLIENT)
2227 result = initResources();
2230 // Initialize the SRM Policy Engine
2231 if(result == OC_STACK_OK)
2233 result = SRMInitPolicyEngine();
2234 // TODO after BeachHead delivery: consolidate into single SRMInit()
2236 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2237 RMSetStackMode(mode);
2238 #ifdef ROUTING_GATEWAY
2239 if (OC_GATEWAY == myStackMode)
2241 result = RMInitialize();
2247 if (result == OC_STACK_OK)
2249 result = InitializeKeepAlive(myStackMode);
2254 if(result != OC_STACK_OK)
2256 OIC_LOG(ERROR, TAG, "Stack initialization error");
2257 deleteAllResources();
2259 stackState = OC_STACK_UNINITIALIZED;
2264 OCStackResult OCStop()
2266 OIC_LOG(INFO, TAG, "Entering OCStop");
2268 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2270 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2273 else if (stackState != OC_STACK_INITIALIZED)
2275 OIC_LOG(ERROR, TAG, "Stack not initialized");
2276 return OC_STACK_ERROR;
2279 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2281 #ifdef WITH_PRESENCE
2282 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2283 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2284 presenceResource.presenceTTL = 0;
2285 #endif // WITH_PRESENCE
2287 #ifdef ROUTING_GATEWAY
2288 if (OC_GATEWAY == myStackMode)
2295 TerminateKeepAlive(myStackMode);
2298 // Free memory dynamically allocated for resources
2299 deleteAllResources();
2301 DeletePlatformInfo();
2303 // Remove all observers
2304 DeleteObserverList();
2305 // Remove all the client callbacks
2306 DeleteClientCBList();
2308 // De-init the SRM Policy Engine
2309 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2310 SRMDeInitPolicyEngine();
2313 stackState = OC_STACK_UNINITIALIZED;
2317 OCStackResult OCStartMulticastServer()
2319 if(stackState != OC_STACK_INITIALIZED)
2321 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2322 return OC_STACK_ERROR;
2324 CAResult_t ret = CAStartListeningServer();
2325 if (CA_STATUS_OK != ret)
2327 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2328 return OC_STACK_ERROR;
2333 OCStackResult OCStopMulticastServer()
2335 CAResult_t ret = CAStopListeningServer();
2336 if (CA_STATUS_OK != ret)
2338 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2339 return OC_STACK_ERROR;
2344 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2349 return CA_MSG_CONFIRM;
2354 return CA_MSG_NONCONFIRM;
2359 * A request uri consists of the following components in order:
2362 * CoAP over UDP prefix "coap://"
2363 * CoAP over TCP prefix "coap+tcp://"
2365 * IPv6 address "[1234::5678]"
2366 * IPv4 address "192.168.1.1"
2367 * optional port ":5683"
2368 * resource uri "/oc/core..."
2370 * for PRESENCE requests, extract resource type.
2372 static OCStackResult ParseRequestUri(const char *fullUri,
2373 OCTransportAdapter adapter,
2374 OCTransportFlags flags,
2375 OCDevAddr **devAddr,
2377 char **resourceType)
2379 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2381 OCStackResult result = OC_STACK_OK;
2382 OCDevAddr *da = NULL;
2386 // provide defaults for all returned values
2393 *resourceUri = NULL;
2397 *resourceType = NULL;
2400 // delimit url prefix, if any
2401 const char *start = fullUri;
2402 char *slash2 = strstr(start, "//");
2407 char *slash = strchr(start, '/');
2410 return OC_STACK_INVALID_URI;
2413 // process url scheme
2414 size_t prefixLen = slash2 - fullUri;
2418 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2424 // TODO: this logic should come in with unit tests exercising the various strings
2425 // processs url prefix, if any
2426 size_t urlLen = slash - start;
2430 if (urlLen && devAddr)
2431 { // construct OCDevAddr
2432 if (start[0] == '[')
2434 char *close = strchr(++start, ']');
2435 if (!close || close > slash)
2437 return OC_STACK_INVALID_URI;
2440 if (close[1] == ':')
2447 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2451 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2453 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2457 char *dot = strchr(start, '.');
2458 if (dot && dot < slash)
2460 colon = strchr(start, ':');
2461 end = (colon && colon < slash) ? colon : slash;
2466 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2470 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2472 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2480 if (len >= sizeof(da->addr))
2482 return OC_STACK_INVALID_URI;
2484 // collect port, if any
2485 if (colon && colon < slash)
2487 for (colon++; colon < slash; colon++)
2490 if (c < '0' || c > '9')
2492 return OC_STACK_INVALID_URI;
2494 port = 10 * port + c - '0';
2499 if (len >= sizeof(da->addr))
2501 return OC_STACK_INVALID_URI;
2504 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2507 return OC_STACK_NO_MEMORY;
2509 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2511 da->adapter = adapter;
2513 if (!strncmp(fullUri, "coaps:", 6))
2515 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2520 // process resource uri, if any
2522 { // request uri and query
2523 size_t ulen = strlen(slash); // resource uri length
2524 size_t tlen = 0; // resource type length
2527 static const char strPresence[] = "/oic/ad?rt=";
2528 static const size_t lenPresence = sizeof(strPresence) - 1;
2529 if (!strncmp(slash, strPresence, lenPresence))
2531 type = slash + lenPresence;
2532 tlen = ulen - lenPresence;
2537 *resourceUri = (char *)OICMalloc(ulen + 1);
2540 result = OC_STACK_NO_MEMORY;
2543 strcpy(*resourceUri, slash);
2546 if (type && resourceType)
2548 *resourceType = (char *)OICMalloc(tlen + 1);
2551 result = OC_STACK_NO_MEMORY;
2555 OICStrcpy(*resourceType, (tlen+1), type);
2562 // free all returned values
2569 OICFree(*resourceUri);
2573 OICFree(*resourceType);
2578 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2579 char *resourceUri, char **requestUri)
2581 char uri[CA_MAX_URI_LENGTH];
2583 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2585 *requestUri = OICStrdup(uri);
2588 return OC_STACK_NO_MEMORY;
2595 * Discover or Perform requests on a specified resource
2597 OCStackResult OCDoResource(OCDoHandle *handle,
2599 const char *requestUri,
2600 const OCDevAddr *destination,
2602 OCConnectivityType connectivityType,
2603 OCQualityOfService qos,
2604 OCCallbackData *cbData,
2605 OCHeaderOption *options,
2608 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2610 // Validate input parameters
2611 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2612 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2613 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2615 OCStackResult result = OC_STACK_ERROR;
2616 CAResult_t caResult;
2617 CAToken_t token = NULL;
2618 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2619 ClientCB *clientCB = NULL;
2620 OCDoHandle resHandle = NULL;
2621 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2622 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2624 OCTransportAdapter adapter;
2625 OCTransportFlags flags;
2626 // the request contents are put here
2627 CARequestInfo_t requestInfo = {.method = CA_GET};
2628 // requestUri will be parsed into the following three variables
2629 OCDevAddr *devAddr = NULL;
2630 char *resourceUri = NULL;
2631 char *resourceType = NULL;
2634 * Support original behavior with address on resourceUri argument.
2636 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2637 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2639 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2641 if (result != OC_STACK_OK)
2643 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2650 case OC_REST_OBSERVE:
2651 case OC_REST_OBSERVE_ALL:
2652 case OC_REST_CANCEL_OBSERVE:
2653 requestInfo.method = CA_GET;
2656 requestInfo.method = CA_PUT;
2659 requestInfo.method = CA_POST;
2661 case OC_REST_DELETE:
2662 requestInfo.method = CA_DELETE;
2664 case OC_REST_DISCOVER:
2666 if (destination || devAddr)
2668 requestInfo.isMulticast = false;
2672 tmpDevAddr.adapter = adapter;
2673 tmpDevAddr.flags = flags;
2674 destination = &tmpDevAddr;
2675 requestInfo.isMulticast = true;
2677 // CA_DISCOVER will become GET and isMulticast
2678 requestInfo.method = CA_GET;
2680 #ifdef WITH_PRESENCE
2681 case OC_REST_PRESENCE:
2682 // Replacing method type with GET because "presence"
2683 // is a stack layer only implementation.
2684 requestInfo.method = CA_GET;
2688 result = OC_STACK_INVALID_METHOD;
2692 if (!devAddr && !destination)
2694 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2695 result = OC_STACK_INVALID_PARAM;
2699 /* If not original behavior, use destination argument */
2700 if (destination && !devAddr)
2702 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2705 result = OC_STACK_NO_MEMORY;
2708 *devAddr = *destination;
2711 resHandle = GenerateInvocationHandle();
2714 result = OC_STACK_NO_MEMORY;
2718 caResult = CAGenerateToken(&token, tokenLength);
2719 if (caResult != CA_STATUS_OK)
2721 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2722 result= OC_STACK_ERROR;
2726 // fill in request data
2727 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2728 requestInfo.info.token = token;
2729 requestInfo.info.tokenLength = tokenLength;
2730 requestInfo.info.resourceUri = resourceUri;
2732 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2734 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2735 options, numOptions, OC_OBSERVE_REGISTER);
2736 if (result != OC_STACK_OK)
2740 requestInfo.info.numOptions = numOptions + 1;
2744 requestInfo.info.numOptions = numOptions;
2745 requestInfo.info.options =
2746 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2747 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2748 numOptions * sizeof(CAHeaderOption_t));
2751 CopyDevAddrToEndpoint(devAddr, &endpoint);
2756 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2759 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2762 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2766 requestInfo.info.payload = NULL;
2767 requestInfo.info.payloadSize = 0;
2768 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2771 // prepare for response
2772 #ifdef WITH_PRESENCE
2773 if (method == OC_REST_PRESENCE)
2775 char *presenceUri = NULL;
2776 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2777 if (OC_STACK_OK != result)
2782 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2783 // Presence notification will form a canonical uri to
2784 // look for callbacks into the application.
2785 resourceUri = presenceUri;
2789 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2790 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2791 method, devAddr, resourceUri, resourceType, ttl);
2792 if (OC_STACK_OK != result)
2797 devAddr = NULL; // Client CB list entry now owns it
2798 resourceUri = NULL; // Client CB list entry now owns it
2799 resourceType = NULL; // Client CB list entry now owns it
2802 result = OCSendRequest(&endpoint, &requestInfo);
2803 if (OC_STACK_OK != result)
2810 *handle = resHandle;
2814 if (result != OC_STACK_OK)
2816 OIC_LOG(ERROR, TAG, "OCDoResource error");
2817 FindAndDeleteClientCB(clientCB);
2818 CADestroyToken(token);
2826 // This is the owner of the payload object, so we free it
2827 OCPayloadDestroy(payload);
2828 OICFree(requestInfo.info.payload);
2830 OICFree(resourceUri);
2831 OICFree(resourceType);
2832 OICFree(requestInfo.info.options);
2836 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2840 * This ftn is implemented one of two ways in the case of observation:
2842 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2843 * Remove the callback associated on client side.
2844 * When the next notification comes in from server,
2845 * reply with RESET message to server.
2846 * Keep in mind that the server will react to RESET only
2847 * if the last notification was sent as CON
2849 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2850 * and it is associated with an observe request
2851 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2852 * Send CON Observe request to server with
2853 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2854 * Remove the callback associated on client side.
2856 OCStackResult ret = OC_STACK_OK;
2857 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2858 CARequestInfo_t requestInfo = {.method = CA_GET};
2862 return OC_STACK_INVALID_PARAM;
2865 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2868 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2869 return OC_STACK_ERROR;
2872 switch (clientCB->method)
2874 case OC_REST_OBSERVE:
2875 case OC_REST_OBSERVE_ALL:
2877 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2879 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2881 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2883 FindAndDeleteClientCB(clientCB);
2887 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2889 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2890 requestInfo.info.token = clientCB->token;
2891 requestInfo.info.tokenLength = clientCB->tokenLength;
2893 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2894 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2896 return OC_STACK_ERROR;
2898 requestInfo.info.numOptions = numOptions + 1;
2899 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2902 ret = OCSendRequest(&endpoint, &requestInfo);
2904 if (requestInfo.info.options)
2906 OICFree (requestInfo.info.options);
2908 if (requestInfo.info.resourceUri)
2910 OICFree (requestInfo.info.resourceUri);
2915 case OC_REST_DISCOVER:
2916 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2917 clientCB->requestUri);
2918 FindAndDeleteClientCB(clientCB);
2921 #ifdef WITH_PRESENCE
2922 case OC_REST_PRESENCE:
2923 FindAndDeleteClientCB(clientCB);
2928 ret = OC_STACK_INVALID_METHOD;
2936 * @brief Register Persistent storage callback.
2937 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2939 * OC_STACK_OK - No errors; Success
2940 * OC_STACK_INVALID_PARAM - Invalid parameter
2942 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2944 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2945 if(!persistentStorageHandler)
2947 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2948 return OC_STACK_INVALID_PARAM;
2952 if( !persistentStorageHandler->open ||
2953 !persistentStorageHandler->close ||
2954 !persistentStorageHandler->read ||
2955 !persistentStorageHandler->unlink ||
2956 !persistentStorageHandler->write)
2958 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2959 return OC_STACK_INVALID_PARAM;
2962 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2965 #ifdef WITH_PRESENCE
2967 OCStackResult OCProcessPresence()
2969 OCStackResult result = OC_STACK_OK;
2971 // the following line floods the log with messages that are irrelevant
2972 // to most purposes. Uncomment as needed.
2973 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2974 ClientCB* cbNode = NULL;
2975 OCClientResponse clientResponse;
2976 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2978 LL_FOREACH(cbList, cbNode)
2980 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2985 uint32_t now = GetTicks(0);
2986 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2987 cbNode->presence->TTLlevel);
2988 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2990 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2995 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2997 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2998 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3000 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3002 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3004 clientResponse.sequenceNumber = 0;
3005 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3006 clientResponse.devAddr = *cbNode->devAddr;
3007 FixUpClientResponse(&clientResponse);
3008 clientResponse.payload = NULL;
3010 // Increment the TTLLevel (going to a next state), so we don't keep
3011 // sending presence notification to client.
3012 cbNode->presence->TTLlevel++;
3013 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3014 cbNode->presence->TTLlevel);
3016 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3017 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3019 FindAndDeleteClientCB(cbNode);
3023 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3028 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3029 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3030 CARequestInfo_t requestInfo = {.method = CA_GET};
3032 OIC_LOG(DEBUG, TAG, "time to test server presence");
3034 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3036 requestData.type = CA_MSG_NONCONFIRM;
3037 requestData.token = cbNode->token;
3038 requestData.tokenLength = cbNode->tokenLength;
3039 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3040 requestInfo.method = CA_GET;
3041 requestInfo.info = requestData;
3043 result = OCSendRequest(&endpoint, &requestInfo);
3044 if (OC_STACK_OK != result)
3049 cbNode->presence->TTLlevel++;
3050 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3053 if (result != OC_STACK_OK)
3055 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3060 #endif // WITH_PRESENCE
3062 OCStackResult OCProcess()
3064 #ifdef WITH_PRESENCE
3065 OCProcessPresence();
3067 CAHandleRequestResponse();
3069 #ifdef ROUTING_GATEWAY
3079 #ifdef WITH_PRESENCE
3080 OCStackResult OCStartPresence(const uint32_t ttl)
3082 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3083 OCChangeResourceProperty(
3084 &(((OCResource *)presenceResource.handle)->resourceProperties),
3087 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3089 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3090 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3094 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3095 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3099 presenceResource.presenceTTL = ttl;
3101 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3103 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3105 presenceState = OC_PRESENCE_INITIALIZED;
3107 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3109 CAToken_t caToken = NULL;
3110 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3111 if (caResult != CA_STATUS_OK)
3113 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3114 CADestroyToken(caToken);
3115 return OC_STACK_ERROR;
3118 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3119 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3120 CADestroyToken(caToken);
3123 // Each time OCStartPresence is called
3124 // a different random 32-bit integer number is used
3125 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3127 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3128 OC_PRESENCE_TRIGGER_CREATE);
3131 OCStackResult OCStopPresence()
3133 OCStackResult result = OC_STACK_ERROR;
3135 if(presenceResource.handle)
3137 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3139 // make resource inactive
3140 result = OCChangeResourceProperty(
3141 &(((OCResource *) presenceResource.handle)->resourceProperties),
3145 if(result != OC_STACK_OK)
3148 "Changing the presence resource properties to ACTIVE not successful");
3152 return SendStopNotification();
3156 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3157 void* callbackParameter)
3159 defaultDeviceHandler = entityHandler;
3160 defaultDeviceHandlerCallbackParameter = callbackParameter;
3165 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3167 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3169 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3171 if (validatePlatformInfo(platformInfo))
3173 return SavePlatformInfo(platformInfo);
3177 return OC_STACK_INVALID_PARAM;
3182 return OC_STACK_ERROR;
3186 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3188 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3190 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3192 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3193 return OC_STACK_INVALID_PARAM;
3196 if (deviceInfo.types)
3198 OCStringLL *type = deviceInfo.types;
3199 OCResource *resource = findResource((OCResource *) deviceResource);
3202 return OC_STACK_INVALID_PARAM;
3207 OCBindResourceTypeToResource(deviceResource, type->value);
3211 return SaveDeviceInfo(deviceInfo);
3214 OCStackResult OCCreateResource(OCResourceHandle *handle,
3215 const char *resourceTypeName,
3216 const char *resourceInterfaceName,
3217 const char *uri, OCEntityHandler entityHandler,
3218 void* callbackParam,
3219 uint8_t resourceProperties)
3222 OCResource *pointer = NULL;
3223 OCStackResult result = OC_STACK_ERROR;
3225 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3227 if(myStackMode == OC_CLIENT)
3229 return OC_STACK_INVALID_PARAM;
3231 // Validate parameters
3232 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3234 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3235 return OC_STACK_INVALID_URI;
3237 // Is it presented during resource discovery?
3238 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3240 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3241 return OC_STACK_INVALID_PARAM;
3244 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3246 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3250 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3252 // Make sure resourceProperties bitmask has allowed properties specified
3253 if (resourceProperties
3254 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3255 OC_EXPLICIT_DISCOVERABLE
3264 OIC_LOG(ERROR, TAG, "Invalid property");
3265 return OC_STACK_INVALID_PARAM;
3268 // If the headResource is NULL, then no resources have been created...
3269 pointer = headResource;
3272 // At least one resources is in the resource list, so we need to search for
3273 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3276 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3278 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3279 return OC_STACK_INVALID_PARAM;
3281 pointer = pointer->next;
3284 // Create the pointer and insert it into the resource list
3285 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3288 result = OC_STACK_NO_MEMORY;
3291 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3293 insertResource(pointer);
3296 pointer->uri = OICStrdup(uri);
3299 result = OC_STACK_NO_MEMORY;
3303 // Set properties. Set OC_ACTIVE
3304 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3307 // Add the resourcetype to the resource
3308 result = BindResourceTypeToResource(pointer, resourceTypeName);
3309 if (result != OC_STACK_OK)
3311 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3315 // Add the resourceinterface to the resource
3316 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3317 if (result != OC_STACK_OK)
3319 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3323 // If an entity handler has been passed, attach it to the newly created
3324 // resource. Otherwise, set the default entity handler.
3327 pointer->entityHandler = entityHandler;
3328 pointer->entityHandlerCallbackParam = callbackParam;
3332 pointer->entityHandler = defaultResourceEHandler;
3333 pointer->entityHandlerCallbackParam = NULL;
3336 // Initialize a pointer indicating child resources in case of collection
3337 pointer->rsrcChildResourcesHead = NULL;
3340 result = OC_STACK_OK;
3342 #ifdef WITH_PRESENCE
3343 if (presenceResource.handle)
3345 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3346 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3350 if (result != OC_STACK_OK)
3352 // Deep delete of resource and other dynamic elements that it contains
3353 deleteResource(pointer);
3358 OCStackResult OCBindResource(
3359 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3361 OCResource *resource = NULL;
3362 OCChildResource *tempChildResource = NULL;
3363 OCChildResource *newChildResource = NULL;
3365 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3367 // Validate parameters
3368 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3369 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3370 // Container cannot contain itself
3371 if (collectionHandle == resourceHandle)
3373 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3374 return OC_STACK_INVALID_PARAM;
3377 // Use the handle to find the resource in the resource linked list
3378 resource = findResource((OCResource *) collectionHandle);
3381 OIC_LOG(ERROR, TAG, "Collection handle not found");
3382 return OC_STACK_INVALID_PARAM;
3385 // Look for an open slot to add add the child resource.
3386 // If found, add it and return success
3388 tempChildResource = resource->rsrcChildResourcesHead;
3390 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3392 // TODO: what if one of child resource was deregistered without unbinding?
3393 tempChildResource = tempChildResource->next;
3396 // Do memory allocation for child resource
3397 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3398 if(!newChildResource)
3400 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3401 return OC_STACK_ERROR;
3404 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3405 newChildResource->next = NULL;
3407 if(!resource->rsrcChildResourcesHead)
3409 resource->rsrcChildResourcesHead = newChildResource;
3412 tempChildResource->next = newChildResource;
3415 OIC_LOG(INFO, TAG, "resource bound");
3417 #ifdef WITH_PRESENCE
3418 if (presenceResource.handle)
3420 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3421 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3422 OC_PRESENCE_TRIGGER_CHANGE);
3429 OCStackResult OCUnBindResource(
3430 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3432 OCResource *resource = NULL;
3433 OCChildResource *tempChildResource = NULL;
3434 OCChildResource *tempLastChildResource = NULL;
3436 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3438 // Validate parameters
3439 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3440 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3441 // Container cannot contain itself
3442 if (collectionHandle == resourceHandle)
3444 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3445 return OC_STACK_INVALID_PARAM;
3448 // Use the handle to find the resource in the resource linked list
3449 resource = findResource((OCResource *) collectionHandle);
3452 OIC_LOG(ERROR, TAG, "Collection handle not found");
3453 return OC_STACK_INVALID_PARAM;
3456 // Look for an open slot to add add the child resource.
3457 // If found, add it and return success
3458 if(!resource->rsrcChildResourcesHead)
3460 OIC_LOG(INFO, TAG, "resource not found in collection");
3462 // Unable to add resourceHandle, so return error
3463 return OC_STACK_ERROR;
3467 tempChildResource = resource->rsrcChildResourcesHead;
3469 while (tempChildResource)
3471 if(tempChildResource->rsrcResource == resourceHandle)
3473 // if resource going to be unbinded is the head one.
3474 if( tempChildResource == resource->rsrcChildResourcesHead )
3476 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3477 OICFree(resource->rsrcChildResourcesHead);
3478 resource->rsrcChildResourcesHead = temp;
3483 OCChildResource *temp = tempChildResource->next;
3484 OICFree(tempChildResource);
3485 tempLastChildResource->next = temp;
3489 OIC_LOG(INFO, TAG, "resource unbound");
3491 // Send notification when resource is unbounded successfully.
3492 #ifdef WITH_PRESENCE
3493 if (presenceResource.handle)
3495 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3496 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3497 OC_PRESENCE_TRIGGER_CHANGE);
3500 tempChildResource = NULL;
3501 tempLastChildResource = NULL;
3507 tempLastChildResource = tempChildResource;
3508 tempChildResource = tempChildResource->next;
3511 OIC_LOG(INFO, TAG, "resource not found in collection");
3513 tempChildResource = NULL;
3514 tempLastChildResource = NULL;
3516 // Unable to add resourceHandle, so return error
3517 return OC_STACK_ERROR;
3520 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3522 if (!resourceItemName)
3526 // Per RFC 6690 only registered values must follow the first rule below.
3527 // At this point in time the only values registered begin with "core", and
3528 // all other values are specified as opaque strings where multiple values
3529 // are separated by a space.
3530 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3532 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3534 if (resourceItemName[index] != '.'
3535 && resourceItemName[index] != '-'
3536 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3537 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3545 for (size_t index = 0; resourceItemName[index]; ++index)
3547 if (resourceItemName[index] == ' '
3548 || resourceItemName[index] == '\t'
3549 || resourceItemName[index] == '\r'
3550 || resourceItemName[index] == '\n')
3560 OCStackResult BindResourceTypeToResource(OCResource* resource,
3561 const char *resourceTypeName)
3563 OCResourceType *pointer = NULL;
3565 OCStackResult result = OC_STACK_ERROR;
3567 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3569 if (!ValidateResourceTypeInterface(resourceTypeName))
3571 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3572 return OC_STACK_INVALID_PARAM;
3575 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3578 result = OC_STACK_NO_MEMORY;
3582 str = OICStrdup(resourceTypeName);
3585 result = OC_STACK_NO_MEMORY;
3588 pointer->resourcetypename = str;
3589 pointer->next = NULL;
3591 insertResourceType(resource, pointer);
3592 result = OC_STACK_OK;
3595 if (result != OC_STACK_OK)
3604 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3605 const char *resourceInterfaceName)
3607 OCResourceInterface *pointer = NULL;
3609 OCStackResult result = OC_STACK_ERROR;
3611 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3613 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3615 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3616 return OC_STACK_INVALID_PARAM;
3619 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3621 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3624 result = OC_STACK_NO_MEMORY;
3628 str = OICStrdup(resourceInterfaceName);
3631 result = OC_STACK_NO_MEMORY;
3634 pointer->name = str;
3636 // Bind the resourceinterface to the resource
3637 insertResourceInterface(resource, pointer);
3639 result = OC_STACK_OK;
3642 if (result != OC_STACK_OK)
3651 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3652 const char *resourceTypeName)
3655 OCStackResult result = OC_STACK_ERROR;
3656 OCResource *resource = NULL;
3658 resource = findResource((OCResource *) handle);
3661 OIC_LOG(ERROR, TAG, "Resource not found");
3662 return OC_STACK_ERROR;
3665 result = BindResourceTypeToResource(resource, resourceTypeName);
3667 #ifdef WITH_PRESENCE
3668 if(presenceResource.handle)
3670 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3671 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3678 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3679 const char *resourceInterfaceName)
3682 OCStackResult result = OC_STACK_ERROR;
3683 OCResource *resource = NULL;
3685 resource = findResource((OCResource *) handle);
3688 OIC_LOG(ERROR, TAG, "Resource not found");
3689 return OC_STACK_ERROR;
3692 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3694 #ifdef WITH_PRESENCE
3695 if (presenceResource.handle)
3697 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3698 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3705 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3707 OCResource *pointer = headResource;
3709 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3713 *numResources = *numResources + 1;
3714 pointer = pointer->next;
3719 OCResourceHandle OCGetResourceHandle(uint8_t index)
3721 OCResource *pointer = headResource;
3723 for( uint8_t i = 0; i < index && pointer; ++i)
3725 pointer = pointer->next;
3727 return (OCResourceHandle) pointer;
3730 OCStackResult OCDeleteResource(OCResourceHandle handle)
3734 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3735 return OC_STACK_INVALID_PARAM;
3738 OCResource *resource = findResource((OCResource *) handle);
3739 if (resource == NULL)
3741 OIC_LOG(ERROR, TAG, "Resource not found");
3742 return OC_STACK_NO_RESOURCE;
3745 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3747 OIC_LOG(ERROR, TAG, "Error deleting resource");
3748 return OC_STACK_ERROR;
3754 const char *OCGetResourceUri(OCResourceHandle handle)
3756 OCResource *resource = NULL;
3758 resource = findResource((OCResource *) handle);
3761 return resource->uri;
3763 return (const char *) NULL;
3766 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3768 OCResource *resource = NULL;
3770 resource = findResource((OCResource *) handle);
3773 return resource->resourceProperties;
3775 return (OCResourceProperty)-1;
3778 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3779 uint8_t *numResourceTypes)
3781 OCResource *resource = NULL;
3782 OCResourceType *pointer = NULL;
3784 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3785 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3787 *numResourceTypes = 0;
3789 resource = findResource((OCResource *) handle);
3792 pointer = resource->rsrcType;
3795 *numResourceTypes = *numResourceTypes + 1;
3796 pointer = pointer->next;
3802 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3804 OCResourceType *resourceType = NULL;
3806 resourceType = findResourceTypeAtIndex(handle, index);
3809 return resourceType->resourcetypename;
3811 return (const char *) NULL;
3814 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3815 uint8_t *numResourceInterfaces)
3817 OCResourceInterface *pointer = NULL;
3818 OCResource *resource = NULL;
3820 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3821 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3823 *numResourceInterfaces = 0;
3824 resource = findResource((OCResource *) handle);
3827 pointer = resource->rsrcInterface;
3830 *numResourceInterfaces = *numResourceInterfaces + 1;
3831 pointer = pointer->next;
3837 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3839 OCResourceInterface *resourceInterface = NULL;
3841 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3842 if (resourceInterface)
3844 return resourceInterface->name;
3846 return (const char *) NULL;
3849 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3852 OCResource *resource = NULL;
3853 OCChildResource *tempChildResource = NULL;
3856 resource = findResource((OCResource *) collectionHandle);
3862 tempChildResource = resource->rsrcChildResourcesHead;
3864 while(tempChildResource)
3868 return tempChildResource->rsrcResource;
3871 tempChildResource = tempChildResource->next;
3874 // In this case, the number of resource handles in the collection exceeds the index
3875 tempChildResource = NULL;
3879 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3880 OCEntityHandler entityHandler,
3881 void* callbackParam)
3883 OCResource *resource = NULL;
3885 // Validate parameters
3886 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3888 // Use the handle to find the resource in the resource linked list
3889 resource = findResource((OCResource *)handle);
3892 OIC_LOG(ERROR, TAG, "Resource not found");
3893 return OC_STACK_ERROR;
3897 resource->entityHandler = entityHandler;
3898 resource->entityHandlerCallbackParam = callbackParam;
3900 #ifdef WITH_PRESENCE
3901 if (presenceResource.handle)
3903 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3904 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3911 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3913 OCResource *resource = NULL;
3915 resource = findResource((OCResource *)handle);
3918 OIC_LOG(ERROR, TAG, "Resource not found");
3923 return resource->entityHandler;
3926 void incrementSequenceNumber(OCResource * resPtr)
3928 // Increment the sequence number
3929 resPtr->sequenceNum += 1;
3930 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3932 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3937 #ifdef WITH_PRESENCE
3938 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3939 OCPresenceTrigger trigger)
3941 OCResource *resPtr = NULL;
3942 OCStackResult result = OC_STACK_ERROR;
3943 OCMethod method = OC_REST_PRESENCE;
3944 uint32_t maxAge = 0;
3945 resPtr = findResource((OCResource *) presenceResource.handle);
3948 return OC_STACK_NO_RESOURCE;
3951 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3953 maxAge = presenceResource.presenceTTL;
3955 result = SendAllObserverNotification(method, resPtr, maxAge,
3956 trigger, resourceType, OC_LOW_QOS);
3962 OCStackResult SendStopNotification()
3964 OCResource *resPtr = NULL;
3965 OCStackResult result = OC_STACK_ERROR;
3966 OCMethod method = OC_REST_PRESENCE;
3967 resPtr = findResource((OCResource *) presenceResource.handle);
3970 return OC_STACK_NO_RESOURCE;
3973 // maxAge is 0. ResourceType is NULL.
3974 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3980 #endif // WITH_PRESENCE
3981 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3983 OCResource *resPtr = NULL;
3984 OCStackResult result = OC_STACK_ERROR;
3985 OCMethod method = OC_REST_NOMETHOD;
3986 uint32_t maxAge = 0;
3988 OIC_LOG(INFO, TAG, "Notifying all observers");
3989 #ifdef WITH_PRESENCE
3990 if(handle == presenceResource.handle)
3994 #endif // WITH_PRESENCE
3995 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3997 // Verify that the resource exists
3998 resPtr = findResource ((OCResource *) handle);
4001 return OC_STACK_NO_RESOURCE;
4005 //only increment in the case of regular observing (not presence)
4006 incrementSequenceNumber(resPtr);
4007 method = OC_REST_OBSERVE;
4008 maxAge = MAX_OBSERVE_AGE;
4009 #ifdef WITH_PRESENCE
4010 result = SendAllObserverNotification (method, resPtr, maxAge,
4011 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4013 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4020 OCNotifyListOfObservers (OCResourceHandle handle,
4021 OCObservationId *obsIdList,
4022 uint8_t numberOfIds,
4023 const OCRepPayload *payload,
4024 OCQualityOfService qos)
4026 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4028 OCResource *resPtr = NULL;
4029 //TODO: we should allow the server to define this
4030 uint32_t maxAge = MAX_OBSERVE_AGE;
4032 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4033 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4034 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4036 resPtr = findResource ((OCResource *) handle);
4037 if (NULL == resPtr || myStackMode == OC_CLIENT)
4039 return OC_STACK_NO_RESOURCE;
4043 incrementSequenceNumber(resPtr);
4045 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4046 payload, maxAge, qos));
4049 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4051 OCStackResult result = OC_STACK_ERROR;
4052 OCServerRequest *serverRequest = NULL;
4054 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4056 // Validate input parameters
4057 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4058 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4061 // Get pointer to request info
4062 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4065 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4066 result = serverRequest->ehResponseHandler(ehResponse);
4072 //#ifdef DIRECT_PAIRING
4073 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4075 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4076 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4078 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4082 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4085 const OCDPDev_t* OCGetDirectPairedDevices()
4087 return (const OCDPDev_t*)DPGetPairedDevices();
4090 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4091 OCDirectPairingCB resultCallback)
4093 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4094 if(NULL == peer || NULL == pinNumber)
4096 OIC_LOG(ERROR, TAG, "Invalid parameters");
4097 return OC_STACK_INVALID_PARAM;
4099 if (NULL == resultCallback)
4101 OIC_LOG(ERROR, TAG, "Invalid callback");
4102 return OC_STACK_INVALID_CALLBACK;
4105 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4106 pinNumber, (OCDirectPairingResultCB)resultCallback);
4108 //#endif // DIRECT_PAIRING
4110 //-----------------------------------------------------------------------------
4111 // Private internal function definitions
4112 //-----------------------------------------------------------------------------
4113 static OCDoHandle GenerateInvocationHandle()
4115 OCDoHandle handle = NULL;
4116 // Generate token here, it will be deleted when the transaction is deleted
4117 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4120 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4126 #ifdef WITH_PRESENCE
4127 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4128 OCResourceProperty resourceProperties, uint8_t enable)
4132 return OC_STACK_INVALID_PARAM;
4134 if (resourceProperties
4135 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4137 OIC_LOG(ERROR, TAG, "Invalid property");
4138 return OC_STACK_INVALID_PARAM;
4142 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4146 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4152 OCStackResult initResources()
4154 OCStackResult result = OC_STACK_OK;
4156 headResource = NULL;
4157 tailResource = NULL;
4158 // Init Virtual Resources
4159 #ifdef WITH_PRESENCE
4160 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4162 result = OCCreateResource(&presenceResource.handle,
4163 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4165 OC_RSRVD_PRESENCE_URI,
4169 //make resource inactive
4170 result = OCChangeResourceProperty(
4171 &(((OCResource *) presenceResource.handle)->resourceProperties),
4174 #ifndef WITH_ARDUINO
4175 if (result == OC_STACK_OK)
4177 result = SRMInitSecureResources();
4181 if(result == OC_STACK_OK)
4183 CreateResetProfile();
4184 result = OCCreateResource(&deviceResource,
4185 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4186 OC_RSRVD_INTERFACE_DEFAULT,
4187 OC_RSRVD_DEVICE_URI,
4191 if(result == OC_STACK_OK)
4193 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4194 OC_RSRVD_INTERFACE_READ);
4198 if(result == OC_STACK_OK)
4200 result = OCCreateResource(&platformResource,
4201 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4202 OC_RSRVD_INTERFACE_DEFAULT,
4203 OC_RSRVD_PLATFORM_URI,
4207 if(result == OC_STACK_OK)
4209 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4210 OC_RSRVD_INTERFACE_READ);
4217 void insertResource(OCResource *resource)
4221 headResource = resource;
4222 tailResource = resource;
4226 tailResource->next = resource;
4227 tailResource = resource;
4229 resource->next = NULL;
4232 OCResource *findResource(OCResource *resource)
4234 OCResource *pointer = headResource;
4238 if (pointer == resource)
4242 pointer = pointer->next;
4247 void deleteAllResources()
4249 OCResource *pointer = headResource;
4250 OCResource *temp = NULL;
4254 temp = pointer->next;
4255 #ifdef WITH_PRESENCE
4256 if (pointer != (OCResource *) presenceResource.handle)
4258 #endif // WITH_PRESENCE
4259 deleteResource(pointer);
4260 #ifdef WITH_PRESENCE
4262 #endif // WITH_PRESENCE
4265 memset(&platformResource, 0, sizeof(platformResource));
4266 memset(&deviceResource, 0, sizeof(deviceResource));
4268 memset(&brokerResource, 0, sizeof(brokerResource));
4271 SRMDeInitSecureResources();
4273 #ifdef WITH_PRESENCE
4274 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4275 // presence notification attributed to their deletion to be processed.
4276 deleteResource((OCResource *) presenceResource.handle);
4277 memset(&presenceResource, 0, sizeof(presenceResource));
4278 #endif // WITH_PRESENCE
4281 OCStackResult deleteResource(OCResource *resource)
4283 OCResource *prev = NULL;
4284 OCResource *temp = NULL;
4287 OIC_LOG(DEBUG,TAG,"resource is NULL");
4288 return OC_STACK_INVALID_PARAM;
4291 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4293 temp = headResource;
4296 if (temp == resource)
4298 // Invalidate all Resource Properties.
4299 resource->resourceProperties = (OCResourceProperty) 0;
4300 #ifdef WITH_PRESENCE
4301 if(resource != (OCResource *) presenceResource.handle)
4303 #endif // WITH_PRESENCE
4304 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4305 #ifdef WITH_PRESENCE
4308 if(presenceResource.handle)
4310 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4311 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4314 // Only resource in list.
4315 if (temp == headResource && temp == tailResource)
4317 headResource = NULL;
4318 tailResource = NULL;
4321 else if (temp == headResource)
4323 headResource = temp->next;
4326 else if (temp == tailResource)
4328 tailResource = prev;
4329 tailResource->next = NULL;
4333 prev->next = temp->next;
4336 deleteResourceElements(temp);
4347 return OC_STACK_ERROR;
4350 void deleteResourceElements(OCResource *resource)
4357 OICFree(resource->uri);
4358 deleteResourceType(resource->rsrcType);
4359 deleteResourceInterface(resource->rsrcInterface);
4362 void deleteResourceType(OCResourceType *resourceType)
4364 OCResourceType *pointer = resourceType;
4365 OCResourceType *next = NULL;
4369 next = pointer->next;
4370 OICFree(pointer->resourcetypename);
4376 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4378 OCResourceInterface *pointer = resourceInterface;
4379 OCResourceInterface *next = NULL;
4383 next = pointer->next;
4384 OICFree(pointer->name);
4390 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4392 OCResourceType *pointer = NULL;
4393 OCResourceType *previous = NULL;
4394 if (!resource || !resourceType)
4398 // resource type list is empty.
4399 else if (!resource->rsrcType)
4401 resource->rsrcType = resourceType;
4405 pointer = resource->rsrcType;
4409 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4411 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4412 OICFree(resourceType->resourcetypename);
4413 OICFree(resourceType);
4417 pointer = pointer->next;
4422 previous->next = resourceType;
4425 resourceType->next = NULL;
4427 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4430 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4432 OCResource *resource = NULL;
4433 OCResourceType *pointer = NULL;
4435 // Find the specified resource
4436 resource = findResource((OCResource *) handle);
4442 // Make sure a resource has a resourcetype
4443 if (!resource->rsrcType)
4448 // Iterate through the list
4449 pointer = resource->rsrcType;
4450 for(uint8_t i = 0; i< index && pointer; ++i)
4452 pointer = pointer->next;
4457 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4459 if(resourceTypeList && resourceTypeName)
4461 OCResourceType * rtPointer = resourceTypeList;
4462 while(resourceTypeName && rtPointer)
4464 if(rtPointer->resourcetypename &&
4465 strcmp(resourceTypeName, (const char *)
4466 (rtPointer->resourcetypename)) == 0)
4470 rtPointer = rtPointer->next;
4478 * Insert a new interface into interface linked list only if not already present.
4479 * If alredy present, 2nd arg is free'd.
4480 * Default interface will always be first if present.
4482 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4484 OCResourceInterface *pointer = NULL;
4485 OCResourceInterface *previous = NULL;
4487 newInterface->next = NULL;
4489 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4491 if (!*firstInterface)
4493 // If first interface is not oic.if.baseline, by default add it as first interface type.
4494 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4496 *firstInterface = newInterface;
4500 OCStackResult result = BindResourceInterfaceToResource(resource,
4501 OC_RSRVD_INTERFACE_DEFAULT);
4502 if (result != OC_STACK_OK)
4504 OICFree(newInterface->name);
4505 OICFree(newInterface);
4508 if (*firstInterface)
4510 (*firstInterface)->next = newInterface;
4514 // If once add oic.if.baseline, later too below code take care of freeing memory.
4515 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4517 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4519 OICFree(newInterface->name);
4520 OICFree(newInterface);
4523 // This code will not hit anymore, keeping
4526 newInterface->next = *firstInterface;
4527 *firstInterface = newInterface;
4532 pointer = *firstInterface;
4535 if (strcmp(newInterface->name, pointer->name) == 0)
4537 OICFree(newInterface->name);
4538 OICFree(newInterface);
4542 pointer = pointer->next;
4547 previous->next = newInterface;
4552 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4555 OCResource *resource = NULL;
4556 OCResourceInterface *pointer = NULL;
4558 // Find the specified resource
4559 resource = findResource((OCResource *) handle);
4565 // Make sure a resource has a resourceinterface
4566 if (!resource->rsrcInterface)
4571 // Iterate through the list
4572 pointer = resource->rsrcInterface;
4574 for (uint8_t i = 0; i < index && pointer; ++i)
4576 pointer = pointer->next;
4582 * This function splits the uri using the '?' delimiter.
4583 * "uriWithoutQuery" is the block of characters between the beginning
4584 * till the delimiter or '\0' which ever comes first.
4585 * "query" is whatever is to the right of the delimiter if present.
4586 * No delimiter sets the query to NULL.
4587 * If either are present, they will be malloc'ed into the params 2, 3.
4588 * The first param, *uri is left untouched.
4590 * NOTE: This function does not account for whitespace at the end of the uri NOR
4591 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4592 * part of the query.
4594 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4598 return OC_STACK_INVALID_URI;
4600 if(!query || !uriWithoutQuery)
4602 return OC_STACK_INVALID_PARAM;
4606 *uriWithoutQuery = NULL;
4608 size_t uriWithoutQueryLen = 0;
4609 size_t queryLen = 0;
4610 size_t uriLen = strlen(uri);
4612 char *pointerToDelimiter = strstr(uri, "?");
4614 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4615 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4617 if (uriWithoutQueryLen)
4619 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4620 if (!*uriWithoutQuery)
4624 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4628 *query = (char *) OICCalloc(queryLen + 1, 1);
4631 OICFree(*uriWithoutQuery);
4632 *uriWithoutQuery = NULL;
4635 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4641 return OC_STACK_NO_MEMORY;
4644 static const OicUuid_t* OCGetServerInstanceID(void)
4646 static bool generated = false;
4647 static OicUuid_t sid;
4653 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4655 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4662 const char* OCGetServerInstanceIDString(void)
4664 static bool generated = false;
4665 static char sidStr[UUID_STRING_SIZE];
4672 const OicUuid_t *sid = OCGetServerInstanceID();
4673 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4675 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4683 CAResult_t OCSelectNetwork()
4685 CAResult_t retResult = CA_STATUS_FAILED;
4686 CAResult_t caResult = CA_STATUS_OK;
4688 CATransportAdapter_t connTypes[] = {
4690 CA_ADAPTER_RFCOMM_BTEDR,
4691 CA_ADAPTER_GATT_BTLE,
4694 ,CA_ADAPTER_REMOTE_ACCESS
4701 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4703 for(int i = 0; i<numConnTypes; i++)
4705 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4706 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4708 caResult = CASelectNetwork(connTypes[i]);
4709 if(caResult == CA_STATUS_OK)
4711 retResult = CA_STATUS_OK;
4716 if(retResult != CA_STATUS_OK)
4718 return caResult; // Returns error of appropriate transport that failed fatally.
4724 OCStackResult CAResultToOCResult(CAResult_t caResult)
4730 case CA_STATUS_INVALID_PARAM:
4731 return OC_STACK_INVALID_PARAM;
4732 case CA_ADAPTER_NOT_ENABLED:
4733 return OC_STACK_ADAPTER_NOT_ENABLED;
4734 case CA_SERVER_STARTED_ALREADY:
4736 case CA_SERVER_NOT_STARTED:
4737 return OC_STACK_ERROR;
4738 case CA_DESTINATION_NOT_REACHABLE:
4739 return OC_STACK_COMM_ERROR;
4740 case CA_SOCKET_OPERATION_FAILED:
4741 return OC_STACK_COMM_ERROR;
4742 case CA_SEND_FAILED:
4743 return OC_STACK_COMM_ERROR;
4744 case CA_RECEIVE_FAILED:
4745 return OC_STACK_COMM_ERROR;
4746 case CA_MEMORY_ALLOC_FAILED:
4747 return OC_STACK_NO_MEMORY;
4748 case CA_REQUEST_TIMEOUT:
4749 return OC_STACK_TIMEOUT;
4750 case CA_DESTINATION_DISCONNECTED:
4751 return OC_STACK_COMM_ERROR;
4752 case CA_STATUS_FAILED:
4753 return OC_STACK_ERROR;
4754 case CA_NOT_SUPPORTED:
4755 return OC_STACK_NOTIMPL;
4757 return OC_STACK_ERROR;
4761 bool OCResultToSuccess(OCStackResult ocResult)
4766 case OC_STACK_RESOURCE_CREATED:
4767 case OC_STACK_RESOURCE_DELETED:
4768 case OC_STACK_CONTINUE:
4769 case OC_STACK_RESOURCE_CHANGED:
4776 #if defined(RD_CLIENT) || defined(RD_SERVER)
4777 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
4779 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4781 OCResource *resource = NULL;
4783 resource = findResource((OCResource *) handle);
4786 OIC_LOG(ERROR, TAG, "Resource not found");
4787 return OC_STACK_ERROR;
4790 resource->ins = ins;
4795 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
4799 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
4803 OCResource *pointer = headResource;
4807 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
4809 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
4812 pointer = pointer->next;
4817 OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
4819 OCResource *resource = NULL;
4821 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4822 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
4824 resource = findResource((OCResource *) handle);
4827 *ins = resource->ins;
4830 return OC_STACK_ERROR;