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 RFC6874.
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 /** @todo Use a max IPv6 string length instead of CA_MAX_URI_LENGTH. */
879 #define ENCODE_MAX_INPUT_LENGTH CA_MAX_URI_LENGTH
881 size_t inputLength = strnlen(inputAddress, ENCODE_MAX_INPUT_LENGTH);
883 if (inputLength >= ENCODE_MAX_INPUT_LENGTH)
886 "encodeAddressForRFC6874 failed: Invalid input string: too long/unterminated!");
887 return OC_STACK_INVALID_PARAM;
890 // inputSize includes the null terminator
891 size_t inputSize = inputLength + 1;
893 if (inputSize > outputSize)
895 OIC_LOG_V(ERROR, TAG,
896 "encodeAddressForRFC6874 failed: "
897 "outputSize (%d) < inputSize (%d)",
898 outputSize, inputSize);
900 return OC_STACK_ERROR;
903 char* percentChar = strchr(inputAddress, '%');
905 // If there is no '%' character, then no change is required to the string.
906 if (NULL == percentChar)
908 OICStrcpy(outputAddress, outputSize, inputAddress);
912 const char* addressPart = &inputAddress[0];
913 const char* scopeIdPart = percentChar + 1;
915 // Sanity check to make sure this string doesn't have more '%' characters
916 if (NULL != strchr(scopeIdPart, '%'))
918 return OC_STACK_ERROR;
921 // If no string follows the first '%', then the input was invalid.
922 if (scopeIdPart[0] == '\0')
924 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
925 return OC_STACK_ERROR;
928 // Check to see if the string is already encoded
929 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
931 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
932 return OC_STACK_ERROR;
935 // Fail if we don't have room for encoded string's two additional chars
936 if (outputSize < (inputSize + 2))
938 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
939 return OC_STACK_ERROR;
942 // Restore the null terminator with an escaped '%' character, per RFC6874
943 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
944 strcat(outputAddress, "%25");
945 strcat(outputAddress, scopeIdPart);
951 * The cononical presence allows constructed URIs to be string compared.
953 * requestUri must be a char array of size CA_MAX_URI_LENGTH
955 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
958 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
959 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
960 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
962 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
964 if (ep->adapter == CA_ADAPTER_IP)
966 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
968 if ('\0' == ep->addr[0]) // multicast
970 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
974 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
976 OCStackResult result = encodeAddressForRFC6874(addressEncoded,
977 sizeof(addressEncoded),
980 if (OC_STACK_OK != result)
985 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
986 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
991 if ('\0' == ep->addr[0]) // multicast
993 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
994 ep->port = OC_MULTICAST_PORT;
996 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
997 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1001 // might work for other adapters (untested, but better than nothing)
1002 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1003 OC_RSRVD_PRESENCE_URI);
1007 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1008 const CAResponseInfo_t *responseInfo)
1010 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1011 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1013 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1014 ClientCB * cbNode = NULL;
1015 char *resourceTypeName = NULL;
1016 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1017 OCStackResult result = OC_STACK_ERROR;
1018 uint32_t maxAge = 0;
1020 char presenceUri[CA_MAX_URI_LENGTH];
1022 int presenceSubscribe = 0;
1023 int multicastPresenceSubscribe = 0;
1025 if (responseInfo->result != CA_CONTENT)
1027 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1028 return OC_STACK_ERROR;
1031 // check for unicast presence
1032 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
1033 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1035 return OC_STACK_INVALID_URI;
1038 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1041 presenceSubscribe = 1;
1045 // check for multiicast presence
1046 CAEndpoint_t ep = { .adapter = endpoint->adapter,
1047 .flags = endpoint->flags };
1049 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
1051 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1054 multicastPresenceSubscribe = 1;
1058 if (!presenceSubscribe && !multicastPresenceSubscribe)
1060 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1064 response.payload = NULL;
1065 response.result = OC_STACK_OK;
1067 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1068 FixUpClientResponse(&response);
1070 if (responseInfo->info.payload)
1072 result = OCParsePayload(&response.payload,
1073 PAYLOAD_TYPE_PRESENCE,
1074 responseInfo->info.payload,
1075 responseInfo->info.payloadSize);
1077 if(result != OC_STACK_OK)
1079 OIC_LOG(ERROR, TAG, "Presence parse failed");
1082 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1084 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1085 result = OC_STACK_ERROR;
1088 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1089 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1090 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1093 if (presenceSubscribe)
1095 if(cbNode->sequenceNumber == response.sequenceNumber)
1097 OIC_LOG(INFO, TAG, "No presence change");
1098 ResetPresenceTTL(cbNode, maxAge);
1099 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1105 OIC_LOG(INFO, TAG, "Stopping presence");
1106 response.result = OC_STACK_PRESENCE_STOPPED;
1107 if(cbNode->presence)
1109 OICFree(cbNode->presence->timeOut);
1110 OICFree(cbNode->presence);
1111 cbNode->presence = NULL;
1116 if(!cbNode->presence)
1118 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1120 if(!(cbNode->presence))
1122 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1123 result = OC_STACK_NO_MEMORY;
1127 VERIFY_NON_NULL_V(cbNode->presence);
1128 cbNode->presence->timeOut = NULL;
1129 cbNode->presence->timeOut = (uint32_t *)
1130 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1131 if(!(cbNode->presence->timeOut)){
1133 "Could not allocate memory for cbNode->presence->timeOut");
1134 OICFree(cbNode->presence);
1135 result = OC_STACK_NO_MEMORY;
1140 ResetPresenceTTL(cbNode, maxAge);
1142 cbNode->sequenceNumber = response.sequenceNumber;
1144 // Ensure that a filter is actually applied.
1145 if( resourceTypeName && cbNode->filterResourceType)
1147 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1156 // This is the multicast case
1157 OCMulticastNode* mcNode = NULL;
1158 mcNode = GetMCPresenceNode(presenceUri);
1162 if(mcNode->nonce == response.sequenceNumber)
1164 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1167 mcNode->nonce = response.sequenceNumber;
1171 OIC_LOG(INFO, TAG, "Stopping presence");
1172 response.result = OC_STACK_PRESENCE_STOPPED;
1177 char* uri = OICStrdup(presenceUri);
1181 "No Memory for URI to store in the presence node");
1182 result = OC_STACK_NO_MEMORY;
1186 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1187 if(result == OC_STACK_NO_MEMORY)
1190 "No Memory for Multicast Presence Node");
1194 // presence node now owns uri
1197 // Ensure that a filter is actually applied.
1198 if(resourceTypeName && cbNode->filterResourceType)
1200 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1207 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1209 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1211 FindAndDeleteClientCB(cbNode);
1215 OCPayloadDestroy(response.payload);
1219 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1221 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1223 if(responseInfo->info.resourceUri &&
1224 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1226 HandlePresenceResponse(endPoint, responseInfo);
1230 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1231 responseInfo->info.tokenLength, NULL, NULL);
1233 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1234 responseInfo->info.tokenLength);
1238 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1239 if(responseInfo->result == CA_EMPTY)
1241 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1242 // We do not have a case for the client to receive a RESET
1243 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1245 //This is the case of receiving an ACK on a request to a slow resource!
1246 OIC_LOG(INFO, TAG, "This is a pure ACK");
1247 //TODO: should we inform the client
1248 // app that at least the request was received at the server?
1251 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1253 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1254 OIC_LOG(INFO, TAG, "Calling into application address space");
1256 OCClientResponse response =
1257 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1258 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1259 FixUpClientResponse(&response);
1260 response.resourceUri = responseInfo->info.resourceUri;
1261 memcpy(response.identity.id, responseInfo->info.identity.id,
1262 sizeof (response.identity.id));
1263 response.identity.id_length = responseInfo->info.identity.id_length;
1265 response.result = CAResponseToOCStackResult(responseInfo->result);
1266 cbNode->callBack(cbNode->context,
1267 cbNode->handle, &response);
1268 FindAndDeleteClientCB(cbNode);
1272 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1273 OIC_LOG(INFO, TAG, "Calling into application address space");
1275 OCClientResponse response =
1276 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1277 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1278 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1279 FixUpClientResponse(&response);
1280 response.resourceUri = responseInfo->info.resourceUri;
1281 memcpy(response.identity.id, responseInfo->info.identity.id,
1282 sizeof (response.identity.id));
1283 response.identity.id_length = responseInfo->info.identity.id_length;
1285 response.result = CAResponseToOCStackResult(responseInfo->result);
1287 if(responseInfo->info.payload &&
1288 responseInfo->info.payloadSize)
1290 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1291 // check the security resource
1292 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1294 type = PAYLOAD_TYPE_SECURITY;
1296 else if (cbNode->method == OC_REST_DISCOVER)
1298 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1299 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1301 type = PAYLOAD_TYPE_DISCOVERY;
1304 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1306 type = PAYLOAD_TYPE_DISCOVERY;
1309 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1311 type = PAYLOAD_TYPE_DEVICE;
1313 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1315 type = PAYLOAD_TYPE_PLATFORM;
1317 #ifdef ROUTING_GATEWAY
1318 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1320 type = PAYLOAD_TYPE_REPRESENTATION;
1323 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1325 type = PAYLOAD_TYPE_RD;
1328 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1330 type = PAYLOAD_TYPE_REPRESENTATION;
1335 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1336 cbNode->method, cbNode->requestUri);
1340 else if (cbNode->method == OC_REST_GET ||
1341 cbNode->method == OC_REST_PUT ||
1342 cbNode->method == OC_REST_POST ||
1343 cbNode->method == OC_REST_OBSERVE ||
1344 cbNode->method == OC_REST_OBSERVE_ALL ||
1345 cbNode->method == OC_REST_DELETE)
1347 char targetUri[MAX_URI_LENGTH];
1348 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1349 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1350 if (strcmp(targetUri, cbNode->requestUri) == 0)
1352 type = PAYLOAD_TYPE_RD;
1354 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1356 type = PAYLOAD_TYPE_PLATFORM;
1358 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1360 type = PAYLOAD_TYPE_DEVICE;
1362 if (type == PAYLOAD_TYPE_INVALID)
1364 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1365 cbNode->method, cbNode->requestUri);
1366 type = PAYLOAD_TYPE_REPRESENTATION;
1371 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1372 cbNode->method, cbNode->requestUri);
1376 if(OC_STACK_OK != OCParsePayload(&response.payload,
1378 responseInfo->info.payload,
1379 responseInfo->info.payloadSize))
1381 OIC_LOG(ERROR, TAG, "Error converting payload");
1382 OCPayloadDestroy(response.payload);
1387 response.numRcvdVendorSpecificHeaderOptions = 0;
1388 if(responseInfo->info.numOptions > 0)
1391 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1392 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1395 uint32_t observationOption;
1396 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1397 for (observationOption=0, i=0;
1398 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1402 (observationOption << 8) | optionData[i];
1404 response.sequenceNumber = observationOption;
1405 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1410 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1413 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1415 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1416 OCPayloadDestroy(response.payload);
1420 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1422 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1423 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1427 if (cbNode->method == OC_REST_OBSERVE &&
1428 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1429 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1430 response.sequenceNumber <= cbNode->sequenceNumber)
1432 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1433 response.sequenceNumber);
1437 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1440 cbNode->sequenceNumber = response.sequenceNumber;
1442 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1444 FindAndDeleteClientCB(cbNode);
1448 // To keep discovery callbacks active.
1449 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1450 MILLISECONDS_PER_SECOND);
1454 //Need to send ACK when the response is CON
1455 if(responseInfo->info.type == CA_MSG_CONFIRM)
1457 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1458 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1461 OCPayloadDestroy(response.payload);
1468 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1469 if(responseInfo->result == CA_EMPTY)
1471 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1472 if(responseInfo->info.type == CA_MSG_RESET)
1474 OIC_LOG(INFO, TAG, "This is a RESET");
1475 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1476 OC_OBSERVER_NOT_INTERESTED);
1478 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1480 OIC_LOG(INFO, TAG, "This is a pure ACK");
1481 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1482 OC_OBSERVER_STILL_INTERESTED);
1485 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1487 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1488 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1489 OC_OBSERVER_FAILED_COMM);
1494 if(!cbNode && !observer)
1496 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1497 || myStackMode == OC_GATEWAY)
1499 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1500 if(responseInfo->result == CA_EMPTY)
1502 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1506 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1507 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1508 CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1512 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1513 || myStackMode == OC_GATEWAY)
1515 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1516 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1518 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1519 responseInfo->info.messageId);
1521 if (responseInfo->info.type == CA_MSG_RESET)
1523 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1524 responseInfo->info.messageId);
1531 OIC_LOG(INFO, TAG, "Exit OCHandleResponse");
1534 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1536 VERIFY_NON_NULL_NR(endPoint, FATAL);
1537 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1539 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1541 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1542 #ifdef ROUTING_GATEWAY
1543 bool needRIHandling = false;
1545 * Routing manager is going to update either of endpoint or response or both.
1546 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1547 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1550 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1552 if(ret != OC_STACK_OK || !needRIHandling)
1554 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1560 * Put source in sender endpoint so that the next packet from application can be routed to
1561 * proper destination and remove "RM" coap header option before passing request / response to
1562 * RI as this option will make no sense to either RI or application.
1564 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1565 (uint8_t *) &(responseInfo->info.numOptions),
1566 (CAEndpoint_t *) endPoint);
1569 OCHandleResponse(endPoint, responseInfo);
1571 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1575 * This function handles error response from CA
1576 * code shall be added to handle the errors
1578 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1580 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1582 if (NULL == endPoint)
1584 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1588 if (NULL == errorInfo)
1590 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1594 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1595 errorInfo->info.tokenLength, NULL, NULL);
1598 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1599 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1600 FixUpClientResponse(&response);
1601 response.resourceUri = errorInfo->info.resourceUri;
1602 memcpy(response.identity.id, errorInfo->info.identity.id,
1603 sizeof (response.identity.id));
1604 response.identity.id_length = errorInfo->info.identity.id_length;
1605 response.result = CAResultToOCStackResult(errorInfo->result);
1607 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1608 FindAndDeleteClientCB(cbNode);
1611 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1615 * This function sends out Direct Stack Responses. These are responses that are not coming
1616 * from the application entity handler. These responses have no payload and are usually ACKs,
1617 * RESETs or some error conditions that were caught by the stack.
1619 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1620 const CAResponseResult_t responseResult, const CAMessageType_t type,
1621 const uint8_t numOptions, const CAHeaderOption_t *options,
1622 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1623 CADataType_t dataType)
1625 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1626 CAResponseInfo_t respInfo = {
1627 .result = responseResult
1629 respInfo.info.messageId = coapID;
1630 respInfo.info.numOptions = numOptions;
1632 if (respInfo.info.numOptions)
1634 respInfo.info.options =
1635 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1636 memcpy (respInfo.info.options, options,
1637 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1641 respInfo.info.payload = NULL;
1642 respInfo.info.token = token;
1643 respInfo.info.tokenLength = tokenLength;
1644 respInfo.info.type = type;
1645 respInfo.info.resourceUri = OICStrdup (resourceUri);
1646 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1647 respInfo.info.dataType = dataType;
1649 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1650 // Add the destination to route option from the endpoint->routeData.
1651 bool doPost = false;
1652 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1653 if(OC_STACK_OK != result)
1655 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1660 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1661 CARequestInfo_t reqInfo = {.method = CA_POST };
1662 /* The following initialization is not done in a single initializer block as in
1663 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1664 * does not have designated initalizers. This is a work-around for now.
1666 reqInfo.info.type = CA_MSG_NONCONFIRM;
1667 reqInfo.info.messageId = coapID;
1668 reqInfo.info.tokenLength = tokenLength;
1669 reqInfo.info.token = token;
1670 reqInfo.info.numOptions = respInfo.info.numOptions;
1671 reqInfo.info.payload = NULL;
1672 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1673 if (reqInfo.info.numOptions)
1675 reqInfo.info.options =
1676 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1677 if (NULL == reqInfo.info.options)
1679 OIC_LOG(ERROR, TAG, "Calloc failed");
1680 return OC_STACK_NO_MEMORY;
1682 memcpy (reqInfo.info.options, respInfo.info.options,
1683 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1686 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1687 OICFree (reqInfo.info.resourceUri);
1688 OICFree (reqInfo.info.options);
1689 OICFree (respInfo.info.resourceUri);
1690 OICFree (respInfo.info.options);
1691 if (CA_STATUS_OK != caResult)
1693 OIC_LOG(ERROR, TAG, "CASendRequest error");
1694 return CAResultToOCResult(caResult);
1700 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1702 // resourceUri in the info field is cloned in the CA layer and
1703 // thus ownership is still here.
1704 OICFree (respInfo.info.resourceUri);
1705 OICFree (respInfo.info.options);
1706 if(CA_STATUS_OK != caResult)
1708 OIC_LOG(ERROR, TAG, "CASendResponse error");
1709 return CAResultToOCResult(caResult);
1712 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1716 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1718 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1719 OCStackResult result = OC_STACK_ERROR;
1720 if(!protocolRequest)
1722 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1723 return OC_STACK_INVALID_PARAM;
1726 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1727 protocolRequest->tokenLength);
1730 OIC_LOG(INFO, TAG, "This is a new Server Request");
1731 result = AddServerRequest(&request, protocolRequest->coapID,
1732 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1733 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1734 protocolRequest->observationOption, protocolRequest->qos,
1735 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1736 protocolRequest->payload, protocolRequest->requestToken,
1737 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1738 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1739 &protocolRequest->devAddr);
1740 if (OC_STACK_OK != result)
1742 OIC_LOG(ERROR, TAG, "Error adding server request");
1748 OIC_LOG(ERROR, TAG, "Out of Memory");
1749 return OC_STACK_NO_MEMORY;
1752 if(!protocolRequest->reqMorePacket)
1754 request->requestComplete = 1;
1759 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1762 if(request->requestComplete)
1764 OIC_LOG(INFO, TAG, "This Server Request is complete");
1765 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1766 OCResource *resource = NULL;
1767 result = DetermineResourceHandling (request, &resHandling, &resource);
1768 if (result == OC_STACK_OK)
1770 result = ProcessRequest(resHandling, resource, request);
1775 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1776 result = OC_STACK_CONTINUE;
1781 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1783 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1786 if (requestInfo->info.resourceUri &&
1787 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1789 HandleKeepAliveRequest(endPoint, requestInfo);
1794 OCStackResult requestResult = OC_STACK_ERROR;
1796 if(myStackMode == OC_CLIENT)
1798 //TODO: should the client be responding to requests?
1802 OCServerProtocolRequest serverRequest = {0};
1804 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1806 char * uriWithoutQuery = NULL;
1807 char * query = NULL;
1809 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1811 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1813 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1816 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1817 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1819 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1821 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1822 OICFree(uriWithoutQuery);
1826 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1827 OICFree(uriWithoutQuery);
1834 if(strlen(query) < MAX_QUERY_LENGTH)
1836 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1841 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1847 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1849 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1850 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1851 if (!serverRequest.payload)
1853 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1856 memcpy (serverRequest.payload, requestInfo->info.payload,
1857 requestInfo->info.payloadSize);
1861 serverRequest.reqTotalSize = 0;
1864 switch (requestInfo->method)
1867 serverRequest.method = OC_REST_GET;
1870 serverRequest.method = OC_REST_PUT;
1873 serverRequest.method = OC_REST_POST;
1876 serverRequest.method = OC_REST_DELETE;
1879 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1880 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1881 requestInfo->info.type, requestInfo->info.numOptions,
1882 requestInfo->info.options, requestInfo->info.token,
1883 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1885 OICFree(serverRequest.payload);
1889 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1890 requestInfo->info.tokenLength);
1892 serverRequest.tokenLength = requestInfo->info.tokenLength;
1893 if (serverRequest.tokenLength) {
1895 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1897 if (!serverRequest.requestToken)
1899 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1900 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1901 requestInfo->info.type, requestInfo->info.numOptions,
1902 requestInfo->info.options, requestInfo->info.token,
1903 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1905 OICFree(serverRequest.payload);
1908 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1911 switch (requestInfo->info.acceptFormat)
1913 case CA_FORMAT_APPLICATION_CBOR:
1914 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1916 case CA_FORMAT_UNDEFINED:
1917 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1920 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1923 if (requestInfo->info.type == CA_MSG_CONFIRM)
1925 serverRequest.qos = OC_HIGH_QOS;
1929 serverRequest.qos = OC_LOW_QOS;
1931 // CA does not need the following field
1932 // Are we sure CA does not need them? how is it responding to multicast
1933 serverRequest.delayedResNeeded = 0;
1935 serverRequest.coapID = requestInfo->info.messageId;
1937 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1939 // copy vendor specific header options
1940 uint8_t tempNum = (requestInfo->info.numOptions);
1942 // Assume no observation requested and it is a pure GET.
1943 // If obs registration/de-registration requested it'll be fetched from the
1944 // options in GetObserveHeaderOption()
1945 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1947 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1948 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1951 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1952 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1953 requestInfo->info.type, requestInfo->info.numOptions,
1954 requestInfo->info.options, requestInfo->info.token,
1955 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1957 OICFree(serverRequest.payload);
1958 OICFree(serverRequest.requestToken);
1961 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1962 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1964 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1965 sizeof(CAHeaderOption_t)*tempNum);
1968 requestResult = HandleStackRequests (&serverRequest);
1970 // Send ACK to client as precursor to slow response
1971 if (requestResult == OC_STACK_SLOW_RESOURCE)
1973 if (requestInfo->info.type == CA_MSG_CONFIRM)
1975 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1976 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
1980 else if(!OCResultToSuccess(requestResult))
1982 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1984 CAResponseResult_t stackResponse =
1985 OCToCAStackResult(requestResult, serverRequest.method);
1987 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1988 requestInfo->info.type, requestInfo->info.numOptions,
1989 requestInfo->info.options, requestInfo->info.token,
1990 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1993 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1994 // The token is copied in there, and is thus still owned by this function.
1995 OICFree(serverRequest.payload);
1996 OICFree(serverRequest.requestToken);
1997 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2000 //This function will be called back by CA layer when a request is received
2001 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2003 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2006 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2012 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2016 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2017 #ifdef ROUTING_GATEWAY
2018 bool needRIHandling = false;
2019 bool isEmptyMsg = false;
2021 * Routing manager is going to update either of endpoint or request or both.
2022 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2023 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2024 * destination. It can also remove "RM" coap header option before passing request / response to
2025 * RI as this option will make no sense to either RI or application.
2027 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2028 &needRIHandling, &isEmptyMsg);
2029 if(OC_STACK_OK != ret || !needRIHandling)
2031 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2037 * Put source in sender endpoint so that the next packet from application can be routed to
2038 * proper destination and remove RM header option.
2040 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2041 (uint8_t *) &(requestInfo->info.numOptions),
2042 (CAEndpoint_t *) endPoint);
2044 #ifdef ROUTING_GATEWAY
2048 * In Gateways, the MSGType in route option is used to check if the actual
2049 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2050 * EMPTY response is sent in the form of POST request which need to be changed
2051 * to a EMPTY response by RM. This translation is done in this part of the code.
2053 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2054 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2055 .info.messageId = requestInfo->info.messageId,
2056 .info.type = CA_MSG_ACKNOWLEDGE};
2057 OCHandleResponse(endPoint, &respInfo);
2063 // Normal handling of the packet
2064 OCHandleRequests(endPoint, requestInfo);
2066 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2069 bool validatePlatformInfo(OCPlatformInfo info)
2072 if (!info.platformID)
2074 OIC_LOG(ERROR, TAG, "No platform ID found.");
2078 if (info.manufacturerName)
2080 size_t lenManufacturerName = strlen(info.manufacturerName);
2082 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2084 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2090 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2094 if (info.manufacturerUrl)
2096 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2098 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2105 //-----------------------------------------------------------------------------
2107 //-----------------------------------------------------------------------------
2109 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2112 !raInfo->username ||
2113 !raInfo->hostname ||
2114 !raInfo->xmpp_domain)
2117 return OC_STACK_INVALID_PARAM;
2119 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2120 gRASetInfo = (result == OC_STACK_OK)? true : false;
2126 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2130 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2133 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2135 if(stackState == OC_STACK_INITIALIZED)
2137 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2138 OCStop() between them are ignored.");
2142 #ifndef ROUTING_GATEWAY
2143 if (OC_GATEWAY == mode)
2145 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2146 return OC_STACK_INVALID_PARAM;
2153 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2154 return OC_STACK_ERROR;
2158 OCStackResult result = OC_STACK_ERROR;
2159 OIC_LOG(INFO, TAG, "Entering OCInit");
2162 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2163 || (mode == OC_GATEWAY)))
2165 OIC_LOG(ERROR, TAG, "Invalid mode");
2166 return OC_STACK_ERROR;
2170 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2172 caglobals.client = true;
2174 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2176 caglobals.server = true;
2179 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2180 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2182 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2184 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2185 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2187 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2190 defaultDeviceHandler = NULL;
2191 defaultDeviceHandlerCallbackParameter = NULL;
2193 result = CAResultToOCResult(CAInitialize());
2194 VERIFY_SUCCESS(result, OC_STACK_OK);
2196 result = CAResultToOCResult(OCSelectNetwork());
2197 VERIFY_SUCCESS(result, OC_STACK_OK);
2199 switch (myStackMode)
2202 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2203 result = CAResultToOCResult(CAStartDiscoveryServer());
2204 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2207 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2208 result = CAResultToOCResult(CAStartListeningServer());
2209 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2211 case OC_CLIENT_SERVER:
2213 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2214 result = CAResultToOCResult(CAStartListeningServer());
2215 if(result == OC_STACK_OK)
2217 result = CAResultToOCResult(CAStartDiscoveryServer());
2221 VERIFY_SUCCESS(result, OC_STACK_OK);
2224 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2227 #ifdef WITH_PRESENCE
2228 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2229 #endif // WITH_PRESENCE
2231 //Update Stack state to initialized
2232 stackState = OC_STACK_INITIALIZED;
2234 // Initialize resource
2235 if(myStackMode != OC_CLIENT)
2237 result = initResources();
2240 // Initialize the SRM Policy Engine
2241 if(result == OC_STACK_OK)
2243 result = SRMInitPolicyEngine();
2244 // TODO after BeachHead delivery: consolidate into single SRMInit()
2246 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2247 RMSetStackMode(mode);
2248 #ifdef ROUTING_GATEWAY
2249 if (OC_GATEWAY == myStackMode)
2251 result = RMInitialize();
2257 if (result == OC_STACK_OK)
2259 result = InitializeKeepAlive(myStackMode);
2264 if(result != OC_STACK_OK)
2266 OIC_LOG(ERROR, TAG, "Stack initialization error");
2267 deleteAllResources();
2269 stackState = OC_STACK_UNINITIALIZED;
2274 OCStackResult OCStop()
2276 OIC_LOG(INFO, TAG, "Entering OCStop");
2278 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2280 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2283 else if (stackState != OC_STACK_INITIALIZED)
2285 OIC_LOG(ERROR, TAG, "Stack not initialized");
2286 return OC_STACK_ERROR;
2289 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2291 #ifdef WITH_PRESENCE
2292 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2293 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2294 presenceResource.presenceTTL = 0;
2295 #endif // WITH_PRESENCE
2297 #ifdef ROUTING_GATEWAY
2298 if (OC_GATEWAY == myStackMode)
2305 TerminateKeepAlive(myStackMode);
2308 // Free memory dynamically allocated for resources
2309 deleteAllResources();
2311 DeletePlatformInfo();
2313 // Remove all observers
2314 DeleteObserverList();
2315 // Remove all the client callbacks
2316 DeleteClientCBList();
2318 // De-init the SRM Policy Engine
2319 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2320 SRMDeInitPolicyEngine();
2323 stackState = OC_STACK_UNINITIALIZED;
2327 OCStackResult OCStartMulticastServer()
2329 if(stackState != OC_STACK_INITIALIZED)
2331 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2332 return OC_STACK_ERROR;
2334 CAResult_t ret = CAStartListeningServer();
2335 if (CA_STATUS_OK != ret)
2337 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2338 return OC_STACK_ERROR;
2343 OCStackResult OCStopMulticastServer()
2345 CAResult_t ret = CAStopListeningServer();
2346 if (CA_STATUS_OK != ret)
2348 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2349 return OC_STACK_ERROR;
2354 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2359 return CA_MSG_CONFIRM;
2364 return CA_MSG_NONCONFIRM;
2369 * A request uri consists of the following components in order:
2372 * CoAP over UDP prefix "coap://"
2373 * CoAP over TCP prefix "coap+tcp://"
2375 * IPv6 address "[1234::5678]"
2376 * IPv4 address "192.168.1.1"
2377 * optional port ":5683"
2378 * resource uri "/oc/core..."
2380 * for PRESENCE requests, extract resource type.
2382 static OCStackResult ParseRequestUri(const char *fullUri,
2383 OCTransportAdapter adapter,
2384 OCTransportFlags flags,
2385 OCDevAddr **devAddr,
2387 char **resourceType)
2389 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2391 OCStackResult result = OC_STACK_OK;
2392 OCDevAddr *da = NULL;
2396 // provide defaults for all returned values
2403 *resourceUri = NULL;
2407 *resourceType = NULL;
2410 // delimit url prefix, if any
2411 const char *start = fullUri;
2412 char *slash2 = strstr(start, "//");
2417 char *slash = strchr(start, '/');
2420 return OC_STACK_INVALID_URI;
2423 // process url scheme
2424 size_t prefixLen = slash2 - fullUri;
2428 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2434 // TODO: this logic should come in with unit tests exercising the various strings
2435 // processs url prefix, if any
2436 size_t urlLen = slash - start;
2440 if (urlLen && devAddr)
2441 { // construct OCDevAddr
2442 if (start[0] == '[')
2444 char *close = strchr(++start, ']');
2445 if (!close || close > slash)
2447 return OC_STACK_INVALID_URI;
2450 if (close[1] == ':')
2457 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2461 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2463 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2467 char *dot = strchr(start, '.');
2468 if (dot && dot < slash)
2470 colon = strchr(start, ':');
2471 end = (colon && colon < slash) ? colon : slash;
2476 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2480 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2482 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2490 if (len >= sizeof(da->addr))
2492 return OC_STACK_INVALID_URI;
2494 // collect port, if any
2495 if (colon && colon < slash)
2497 for (colon++; colon < slash; colon++)
2500 if (c < '0' || c > '9')
2502 return OC_STACK_INVALID_URI;
2504 port = 10 * port + c - '0';
2509 if (len >= sizeof(da->addr))
2511 return OC_STACK_INVALID_URI;
2514 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2517 return OC_STACK_NO_MEMORY;
2519 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2521 da->adapter = adapter;
2523 if (!strncmp(fullUri, "coaps:", 6))
2525 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2530 // process resource uri, if any
2532 { // request uri and query
2533 size_t ulen = strlen(slash); // resource uri length
2534 size_t tlen = 0; // resource type length
2537 static const char strPresence[] = "/oic/ad?rt=";
2538 static const size_t lenPresence = sizeof(strPresence) - 1;
2539 if (!strncmp(slash, strPresence, lenPresence))
2541 type = slash + lenPresence;
2542 tlen = ulen - lenPresence;
2547 *resourceUri = (char *)OICMalloc(ulen + 1);
2550 result = OC_STACK_NO_MEMORY;
2553 strcpy(*resourceUri, slash);
2556 if (type && resourceType)
2558 *resourceType = (char *)OICMalloc(tlen + 1);
2561 result = OC_STACK_NO_MEMORY;
2565 OICStrcpy(*resourceType, (tlen+1), type);
2572 // free all returned values
2579 OICFree(*resourceUri);
2583 OICFree(*resourceType);
2588 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2589 char *resourceUri, char **requestUri)
2591 char uri[CA_MAX_URI_LENGTH];
2593 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2595 *requestUri = OICStrdup(uri);
2598 return OC_STACK_NO_MEMORY;
2605 * Discover or Perform requests on a specified resource
2607 OCStackResult OCDoResource(OCDoHandle *handle,
2609 const char *requestUri,
2610 const OCDevAddr *destination,
2612 OCConnectivityType connectivityType,
2613 OCQualityOfService qos,
2614 OCCallbackData *cbData,
2615 OCHeaderOption *options,
2618 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2620 // Validate input parameters
2621 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2622 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2623 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2625 OCStackResult result = OC_STACK_ERROR;
2626 CAResult_t caResult;
2627 CAToken_t token = NULL;
2628 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2629 ClientCB *clientCB = NULL;
2630 OCDoHandle resHandle = NULL;
2631 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2632 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2634 OCTransportAdapter adapter;
2635 OCTransportFlags flags;
2636 // the request contents are put here
2637 CARequestInfo_t requestInfo = {.method = CA_GET};
2638 // requestUri will be parsed into the following three variables
2639 OCDevAddr *devAddr = NULL;
2640 char *resourceUri = NULL;
2641 char *resourceType = NULL;
2644 * Support original behavior with address on resourceUri argument.
2646 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2647 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2649 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2651 if (result != OC_STACK_OK)
2653 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2660 case OC_REST_OBSERVE:
2661 case OC_REST_OBSERVE_ALL:
2662 case OC_REST_CANCEL_OBSERVE:
2663 requestInfo.method = CA_GET;
2666 requestInfo.method = CA_PUT;
2669 requestInfo.method = CA_POST;
2671 case OC_REST_DELETE:
2672 requestInfo.method = CA_DELETE;
2674 case OC_REST_DISCOVER:
2676 if (destination || devAddr)
2678 requestInfo.isMulticast = false;
2682 tmpDevAddr.adapter = adapter;
2683 tmpDevAddr.flags = flags;
2684 destination = &tmpDevAddr;
2685 requestInfo.isMulticast = true;
2687 // CA_DISCOVER will become GET and isMulticast
2688 requestInfo.method = CA_GET;
2690 #ifdef WITH_PRESENCE
2691 case OC_REST_PRESENCE:
2692 // Replacing method type with GET because "presence"
2693 // is a stack layer only implementation.
2694 requestInfo.method = CA_GET;
2698 result = OC_STACK_INVALID_METHOD;
2702 if (!devAddr && !destination)
2704 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2705 result = OC_STACK_INVALID_PARAM;
2709 /* If not original behavior, use destination argument */
2710 if (destination && !devAddr)
2712 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2715 result = OC_STACK_NO_MEMORY;
2718 *devAddr = *destination;
2721 resHandle = GenerateInvocationHandle();
2724 result = OC_STACK_NO_MEMORY;
2728 caResult = CAGenerateToken(&token, tokenLength);
2729 if (caResult != CA_STATUS_OK)
2731 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2732 result= OC_STACK_ERROR;
2736 // fill in request data
2737 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2738 requestInfo.info.token = token;
2739 requestInfo.info.tokenLength = tokenLength;
2740 requestInfo.info.resourceUri = resourceUri;
2742 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2744 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2745 options, numOptions, OC_OBSERVE_REGISTER);
2746 if (result != OC_STACK_OK)
2750 requestInfo.info.numOptions = numOptions + 1;
2754 requestInfo.info.numOptions = numOptions;
2755 requestInfo.info.options =
2756 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2757 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2758 numOptions * sizeof(CAHeaderOption_t));
2761 CopyDevAddrToEndpoint(devAddr, &endpoint);
2766 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2769 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2772 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2776 requestInfo.info.payload = NULL;
2777 requestInfo.info.payloadSize = 0;
2778 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2781 // prepare for response
2782 #ifdef WITH_PRESENCE
2783 if (method == OC_REST_PRESENCE)
2785 char *presenceUri = NULL;
2786 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2787 if (OC_STACK_OK != result)
2792 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2793 // Presence notification will form a canonical uri to
2794 // look for callbacks into the application.
2795 resourceUri = presenceUri;
2799 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2800 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2801 method, devAddr, resourceUri, resourceType, ttl);
2802 if (OC_STACK_OK != result)
2807 devAddr = NULL; // Client CB list entry now owns it
2808 resourceUri = NULL; // Client CB list entry now owns it
2809 resourceType = NULL; // Client CB list entry now owns it
2812 result = OCSendRequest(&endpoint, &requestInfo);
2813 if (OC_STACK_OK != result)
2820 *handle = resHandle;
2824 if (result != OC_STACK_OK)
2826 OIC_LOG(ERROR, TAG, "OCDoResource error");
2827 FindAndDeleteClientCB(clientCB);
2828 CADestroyToken(token);
2836 // This is the owner of the payload object, so we free it
2837 OCPayloadDestroy(payload);
2838 OICFree(requestInfo.info.payload);
2840 OICFree(resourceUri);
2841 OICFree(resourceType);
2842 OICFree(requestInfo.info.options);
2846 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2850 * This ftn is implemented one of two ways in the case of observation:
2852 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2853 * Remove the callback associated on client side.
2854 * When the next notification comes in from server,
2855 * reply with RESET message to server.
2856 * Keep in mind that the server will react to RESET only
2857 * if the last notification was sent as CON
2859 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2860 * and it is associated with an observe request
2861 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2862 * Send CON Observe request to server with
2863 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2864 * Remove the callback associated on client side.
2866 OCStackResult ret = OC_STACK_OK;
2867 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2868 CARequestInfo_t requestInfo = {.method = CA_GET};
2872 return OC_STACK_INVALID_PARAM;
2875 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2878 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2879 return OC_STACK_ERROR;
2882 switch (clientCB->method)
2884 case OC_REST_OBSERVE:
2885 case OC_REST_OBSERVE_ALL:
2887 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2889 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2891 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2893 FindAndDeleteClientCB(clientCB);
2897 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2899 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2900 requestInfo.info.token = clientCB->token;
2901 requestInfo.info.tokenLength = clientCB->tokenLength;
2903 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2904 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2906 return OC_STACK_ERROR;
2908 requestInfo.info.numOptions = numOptions + 1;
2909 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2912 ret = OCSendRequest(&endpoint, &requestInfo);
2914 if (requestInfo.info.options)
2916 OICFree (requestInfo.info.options);
2918 if (requestInfo.info.resourceUri)
2920 OICFree (requestInfo.info.resourceUri);
2925 case OC_REST_DISCOVER:
2926 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2927 clientCB->requestUri);
2928 FindAndDeleteClientCB(clientCB);
2931 #ifdef WITH_PRESENCE
2932 case OC_REST_PRESENCE:
2933 FindAndDeleteClientCB(clientCB);
2938 ret = OC_STACK_INVALID_METHOD;
2946 * @brief Register Persistent storage callback.
2947 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2949 * OC_STACK_OK - No errors; Success
2950 * OC_STACK_INVALID_PARAM - Invalid parameter
2952 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2954 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2955 if(!persistentStorageHandler)
2957 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2958 return OC_STACK_INVALID_PARAM;
2962 if( !persistentStorageHandler->open ||
2963 !persistentStorageHandler->close ||
2964 !persistentStorageHandler->read ||
2965 !persistentStorageHandler->unlink ||
2966 !persistentStorageHandler->write)
2968 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2969 return OC_STACK_INVALID_PARAM;
2972 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2975 #ifdef WITH_PRESENCE
2977 OCStackResult OCProcessPresence()
2979 OCStackResult result = OC_STACK_OK;
2981 // the following line floods the log with messages that are irrelevant
2982 // to most purposes. Uncomment as needed.
2983 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2984 ClientCB* cbNode = NULL;
2985 OCClientResponse clientResponse;
2986 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2988 LL_FOREACH(cbList, cbNode)
2990 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2995 uint32_t now = GetTicks(0);
2996 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2997 cbNode->presence->TTLlevel);
2998 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3000 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3005 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3007 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3008 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3010 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3012 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3014 clientResponse.sequenceNumber = 0;
3015 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3016 clientResponse.devAddr = *cbNode->devAddr;
3017 FixUpClientResponse(&clientResponse);
3018 clientResponse.payload = NULL;
3020 // Increment the TTLLevel (going to a next state), so we don't keep
3021 // sending presence notification to client.
3022 cbNode->presence->TTLlevel++;
3023 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3024 cbNode->presence->TTLlevel);
3026 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3027 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3029 FindAndDeleteClientCB(cbNode);
3033 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3038 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3039 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3040 CARequestInfo_t requestInfo = {.method = CA_GET};
3042 OIC_LOG(DEBUG, TAG, "time to test server presence");
3044 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3046 requestData.type = CA_MSG_NONCONFIRM;
3047 requestData.token = cbNode->token;
3048 requestData.tokenLength = cbNode->tokenLength;
3049 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3050 requestInfo.method = CA_GET;
3051 requestInfo.info = requestData;
3053 result = OCSendRequest(&endpoint, &requestInfo);
3054 if (OC_STACK_OK != result)
3059 cbNode->presence->TTLlevel++;
3060 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3063 if (result != OC_STACK_OK)
3065 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3070 #endif // WITH_PRESENCE
3072 OCStackResult OCProcess()
3074 #ifdef WITH_PRESENCE
3075 OCProcessPresence();
3077 CAHandleRequestResponse();
3079 #ifdef ROUTING_GATEWAY
3089 #ifdef WITH_PRESENCE
3090 OCStackResult OCStartPresence(const uint32_t ttl)
3092 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3093 OCChangeResourceProperty(
3094 &(((OCResource *)presenceResource.handle)->resourceProperties),
3097 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3099 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3100 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3104 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3105 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3109 presenceResource.presenceTTL = ttl;
3111 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3113 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3115 presenceState = OC_PRESENCE_INITIALIZED;
3117 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3119 CAToken_t caToken = NULL;
3120 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3121 if (caResult != CA_STATUS_OK)
3123 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3124 CADestroyToken(caToken);
3125 return OC_STACK_ERROR;
3128 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3129 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3130 CADestroyToken(caToken);
3133 // Each time OCStartPresence is called
3134 // a different random 32-bit integer number is used
3135 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3137 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3138 OC_PRESENCE_TRIGGER_CREATE);
3141 OCStackResult OCStopPresence()
3143 OCStackResult result = OC_STACK_ERROR;
3145 if(presenceResource.handle)
3147 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3149 // make resource inactive
3150 result = OCChangeResourceProperty(
3151 &(((OCResource *) presenceResource.handle)->resourceProperties),
3155 if(result != OC_STACK_OK)
3158 "Changing the presence resource properties to ACTIVE not successful");
3162 return SendStopNotification();
3166 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3167 void* callbackParameter)
3169 defaultDeviceHandler = entityHandler;
3170 defaultDeviceHandlerCallbackParameter = callbackParameter;
3175 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3177 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3179 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3181 if (validatePlatformInfo(platformInfo))
3183 return SavePlatformInfo(platformInfo);
3187 return OC_STACK_INVALID_PARAM;
3192 return OC_STACK_ERROR;
3196 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3198 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3200 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3202 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3203 return OC_STACK_INVALID_PARAM;
3206 if (deviceInfo.types)
3208 OCStringLL *type = deviceInfo.types;
3209 OCResource *resource = findResource((OCResource *) deviceResource);
3212 return OC_STACK_INVALID_PARAM;
3217 OCBindResourceTypeToResource(deviceResource, type->value);
3221 return SaveDeviceInfo(deviceInfo);
3224 OCStackResult OCCreateResource(OCResourceHandle *handle,
3225 const char *resourceTypeName,
3226 const char *resourceInterfaceName,
3227 const char *uri, OCEntityHandler entityHandler,
3228 void* callbackParam,
3229 uint8_t resourceProperties)
3232 OCResource *pointer = NULL;
3233 OCStackResult result = OC_STACK_ERROR;
3235 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3237 if(myStackMode == OC_CLIENT)
3239 return OC_STACK_INVALID_PARAM;
3241 // Validate parameters
3242 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3244 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3245 return OC_STACK_INVALID_URI;
3247 // Is it presented during resource discovery?
3248 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3250 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3251 return OC_STACK_INVALID_PARAM;
3254 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3256 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3260 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3262 // Make sure resourceProperties bitmask has allowed properties specified
3263 if (resourceProperties
3264 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3265 OC_EXPLICIT_DISCOVERABLE
3274 OIC_LOG(ERROR, TAG, "Invalid property");
3275 return OC_STACK_INVALID_PARAM;
3278 // If the headResource is NULL, then no resources have been created...
3279 pointer = headResource;
3282 // At least one resources is in the resource list, so we need to search for
3283 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3286 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3288 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3289 return OC_STACK_INVALID_PARAM;
3291 pointer = pointer->next;
3294 // Create the pointer and insert it into the resource list
3295 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3298 result = OC_STACK_NO_MEMORY;
3301 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3303 insertResource(pointer);
3306 pointer->uri = OICStrdup(uri);
3309 result = OC_STACK_NO_MEMORY;
3313 // Set properties. Set OC_ACTIVE
3314 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3317 // Add the resourcetype to the resource
3318 result = BindResourceTypeToResource(pointer, resourceTypeName);
3319 if (result != OC_STACK_OK)
3321 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3325 // Add the resourceinterface to the resource
3326 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3327 if (result != OC_STACK_OK)
3329 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3333 // If an entity handler has been passed, attach it to the newly created
3334 // resource. Otherwise, set the default entity handler.
3337 pointer->entityHandler = entityHandler;
3338 pointer->entityHandlerCallbackParam = callbackParam;
3342 pointer->entityHandler = defaultResourceEHandler;
3343 pointer->entityHandlerCallbackParam = NULL;
3346 // Initialize a pointer indicating child resources in case of collection
3347 pointer->rsrcChildResourcesHead = NULL;
3350 result = OC_STACK_OK;
3352 #ifdef WITH_PRESENCE
3353 if (presenceResource.handle)
3355 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3356 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3360 if (result != OC_STACK_OK)
3362 // Deep delete of resource and other dynamic elements that it contains
3363 deleteResource(pointer);
3368 OCStackResult OCBindResource(
3369 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3371 OCResource *resource = NULL;
3372 OCChildResource *tempChildResource = NULL;
3373 OCChildResource *newChildResource = NULL;
3375 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3377 // Validate parameters
3378 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3379 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3380 // Container cannot contain itself
3381 if (collectionHandle == resourceHandle)
3383 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3384 return OC_STACK_INVALID_PARAM;
3387 // Use the handle to find the resource in the resource linked list
3388 resource = findResource((OCResource *) collectionHandle);
3391 OIC_LOG(ERROR, TAG, "Collection handle not found");
3392 return OC_STACK_INVALID_PARAM;
3395 // Look for an open slot to add add the child resource.
3396 // If found, add it and return success
3398 tempChildResource = resource->rsrcChildResourcesHead;
3400 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3402 // TODO: what if one of child resource was deregistered without unbinding?
3403 tempChildResource = tempChildResource->next;
3406 // Do memory allocation for child resource
3407 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3408 if(!newChildResource)
3410 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3411 return OC_STACK_ERROR;
3414 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3415 newChildResource->next = NULL;
3417 if(!resource->rsrcChildResourcesHead)
3419 resource->rsrcChildResourcesHead = newChildResource;
3422 tempChildResource->next = newChildResource;
3425 OIC_LOG(INFO, TAG, "resource bound");
3427 #ifdef WITH_PRESENCE
3428 if (presenceResource.handle)
3430 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3431 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3432 OC_PRESENCE_TRIGGER_CHANGE);
3439 OCStackResult OCUnBindResource(
3440 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3442 OCResource *resource = NULL;
3443 OCChildResource *tempChildResource = NULL;
3444 OCChildResource *tempLastChildResource = NULL;
3446 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3448 // Validate parameters
3449 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3450 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3451 // Container cannot contain itself
3452 if (collectionHandle == resourceHandle)
3454 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3455 return OC_STACK_INVALID_PARAM;
3458 // Use the handle to find the resource in the resource linked list
3459 resource = findResource((OCResource *) collectionHandle);
3462 OIC_LOG(ERROR, TAG, "Collection handle not found");
3463 return OC_STACK_INVALID_PARAM;
3466 // Look for an open slot to add add the child resource.
3467 // If found, add it and return success
3468 if(!resource->rsrcChildResourcesHead)
3470 OIC_LOG(INFO, TAG, "resource not found in collection");
3472 // Unable to add resourceHandle, so return error
3473 return OC_STACK_ERROR;
3477 tempChildResource = resource->rsrcChildResourcesHead;
3479 while (tempChildResource)
3481 if(tempChildResource->rsrcResource == resourceHandle)
3483 // if resource going to be unbinded is the head one.
3484 if( tempChildResource == resource->rsrcChildResourcesHead )
3486 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3487 OICFree(resource->rsrcChildResourcesHead);
3488 resource->rsrcChildResourcesHead = temp;
3493 OCChildResource *temp = tempChildResource->next;
3494 OICFree(tempChildResource);
3495 tempLastChildResource->next = temp;
3499 OIC_LOG(INFO, TAG, "resource unbound");
3501 // Send notification when resource is unbounded successfully.
3502 #ifdef WITH_PRESENCE
3503 if (presenceResource.handle)
3505 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3506 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3507 OC_PRESENCE_TRIGGER_CHANGE);
3510 tempChildResource = NULL;
3511 tempLastChildResource = NULL;
3517 tempLastChildResource = tempChildResource;
3518 tempChildResource = tempChildResource->next;
3521 OIC_LOG(INFO, TAG, "resource not found in collection");
3523 tempChildResource = NULL;
3524 tempLastChildResource = NULL;
3526 // Unable to add resourceHandle, so return error
3527 return OC_STACK_ERROR;
3530 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3532 if (!resourceItemName)
3536 // Per RFC 6690 only registered values must follow the first rule below.
3537 // At this point in time the only values registered begin with "core", and
3538 // all other values are specified as opaque strings where multiple values
3539 // are separated by a space.
3540 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3542 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3544 if (resourceItemName[index] != '.'
3545 && resourceItemName[index] != '-'
3546 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3547 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3555 for (size_t index = 0; resourceItemName[index]; ++index)
3557 if (resourceItemName[index] == ' '
3558 || resourceItemName[index] == '\t'
3559 || resourceItemName[index] == '\r'
3560 || resourceItemName[index] == '\n')
3570 OCStackResult BindResourceTypeToResource(OCResource* resource,
3571 const char *resourceTypeName)
3573 OCResourceType *pointer = NULL;
3575 OCStackResult result = OC_STACK_ERROR;
3577 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3579 if (!ValidateResourceTypeInterface(resourceTypeName))
3581 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3582 return OC_STACK_INVALID_PARAM;
3585 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3588 result = OC_STACK_NO_MEMORY;
3592 str = OICStrdup(resourceTypeName);
3595 result = OC_STACK_NO_MEMORY;
3598 pointer->resourcetypename = str;
3599 pointer->next = NULL;
3601 insertResourceType(resource, pointer);
3602 result = OC_STACK_OK;
3605 if (result != OC_STACK_OK)
3614 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3615 const char *resourceInterfaceName)
3617 OCResourceInterface *pointer = NULL;
3619 OCStackResult result = OC_STACK_ERROR;
3621 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3623 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3625 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3626 return OC_STACK_INVALID_PARAM;
3629 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3631 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3634 result = OC_STACK_NO_MEMORY;
3638 str = OICStrdup(resourceInterfaceName);
3641 result = OC_STACK_NO_MEMORY;
3644 pointer->name = str;
3646 // Bind the resourceinterface to the resource
3647 insertResourceInterface(resource, pointer);
3649 result = OC_STACK_OK;
3652 if (result != OC_STACK_OK)
3661 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3662 const char *resourceTypeName)
3665 OCStackResult result = OC_STACK_ERROR;
3666 OCResource *resource = NULL;
3668 resource = findResource((OCResource *) handle);
3671 OIC_LOG(ERROR, TAG, "Resource not found");
3672 return OC_STACK_ERROR;
3675 result = BindResourceTypeToResource(resource, resourceTypeName);
3677 #ifdef WITH_PRESENCE
3678 if(presenceResource.handle)
3680 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3681 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3688 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3689 const char *resourceInterfaceName)
3692 OCStackResult result = OC_STACK_ERROR;
3693 OCResource *resource = NULL;
3695 resource = findResource((OCResource *) handle);
3698 OIC_LOG(ERROR, TAG, "Resource not found");
3699 return OC_STACK_ERROR;
3702 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3704 #ifdef WITH_PRESENCE
3705 if (presenceResource.handle)
3707 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3708 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3715 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3717 OCResource *pointer = headResource;
3719 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3723 *numResources = *numResources + 1;
3724 pointer = pointer->next;
3729 OCResourceHandle OCGetResourceHandle(uint8_t index)
3731 OCResource *pointer = headResource;
3733 for( uint8_t i = 0; i < index && pointer; ++i)
3735 pointer = pointer->next;
3737 return (OCResourceHandle) pointer;
3740 OCStackResult OCDeleteResource(OCResourceHandle handle)
3744 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3745 return OC_STACK_INVALID_PARAM;
3748 OCResource *resource = findResource((OCResource *) handle);
3749 if (resource == NULL)
3751 OIC_LOG(ERROR, TAG, "Resource not found");
3752 return OC_STACK_NO_RESOURCE;
3755 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3757 OIC_LOG(ERROR, TAG, "Error deleting resource");
3758 return OC_STACK_ERROR;
3764 const char *OCGetResourceUri(OCResourceHandle handle)
3766 OCResource *resource = NULL;
3768 resource = findResource((OCResource *) handle);
3771 return resource->uri;
3773 return (const char *) NULL;
3776 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3778 OCResource *resource = NULL;
3780 resource = findResource((OCResource *) handle);
3783 return resource->resourceProperties;
3785 return (OCResourceProperty)-1;
3788 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3789 uint8_t *numResourceTypes)
3791 OCResource *resource = NULL;
3792 OCResourceType *pointer = NULL;
3794 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3795 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3797 *numResourceTypes = 0;
3799 resource = findResource((OCResource *) handle);
3802 pointer = resource->rsrcType;
3805 *numResourceTypes = *numResourceTypes + 1;
3806 pointer = pointer->next;
3812 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3814 OCResourceType *resourceType = NULL;
3816 resourceType = findResourceTypeAtIndex(handle, index);
3819 return resourceType->resourcetypename;
3821 return (const char *) NULL;
3824 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3825 uint8_t *numResourceInterfaces)
3827 OCResourceInterface *pointer = NULL;
3828 OCResource *resource = NULL;
3830 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3831 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3833 *numResourceInterfaces = 0;
3834 resource = findResource((OCResource *) handle);
3837 pointer = resource->rsrcInterface;
3840 *numResourceInterfaces = *numResourceInterfaces + 1;
3841 pointer = pointer->next;
3847 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3849 OCResourceInterface *resourceInterface = NULL;
3851 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3852 if (resourceInterface)
3854 return resourceInterface->name;
3856 return (const char *) NULL;
3859 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3862 OCResource *resource = NULL;
3863 OCChildResource *tempChildResource = NULL;
3866 resource = findResource((OCResource *) collectionHandle);
3872 tempChildResource = resource->rsrcChildResourcesHead;
3874 while(tempChildResource)
3878 return tempChildResource->rsrcResource;
3881 tempChildResource = tempChildResource->next;
3884 // In this case, the number of resource handles in the collection exceeds the index
3885 tempChildResource = NULL;
3889 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3890 OCEntityHandler entityHandler,
3891 void* callbackParam)
3893 OCResource *resource = NULL;
3895 // Validate parameters
3896 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3898 // Use the handle to find the resource in the resource linked list
3899 resource = findResource((OCResource *)handle);
3902 OIC_LOG(ERROR, TAG, "Resource not found");
3903 return OC_STACK_ERROR;
3907 resource->entityHandler = entityHandler;
3908 resource->entityHandlerCallbackParam = callbackParam;
3910 #ifdef WITH_PRESENCE
3911 if (presenceResource.handle)
3913 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3914 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3921 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3923 OCResource *resource = NULL;
3925 resource = findResource((OCResource *)handle);
3928 OIC_LOG(ERROR, TAG, "Resource not found");
3933 return resource->entityHandler;
3936 void incrementSequenceNumber(OCResource * resPtr)
3938 // Increment the sequence number
3939 resPtr->sequenceNum += 1;
3940 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3942 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3947 #ifdef WITH_PRESENCE
3948 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3949 OCPresenceTrigger trigger)
3951 OCResource *resPtr = NULL;
3952 OCStackResult result = OC_STACK_ERROR;
3953 OCMethod method = OC_REST_PRESENCE;
3954 uint32_t maxAge = 0;
3955 resPtr = findResource((OCResource *) presenceResource.handle);
3958 return OC_STACK_NO_RESOURCE;
3961 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3963 maxAge = presenceResource.presenceTTL;
3965 result = SendAllObserverNotification(method, resPtr, maxAge,
3966 trigger, resourceType, OC_LOW_QOS);
3972 OCStackResult SendStopNotification()
3974 OCResource *resPtr = NULL;
3975 OCStackResult result = OC_STACK_ERROR;
3976 OCMethod method = OC_REST_PRESENCE;
3977 resPtr = findResource((OCResource *) presenceResource.handle);
3980 return OC_STACK_NO_RESOURCE;
3983 // maxAge is 0. ResourceType is NULL.
3984 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3990 #endif // WITH_PRESENCE
3991 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3993 OCResource *resPtr = NULL;
3994 OCStackResult result = OC_STACK_ERROR;
3995 OCMethod method = OC_REST_NOMETHOD;
3996 uint32_t maxAge = 0;
3998 OIC_LOG(INFO, TAG, "Notifying all observers");
3999 #ifdef WITH_PRESENCE
4000 if(handle == presenceResource.handle)
4004 #endif // WITH_PRESENCE
4005 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4007 // Verify that the resource exists
4008 resPtr = findResource ((OCResource *) handle);
4011 return OC_STACK_NO_RESOURCE;
4015 //only increment in the case of regular observing (not presence)
4016 incrementSequenceNumber(resPtr);
4017 method = OC_REST_OBSERVE;
4018 maxAge = MAX_OBSERVE_AGE;
4019 #ifdef WITH_PRESENCE
4020 result = SendAllObserverNotification (method, resPtr, maxAge,
4021 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4023 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4030 OCNotifyListOfObservers (OCResourceHandle handle,
4031 OCObservationId *obsIdList,
4032 uint8_t numberOfIds,
4033 const OCRepPayload *payload,
4034 OCQualityOfService qos)
4036 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4038 OCResource *resPtr = NULL;
4039 //TODO: we should allow the server to define this
4040 uint32_t maxAge = MAX_OBSERVE_AGE;
4042 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4043 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4044 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4046 resPtr = findResource ((OCResource *) handle);
4047 if (NULL == resPtr || myStackMode == OC_CLIENT)
4049 return OC_STACK_NO_RESOURCE;
4053 incrementSequenceNumber(resPtr);
4055 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4056 payload, maxAge, qos));
4059 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4061 OCStackResult result = OC_STACK_ERROR;
4062 OCServerRequest *serverRequest = NULL;
4064 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4066 // Validate input parameters
4067 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4068 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4071 // Get pointer to request info
4072 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4075 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4076 result = serverRequest->ehResponseHandler(ehResponse);
4082 //#ifdef DIRECT_PAIRING
4083 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4085 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4086 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4088 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4092 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4095 const OCDPDev_t* OCGetDirectPairedDevices()
4097 return (const OCDPDev_t*)DPGetPairedDevices();
4100 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4101 OCDirectPairingCB resultCallback)
4103 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4104 if(NULL == peer || NULL == pinNumber)
4106 OIC_LOG(ERROR, TAG, "Invalid parameters");
4107 return OC_STACK_INVALID_PARAM;
4109 if (NULL == resultCallback)
4111 OIC_LOG(ERROR, TAG, "Invalid callback");
4112 return OC_STACK_INVALID_CALLBACK;
4115 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4116 pinNumber, (OCDirectPairingResultCB)resultCallback);
4118 //#endif // DIRECT_PAIRING
4120 //-----------------------------------------------------------------------------
4121 // Private internal function definitions
4122 //-----------------------------------------------------------------------------
4123 static OCDoHandle GenerateInvocationHandle()
4125 OCDoHandle handle = NULL;
4126 // Generate token here, it will be deleted when the transaction is deleted
4127 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4130 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4136 #ifdef WITH_PRESENCE
4137 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4138 OCResourceProperty resourceProperties, uint8_t enable)
4142 return OC_STACK_INVALID_PARAM;
4144 if (resourceProperties
4145 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4147 OIC_LOG(ERROR, TAG, "Invalid property");
4148 return OC_STACK_INVALID_PARAM;
4152 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4156 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4162 OCStackResult initResources()
4164 OCStackResult result = OC_STACK_OK;
4166 headResource = NULL;
4167 tailResource = NULL;
4168 // Init Virtual Resources
4169 #ifdef WITH_PRESENCE
4170 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4172 result = OCCreateResource(&presenceResource.handle,
4173 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4175 OC_RSRVD_PRESENCE_URI,
4179 //make resource inactive
4180 result = OCChangeResourceProperty(
4181 &(((OCResource *) presenceResource.handle)->resourceProperties),
4184 #ifndef WITH_ARDUINO
4185 if (result == OC_STACK_OK)
4187 result = SRMInitSecureResources();
4191 if(result == OC_STACK_OK)
4193 CreateResetProfile();
4194 result = OCCreateResource(&deviceResource,
4195 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4196 OC_RSRVD_INTERFACE_DEFAULT,
4197 OC_RSRVD_DEVICE_URI,
4201 if(result == OC_STACK_OK)
4203 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4204 OC_RSRVD_INTERFACE_READ);
4208 if(result == OC_STACK_OK)
4210 result = OCCreateResource(&platformResource,
4211 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4212 OC_RSRVD_INTERFACE_DEFAULT,
4213 OC_RSRVD_PLATFORM_URI,
4217 if(result == OC_STACK_OK)
4219 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4220 OC_RSRVD_INTERFACE_READ);
4227 void insertResource(OCResource *resource)
4231 headResource = resource;
4232 tailResource = resource;
4236 tailResource->next = resource;
4237 tailResource = resource;
4239 resource->next = NULL;
4242 OCResource *findResource(OCResource *resource)
4244 OCResource *pointer = headResource;
4248 if (pointer == resource)
4252 pointer = pointer->next;
4257 void deleteAllResources()
4259 OCResource *pointer = headResource;
4260 OCResource *temp = NULL;
4264 temp = pointer->next;
4265 #ifdef WITH_PRESENCE
4266 if (pointer != (OCResource *) presenceResource.handle)
4268 #endif // WITH_PRESENCE
4269 deleteResource(pointer);
4270 #ifdef WITH_PRESENCE
4272 #endif // WITH_PRESENCE
4275 memset(&platformResource, 0, sizeof(platformResource));
4276 memset(&deviceResource, 0, sizeof(deviceResource));
4278 memset(&brokerResource, 0, sizeof(brokerResource));
4281 SRMDeInitSecureResources();
4283 #ifdef WITH_PRESENCE
4284 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4285 // presence notification attributed to their deletion to be processed.
4286 deleteResource((OCResource *) presenceResource.handle);
4287 memset(&presenceResource, 0, sizeof(presenceResource));
4288 #endif // WITH_PRESENCE
4291 OCStackResult deleteResource(OCResource *resource)
4293 OCResource *prev = NULL;
4294 OCResource *temp = NULL;
4297 OIC_LOG(DEBUG,TAG,"resource is NULL");
4298 return OC_STACK_INVALID_PARAM;
4301 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4303 temp = headResource;
4306 if (temp == resource)
4308 // Invalidate all Resource Properties.
4309 resource->resourceProperties = (OCResourceProperty) 0;
4310 #ifdef WITH_PRESENCE
4311 if(resource != (OCResource *) presenceResource.handle)
4313 #endif // WITH_PRESENCE
4314 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4315 #ifdef WITH_PRESENCE
4318 if(presenceResource.handle)
4320 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4321 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4324 // Only resource in list.
4325 if (temp == headResource && temp == tailResource)
4327 headResource = NULL;
4328 tailResource = NULL;
4331 else if (temp == headResource)
4333 headResource = temp->next;
4336 else if (temp == tailResource)
4338 tailResource = prev;
4339 tailResource->next = NULL;
4343 prev->next = temp->next;
4346 deleteResourceElements(temp);
4357 return OC_STACK_ERROR;
4360 void deleteResourceElements(OCResource *resource)
4367 OICFree(resource->uri);
4368 deleteResourceType(resource->rsrcType);
4369 deleteResourceInterface(resource->rsrcInterface);
4372 void deleteResourceType(OCResourceType *resourceType)
4374 OCResourceType *pointer = resourceType;
4375 OCResourceType *next = NULL;
4379 next = pointer->next;
4380 OICFree(pointer->resourcetypename);
4386 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4388 OCResourceInterface *pointer = resourceInterface;
4389 OCResourceInterface *next = NULL;
4393 next = pointer->next;
4394 OICFree(pointer->name);
4400 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4402 OCResourceType *pointer = NULL;
4403 OCResourceType *previous = NULL;
4404 if (!resource || !resourceType)
4408 // resource type list is empty.
4409 else if (!resource->rsrcType)
4411 resource->rsrcType = resourceType;
4415 pointer = resource->rsrcType;
4419 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4421 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4422 OICFree(resourceType->resourcetypename);
4423 OICFree(resourceType);
4427 pointer = pointer->next;
4432 previous->next = resourceType;
4435 resourceType->next = NULL;
4437 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4440 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4442 OCResource *resource = NULL;
4443 OCResourceType *pointer = NULL;
4445 // Find the specified resource
4446 resource = findResource((OCResource *) handle);
4452 // Make sure a resource has a resourcetype
4453 if (!resource->rsrcType)
4458 // Iterate through the list
4459 pointer = resource->rsrcType;
4460 for(uint8_t i = 0; i< index && pointer; ++i)
4462 pointer = pointer->next;
4467 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4469 if(resourceTypeList && resourceTypeName)
4471 OCResourceType * rtPointer = resourceTypeList;
4472 while(resourceTypeName && rtPointer)
4474 if(rtPointer->resourcetypename &&
4475 strcmp(resourceTypeName, (const char *)
4476 (rtPointer->resourcetypename)) == 0)
4480 rtPointer = rtPointer->next;
4488 * Insert a new interface into interface linked list only if not already present.
4489 * If alredy present, 2nd arg is free'd.
4490 * Default interface will always be first if present.
4492 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4494 OCResourceInterface *pointer = NULL;
4495 OCResourceInterface *previous = NULL;
4497 newInterface->next = NULL;
4499 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4501 if (!*firstInterface)
4503 // If first interface is not oic.if.baseline, by default add it as first interface type.
4504 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4506 *firstInterface = newInterface;
4510 OCStackResult result = BindResourceInterfaceToResource(resource,
4511 OC_RSRVD_INTERFACE_DEFAULT);
4512 if (result != OC_STACK_OK)
4514 OICFree(newInterface->name);
4515 OICFree(newInterface);
4518 if (*firstInterface)
4520 (*firstInterface)->next = newInterface;
4524 // If once add oic.if.baseline, later too below code take care of freeing memory.
4525 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4527 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4529 OICFree(newInterface->name);
4530 OICFree(newInterface);
4533 // This code will not hit anymore, keeping
4536 newInterface->next = *firstInterface;
4537 *firstInterface = newInterface;
4542 pointer = *firstInterface;
4545 if (strcmp(newInterface->name, pointer->name) == 0)
4547 OICFree(newInterface->name);
4548 OICFree(newInterface);
4552 pointer = pointer->next;
4557 previous->next = newInterface;
4562 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4565 OCResource *resource = NULL;
4566 OCResourceInterface *pointer = NULL;
4568 // Find the specified resource
4569 resource = findResource((OCResource *) handle);
4575 // Make sure a resource has a resourceinterface
4576 if (!resource->rsrcInterface)
4581 // Iterate through the list
4582 pointer = resource->rsrcInterface;
4584 for (uint8_t i = 0; i < index && pointer; ++i)
4586 pointer = pointer->next;
4592 * This function splits the uri using the '?' delimiter.
4593 * "uriWithoutQuery" is the block of characters between the beginning
4594 * till the delimiter or '\0' which ever comes first.
4595 * "query" is whatever is to the right of the delimiter if present.
4596 * No delimiter sets the query to NULL.
4597 * If either are present, they will be malloc'ed into the params 2, 3.
4598 * The first param, *uri is left untouched.
4600 * NOTE: This function does not account for whitespace at the end of the uri NOR
4601 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4602 * part of the query.
4604 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4608 return OC_STACK_INVALID_URI;
4610 if(!query || !uriWithoutQuery)
4612 return OC_STACK_INVALID_PARAM;
4616 *uriWithoutQuery = NULL;
4618 size_t uriWithoutQueryLen = 0;
4619 size_t queryLen = 0;
4620 size_t uriLen = strlen(uri);
4622 char *pointerToDelimiter = strstr(uri, "?");
4624 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4625 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4627 if (uriWithoutQueryLen)
4629 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4630 if (!*uriWithoutQuery)
4634 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4638 *query = (char *) OICCalloc(queryLen + 1, 1);
4641 OICFree(*uriWithoutQuery);
4642 *uriWithoutQuery = NULL;
4645 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4651 return OC_STACK_NO_MEMORY;
4654 static const OicUuid_t* OCGetServerInstanceID(void)
4656 static bool generated = false;
4657 static OicUuid_t sid;
4663 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4665 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4672 const char* OCGetServerInstanceIDString(void)
4674 static bool generated = false;
4675 static char sidStr[UUID_STRING_SIZE];
4682 const OicUuid_t *sid = OCGetServerInstanceID();
4683 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4685 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4693 CAResult_t OCSelectNetwork()
4695 CAResult_t retResult = CA_STATUS_FAILED;
4696 CAResult_t caResult = CA_STATUS_OK;
4698 CATransportAdapter_t connTypes[] = {
4700 CA_ADAPTER_RFCOMM_BTEDR,
4701 CA_ADAPTER_GATT_BTLE,
4704 ,CA_ADAPTER_REMOTE_ACCESS
4711 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4713 for(int i = 0; i<numConnTypes; i++)
4715 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4716 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4718 caResult = CASelectNetwork(connTypes[i]);
4719 if(caResult == CA_STATUS_OK)
4721 retResult = CA_STATUS_OK;
4726 if(retResult != CA_STATUS_OK)
4728 return caResult; // Returns error of appropriate transport that failed fatally.
4734 OCStackResult CAResultToOCResult(CAResult_t caResult)
4740 case CA_STATUS_INVALID_PARAM:
4741 return OC_STACK_INVALID_PARAM;
4742 case CA_ADAPTER_NOT_ENABLED:
4743 return OC_STACK_ADAPTER_NOT_ENABLED;
4744 case CA_SERVER_STARTED_ALREADY:
4746 case CA_SERVER_NOT_STARTED:
4747 return OC_STACK_ERROR;
4748 case CA_DESTINATION_NOT_REACHABLE:
4749 return OC_STACK_COMM_ERROR;
4750 case CA_SOCKET_OPERATION_FAILED:
4751 return OC_STACK_COMM_ERROR;
4752 case CA_SEND_FAILED:
4753 return OC_STACK_COMM_ERROR;
4754 case CA_RECEIVE_FAILED:
4755 return OC_STACK_COMM_ERROR;
4756 case CA_MEMORY_ALLOC_FAILED:
4757 return OC_STACK_NO_MEMORY;
4758 case CA_REQUEST_TIMEOUT:
4759 return OC_STACK_TIMEOUT;
4760 case CA_DESTINATION_DISCONNECTED:
4761 return OC_STACK_COMM_ERROR;
4762 case CA_STATUS_FAILED:
4763 return OC_STACK_ERROR;
4764 case CA_NOT_SUPPORTED:
4765 return OC_STACK_NOTIMPL;
4767 return OC_STACK_ERROR;
4771 bool OCResultToSuccess(OCStackResult ocResult)
4776 case OC_STACK_RESOURCE_CREATED:
4777 case OC_STACK_RESOURCE_DELETED:
4778 case OC_STACK_CONTINUE:
4779 case OC_STACK_RESOURCE_CHANGED:
4786 #if defined(RD_CLIENT) || defined(RD_SERVER)
4787 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
4789 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4791 OCResource *resource = NULL;
4793 resource = findResource((OCResource *) handle);
4796 OIC_LOG(ERROR, TAG, "Resource not found");
4797 return OC_STACK_ERROR;
4800 resource->ins = ins;
4805 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
4809 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
4813 OCResource *pointer = headResource;
4817 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
4819 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
4822 pointer = pointer->next;
4827 OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
4829 OCResource *resource = NULL;
4831 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4832 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
4834 resource = findResource((OCResource *) handle);
4837 *ins = resource->ins;
4840 return OC_STACK_ERROR;