1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //-----------------------------------------------------------------------------
24 //-----------------------------------------------------------------------------
26 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
27 // causes header files to expose definitions
28 // corresponding to the POSIX.1-2001 base
29 // specification (excluding the XSI extension).
30 // For POSIX.1-2001 base specification,
31 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
32 #define _POSIX_C_SOURCE 200112L
33 #ifndef __STDC_FORMAT_MACROS
34 #define __STDC_FORMAT_MACROS
36 #ifndef __STDC_LIMIT_MACROS
37 #define __STDC_LIMIT_MACROS
39 #include "iotivity_config.h"
45 #include "ocstackinternal.h"
46 #include "ocresourcehandler.h"
47 #include "occlientcb.h"
48 #include "ocobserve.h"
50 #include "oic_malloc.h"
51 #include "oic_string.h"
53 #include "ocserverrequest.h"
54 #include "secureresourcemanager.h"
55 #include "psinterface.h"
56 #include "doxmresource.h"
58 #include "cainterface.h"
59 #include "ocpayload.h"
60 #include "ocpayloadcbor.h"
62 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
63 #include "routingutility.h"
64 #ifdef ROUTING_GATEWAY
65 #include "routingmanager.h"
70 #include "oickeepalive.h"
73 //#ifdef DIRECT_PAIRING
74 #include "directpairing.h"
77 #ifdef HAVE_ARDUINO_TIME_H
80 #ifdef HAVE_SYS_TIME_H
83 #include "coap_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 COAPS_TCP[] = "coaps+tcp:";
142 static const char CORESPEC[] = "core";
144 //-----------------------------------------------------------------------------
146 //-----------------------------------------------------------------------------
147 #define TAG "OIC_RI_STACK"
148 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
149 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
150 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
151 TAG, #arg " is NULL"); return (retVal); } }
152 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
153 TAG, #arg " is NULL"); return; } }
154 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
157 //TODO: we should allow the server to define this
158 #define MAX_OBSERVE_AGE (0x2FFFFUL)
160 #define MILLISECONDS_PER_SECOND (1000)
162 //-----------------------------------------------------------------------------
163 // Private internal function prototypes
164 //-----------------------------------------------------------------------------
167 * Generate handle of OCDoResource invocation for callback management.
169 * @return Generated OCDoResource handle.
171 static OCDoHandle GenerateInvocationHandle();
174 * Initialize resource data structures, variables, etc.
176 * @return ::OC_STACK_OK on success, some other value upon failure.
178 static OCStackResult initResources();
181 * Add a resource to the end of the linked list of resources.
183 * @param resource Resource to be added
185 static void insertResource(OCResource *resource);
188 * Find a resource in the linked list of resources.
190 * @param resource Resource to be found.
191 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
194 static OCResource *findResource(OCResource *resource);
197 * Insert a resource type into a resource's resource type linked list.
198 * If resource type already exists, it will not be inserted and the
199 * resourceType will be free'd.
200 * resourceType->next should be null to avoid memory leaks.
201 * Function returns silently for null args.
203 * @param resource Resource where resource type is to be inserted.
204 * @param resourceType Resource type to be inserted.
206 static void insertResourceType(OCResource *resource,
207 OCResourceType *resourceType);
210 * Get a resource type at the specified index within a resource.
212 * @param handle Handle of resource.
213 * @param index Index of resource type.
215 * @return Pointer to resource type if found, NULL otherwise.
217 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
221 * Insert a resource interface into a resource's resource interface linked list.
222 * If resource interface already exists, it will not be inserted and the
223 * resourceInterface will be free'd.
224 * resourceInterface->next should be null to avoid memory leaks.
226 * @param resource Resource where resource interface is to be inserted.
227 * @param resourceInterface Resource interface to be inserted.
229 static void insertResourceInterface(OCResource *resource,
230 OCResourceInterface *resourceInterface);
233 * Get a resource interface at the specified index within a resource.
235 * @param handle Handle of resource.
236 * @param index Index of resource interface.
238 * @return Pointer to resource interface if found, NULL otherwise.
240 static OCResourceInterface *findResourceInterfaceAtIndex(
241 OCResourceHandle handle, uint8_t index);
244 * Delete all of the dynamically allocated elements that were created for the resource type.
246 * @param resourceType Specified resource type.
248 static void deleteResourceType(OCResourceType *resourceType);
251 * Delete all of the dynamically allocated elements that were created for the resource interface.
253 * @param resourceInterface Specified resource interface.
255 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
258 * Delete all of the dynamically allocated elements that were created for the resource.
260 * @param resource Specified resource.
262 static void deleteResourceElements(OCResource *resource);
265 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
268 * @param handle Handle of resource to be deleted.
270 * @return ::OC_STACK_OK on success, some other value upon failure.
272 static OCStackResult deleteResource(OCResource *resource);
275 * Delete all of the resources in the resource list.
277 static void deleteAllResources();
280 * Increment resource sequence number. Handles rollover.
282 * @param resPtr Pointer to resource.
284 static void incrementSequenceNumber(OCResource * resPtr);
287 * Attempts to initialize every network interface that the CA Layer might have compiled in.
289 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
290 * return something other than @ref CA_STATUS_OK, then this function fails.
292 * @return ::CA_STATUS_OK on success, some other value upon failure.
294 static CAResult_t OCSelectNetwork();
297 * Get the CoAP ticks after the specified number of milli-seconds.
299 * @param afterMilliSeconds Milli-seconds.
303 static uint32_t GetTicks(uint32_t afterMilliSeconds);
306 * Convert CAResult_t to OCStackResult.
308 * @param caResult CAResult_t code.
309 * @return ::OC_STACK_OK on success, some other value upon failure.
311 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
314 * Convert CAResponseResult_t to OCStackResult.
316 * @param caCode CAResponseResult_t code.
317 * @return ::OC_STACK_OK on success, some other value upon failure.
319 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
322 * Convert OCStackResult to CAResponseResult_t.
324 * @param caCode OCStackResult code.
325 * @param method OCMethod method the return code replies to.
326 * @return ::CA_CONTENT on OK, some other value upon failure.
328 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
331 * Convert OCTransportFlags_t to CATransportModifiers_t.
333 * @param ocConType OCTransportFlags_t input.
334 * @return CATransportFlags
336 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
339 * Convert CATransportFlags_t to OCTransportModifiers_t.
341 * @param caConType CATransportFlags_t input.
342 * @return OCTransportFlags
344 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
347 * Handle response from presence request.
349 * @param endPoint CA remote endpoint.
350 * @param responseInfo CA response info.
351 * @return ::OC_STACK_OK on success, some other value upon failure.
353 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
354 const CAResponseInfo_t *responseInfo);
357 * This function will be called back by CA layer when a response is received.
359 * @param endPoint CA remote endpoint.
360 * @param responseInfo CA response info.
362 static void HandleCAResponses(const CAEndpoint_t* endPoint,
363 const CAResponseInfo_t* responseInfo);
366 * This function will be called back by CA layer when a request is received.
368 * @param endPoint CA remote endpoint.
369 * @param requestInfo CA request info.
371 static void HandleCARequests(const CAEndpoint_t* endPoint,
372 const CARequestInfo_t* requestInfo);
375 * Extract query from a URI.
377 * @param uri Full URI with query.
378 * @param query Pointer to string that will contain query.
379 * @param newURI Pointer to string that will contain URI.
380 * @return ::OC_STACK_OK on success, some other value upon failure.
382 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
385 * Finds a resource type in an OCResourceType link-list.
387 * @param resourceTypeList The link-list to be searched through.
388 * @param resourceTypeName The key to search for.
390 * @return Resource type that matches the key (ie. resourceTypeName) or
391 * NULL if there is either an invalid parameter or this function was unable to find the key.
393 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
394 const char * resourceTypeName);
397 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
398 * TTL will be set to maxAge.
400 * @param cbNode Callback Node for which presence ttl is to be reset.
401 * @param maxAge New value of ttl in seconds.
403 * @return ::OC_STACK_OK on success, some other value upon failure.
405 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
408 * Ensure the accept header option is set appropriatly before sending the requests and routing
409 * header option is updated with destination.
411 * @param object CA remote endpoint.
412 * @param requestInfo CA request info.
414 * @return ::OC_STACK_OK on success, some other value upon failure.
416 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
418 //-----------------------------------------------------------------------------
419 // Internal functions
420 //-----------------------------------------------------------------------------
422 bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
424 if (!options || 0 == numOptions)
426 OIC_LOG (INFO, TAG, "No options present");
430 for (uint8_t i = 0; i < numOptions; i++)
432 if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
434 OIC_LOG(DEBUG, TAG, "Proxy URI is present");
441 uint32_t GetTicks(uint32_t afterMilliSeconds)
446 // Guard against overflow of uint32_t
447 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
448 COAP_TICKS_PER_SECOND)
450 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
458 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
460 VERIFY_NON_NULL_NR(in, FATAL);
461 VERIFY_NON_NULL_NR(out, FATAL);
463 out->adapter = (OCTransportAdapter)in->adapter;
464 out->flags = CAToOCTransportFlags(in->flags);
465 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
466 out->port = in->port;
467 out->ifindex = in->ifindex;
468 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
469 /* This assert is to prevent accidental mismatch between address size macros defined in
470 * RI and CA and cause crash here. */
471 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
472 "Address size mismatch between RI and CA");
473 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
477 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
479 VERIFY_NON_NULL_NR(in, FATAL);
480 VERIFY_NON_NULL_NR(out, FATAL);
482 out->adapter = (CATransportAdapter_t)in->adapter;
483 out->flags = OCToCATransportFlags(in->flags);
484 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
485 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
486 /* This assert is to prevent accidental mismatch between address size macros defined in
487 * RI and CA and cause crash here. */
488 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
489 "Address size mismatch between RI and CA");
490 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
492 out->port = in->port;
493 out->ifindex = in->ifindex;
496 void FixUpClientResponse(OCClientResponse *cr)
498 VERIFY_NON_NULL_NR(cr, FATAL);
500 cr->addr = &cr->devAddr;
501 cr->connType = (OCConnectivityType)
502 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
505 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
507 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
508 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
510 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
511 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
512 if (OC_STACK_OK != rmResult)
514 OIC_LOG(ERROR, TAG, "Add destination option failed");
519 // OC stack prefer CBOR encoded payloads.
520 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
521 CAResult_t result = CASendRequest(object, requestInfo);
522 if(CA_STATUS_OK != result)
524 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
525 return CAResultToOCResult(result);
529 //-----------------------------------------------------------------------------
530 // Internal API function
531 //-----------------------------------------------------------------------------
533 // This internal function is called to update the stack with the status of
534 // observers and communication failures
535 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
537 OCStackResult result = OC_STACK_ERROR;
538 ResourceObserver * observer = NULL;
539 OCEntityHandlerRequest ehRequest = {0};
543 case OC_OBSERVER_NOT_INTERESTED:
544 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
545 observer = GetObserverUsingToken (token, tokenLength);
548 result = FormOCEntityHandlerRequest(&ehRequest,
549 (OCRequestHandle)NULL,
552 (OCResourceHandle)NULL,
553 NULL, PAYLOAD_TYPE_REPRESENTATION,
555 OC_OBSERVE_DEREGISTER,
558 if(result != OC_STACK_OK)
562 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
563 observer->resource->entityHandlerCallbackParam);
566 result = DeleteObserverUsingToken (token, tokenLength);
567 if(result == OC_STACK_OK)
569 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
573 result = OC_STACK_OK;
574 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
578 case OC_OBSERVER_STILL_INTERESTED:
579 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
580 observer = GetObserverUsingToken (token, tokenLength);
583 observer->forceHighQos = 0;
584 observer->failedCommCount = 0;
585 result = OC_STACK_OK;
589 result = OC_STACK_OBSERVER_NOT_FOUND;
593 case OC_OBSERVER_FAILED_COMM:
594 OIC_LOG(DEBUG, TAG, "observer is unreachable");
595 observer = GetObserverUsingToken (token, tokenLength);
598 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
600 result = FormOCEntityHandlerRequest(&ehRequest,
601 (OCRequestHandle)NULL,
604 (OCResourceHandle)NULL,
605 NULL, PAYLOAD_TYPE_REPRESENTATION,
607 OC_OBSERVE_DEREGISTER,
610 if(result != OC_STACK_OK)
612 return OC_STACK_ERROR;
614 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
615 observer->resource->entityHandlerCallbackParam);
617 result = DeleteObserverUsingToken (token, tokenLength);
618 if(result == OC_STACK_OK)
620 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
624 result = OC_STACK_OK;
625 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
630 observer->failedCommCount++;
631 result = OC_STACK_CONTINUE;
633 observer->forceHighQos = 1;
634 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
638 OIC_LOG(ERROR, TAG, "Unknown status");
639 result = OC_STACK_ERROR;
645 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
647 OCStackResult ret = OC_STACK_ERROR;
651 case CA_ADAPTER_NOT_ENABLED:
652 case CA_SERVER_NOT_STARTED:
653 ret = OC_STACK_ADAPTER_NOT_ENABLED;
655 case CA_MEMORY_ALLOC_FAILED:
656 ret = OC_STACK_NO_MEMORY;
658 case CA_STATUS_INVALID_PARAM:
659 ret = OC_STACK_INVALID_PARAM;
667 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
669 OCStackResult ret = OC_STACK_ERROR;
673 ret = OC_STACK_RESOURCE_CREATED;
676 ret = OC_STACK_RESOURCE_DELETED;
679 ret = OC_STACK_RESOURCE_CHANGED;
686 ret = OC_STACK_INVALID_QUERY;
688 case CA_UNAUTHORIZED_REQ:
689 ret = OC_STACK_UNAUTHORIZED_REQ;
692 ret = OC_STACK_INVALID_OPTION;
695 ret = OC_STACK_NO_RESOURCE;
697 case CA_RETRANSMIT_TIMEOUT:
698 ret = OC_STACK_COMM_ERROR;
700 case CA_REQUEST_ENTITY_TOO_LARGE:
701 ret = OC_STACK_TOO_LARGE_REQ;
709 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
711 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
720 // This Response Code is like HTTP 204 "No Content" but only used in
721 // response to POST and PUT requests.
725 // This Response Code is like HTTP 200 "OK" but only used in response to
730 // This should not happen but,
731 // give it a value just in case but output an error
733 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
737 case OC_STACK_RESOURCE_CREATED:
740 case OC_STACK_RESOURCE_DELETED:
743 case OC_STACK_RESOURCE_CHANGED:
746 case OC_STACK_INVALID_QUERY:
749 case OC_STACK_INVALID_OPTION:
752 case OC_STACK_NO_RESOURCE:
755 case OC_STACK_COMM_ERROR:
756 ret = CA_RETRANSMIT_TIMEOUT;
758 case OC_STACK_UNAUTHORIZED_REQ:
759 ret = CA_UNAUTHORIZED_REQ;
767 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
769 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
771 // supply default behavior.
772 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
774 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
776 if ((caFlags & OC_MASK_SCOPE) == 0)
778 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
783 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
785 return (OCTransportFlags)caFlags;
788 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
790 uint32_t lowerBound = 0;
791 uint32_t higherBound = 0;
793 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
795 return OC_STACK_INVALID_PARAM;
798 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
800 cbNode->presence->TTL = maxAgeSeconds;
802 for (int index = 0; index < PresenceTimeOutSize; index++)
804 // Guard against overflow
805 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
808 lowerBound = GetTicks((PresenceTimeOut[index] *
809 cbNode->presence->TTL *
810 MILLISECONDS_PER_SECOND)/100);
814 lowerBound = GetTicks(UINT32_MAX);
817 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
820 higherBound = GetTicks((PresenceTimeOut[index + 1] *
821 cbNode->presence->TTL *
822 MILLISECONDS_PER_SECOND)/100);
826 higherBound = GetTicks(UINT32_MAX);
829 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
831 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
832 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
833 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
836 cbNode->presence->TTLlevel = 0;
838 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
842 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
844 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
846 return OC_RSRVD_TRIGGER_CREATE;
848 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
850 return OC_RSRVD_TRIGGER_CHANGE;
854 return OC_RSRVD_TRIGGER_DELETE;
858 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
862 return OC_PRESENCE_TRIGGER_CREATE;
864 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
866 return OC_PRESENCE_TRIGGER_CREATE;
868 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
870 return OC_PRESENCE_TRIGGER_CHANGE;
874 return OC_PRESENCE_TRIGGER_DELETE;
879 * Encode an address string to match RFC 6874.
881 * @param outputAddress a char array to be written with the encoded string.
883 * @param outputSize size of outputAddress buffer.
885 * @param inputAddress a char array of size <= CA_MAX_URI_LENGTH
886 * containing a valid IPv6 address string.
888 * @return OC_STACK_OK if encoding succeeded.
889 * Else an error occured.
891 OCStackResult encodeAddressForRFC6874(char *outputAddress,
893 const char *inputAddress)
895 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
896 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
898 size_t inputLength = strnlen(inputAddress, outputSize);
900 // inputSize includes the null terminator
901 size_t inputSize = inputLength + 1;
903 if (inputSize > outputSize)
905 OIC_LOG_V(ERROR, TAG,
906 "encodeAddressForRFC6874 failed: "
907 "outputSize (%zu) < inputSize (%zu)",
908 outputSize, inputSize);
910 return OC_STACK_ERROR;
913 char* percentChar = strchr(inputAddress, '%');
915 // If there is no '%' character, then no change is required to the string.
916 if (NULL == percentChar)
918 OICStrcpy(outputAddress, outputSize, inputAddress);
922 const char* addressPart = &inputAddress[0];
923 const char* scopeIdPart = percentChar + 1;
925 // Sanity check to make sure this string doesn't have more '%' characters
926 if (NULL != strchr(scopeIdPart, '%'))
928 return OC_STACK_ERROR;
931 // If no string follows the first '%', then the input was invalid.
932 if (scopeIdPart[0] == '\0')
934 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
935 return OC_STACK_ERROR;
938 // Check to see if the string is already encoded
939 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
941 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
942 return OC_STACK_ERROR;
945 // Fail if we don't have room for encoded string's two additional chars
946 if (outputSize < (inputSize + 2))
948 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: encoded output will not fit!");
949 return OC_STACK_ERROR;
952 // Restore the null terminator with an escaped '%' character, per RFC 6874
953 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
954 strcat(outputAddress, "%25");
955 strcat(outputAddress, scopeIdPart);
961 * The cononical presence allows constructed URIs to be string compared.
963 * requestUri must be a char array of size CA_MAX_URI_LENGTH
965 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
966 char *presenceUri, bool isMulticast)
968 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
969 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
970 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
974 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
975 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
978 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
979 if (ep->adapter == CA_ADAPTER_IP)
981 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
983 if ('\0' == ep->addr[0]) // multicast
985 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
989 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
991 OCStackResult result = encodeAddressForRFC6874(addressEncoded,
992 sizeof(addressEncoded),
995 if (OC_STACK_OK != result)
1000 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1001 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1006 if ('\0' == ep->addr[0]) // multicast
1008 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1009 ep->port = OC_MULTICAST_PORT;
1011 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1012 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1016 // might work for other adapters (untested, but better than nothing)
1017 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1018 OC_RSRVD_PRESENCE_URI);
1022 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1023 const CAResponseInfo_t *responseInfo)
1025 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1026 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1028 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1029 ClientCB * cbNode = NULL;
1030 char *resourceTypeName = NULL;
1031 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1032 OCStackResult result = OC_STACK_ERROR;
1033 uint32_t maxAge = 0;
1035 char presenceUri[CA_MAX_URI_LENGTH];
1037 int presenceSubscribe = 0;
1038 int multicastPresenceSubscribe = 0;
1040 if (responseInfo->result != CA_CONTENT)
1042 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1043 return OC_STACK_ERROR;
1046 response.payload = NULL;
1047 response.result = OC_STACK_OK;
1049 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1050 FixUpClientResponse(&response);
1052 if (responseInfo->info.payload)
1054 result = OCParsePayload(&response.payload,
1055 PAYLOAD_TYPE_PRESENCE,
1056 responseInfo->info.payload,
1057 responseInfo->info.payloadSize);
1059 if(result != OC_STACK_OK)
1061 OIC_LOG(ERROR, TAG, "Presence parse failed");
1064 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1066 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1067 result = OC_STACK_ERROR;
1070 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1071 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1072 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1075 // check for unicast presence
1076 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri,
1077 responseInfo->isMulticast);
1078 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1080 return OC_STACK_INVALID_URI;
1082 OIC_LOG(ERROR, TAG, "check for unicast presence");
1083 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1086 presenceSubscribe = 1;
1090 // check for multicast presence
1091 OIC_LOG(ERROR, TAG, "check for multicast presence");
1092 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1095 multicastPresenceSubscribe = 1;
1099 if (!presenceSubscribe && !multicastPresenceSubscribe)
1101 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1105 if (presenceSubscribe)
1107 if(cbNode->sequenceNumber == response.sequenceNumber)
1109 OIC_LOG(INFO, TAG, "No presence change");
1110 ResetPresenceTTL(cbNode, maxAge);
1111 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1117 OIC_LOG(INFO, TAG, "Stopping presence");
1118 response.result = OC_STACK_PRESENCE_STOPPED;
1119 if(cbNode->presence)
1121 OICFree(cbNode->presence->timeOut);
1122 OICFree(cbNode->presence);
1123 cbNode->presence = NULL;
1128 if(!cbNode->presence)
1130 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1132 if(!(cbNode->presence))
1134 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1135 result = OC_STACK_NO_MEMORY;
1139 VERIFY_NON_NULL_V(cbNode->presence);
1140 cbNode->presence->timeOut = NULL;
1141 cbNode->presence->timeOut = (uint32_t *)
1142 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1143 if(!(cbNode->presence->timeOut)){
1145 "Could not allocate memory for cbNode->presence->timeOut");
1146 OICFree(cbNode->presence);
1147 result = OC_STACK_NO_MEMORY;
1152 ResetPresenceTTL(cbNode, maxAge);
1154 cbNode->sequenceNumber = response.sequenceNumber;
1156 // Ensure that a filter is actually applied.
1157 if( resourceTypeName && cbNode->filterResourceType)
1159 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1168 // This is the multicast case
1169 OCMulticastNode* mcNode = NULL;
1170 mcNode = GetMCPresenceNode(presenceUri);
1174 if(mcNode->nonce == response.sequenceNumber)
1176 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1179 mcNode->nonce = response.sequenceNumber;
1183 OIC_LOG(INFO, TAG, "Stopping presence");
1184 response.result = OC_STACK_PRESENCE_STOPPED;
1189 char* uri = OICStrdup(presenceUri);
1193 "No Memory for URI to store in the presence node");
1194 result = OC_STACK_NO_MEMORY;
1198 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1199 if(result == OC_STACK_NO_MEMORY)
1202 "No Memory for Multicast Presence Node");
1206 // presence node now owns uri
1211 // Ensure that a filter is actually applied.
1212 if(resourceTypeName && cbNode->filterResourceType)
1214 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1215 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1221 OIC_LOG(INFO, TAG, "Callback for presence");
1223 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1225 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1227 FindAndDeleteClientCB(cbNode);
1231 OCPayloadDestroy(response.payload);
1235 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1237 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1239 if(responseInfo->info.resourceUri &&
1240 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1242 HandlePresenceResponse(endPoint, responseInfo);
1246 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1247 responseInfo->info.tokenLength, NULL, NULL);
1249 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1250 responseInfo->info.tokenLength);
1254 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1255 if(responseInfo->result == CA_EMPTY)
1257 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1258 // We do not have a case for the client to receive a RESET
1259 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1261 //This is the case of receiving an ACK on a request to a slow resource!
1262 OIC_LOG(INFO, TAG, "This is a pure ACK");
1263 //TODO: should we inform the client
1264 // app that at least the request was received at the server?
1267 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1269 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1270 OIC_LOG(INFO, TAG, "Calling into application address space");
1272 OCClientResponse response =
1273 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1274 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1275 FixUpClientResponse(&response);
1276 response.resourceUri = responseInfo->info.resourceUri;
1277 memcpy(response.identity.id, responseInfo->info.identity.id,
1278 sizeof (response.identity.id));
1279 response.identity.id_length = responseInfo->info.identity.id_length;
1281 response.result = CAResponseToOCStackResult(responseInfo->result);
1282 cbNode->callBack(cbNode->context,
1283 cbNode->handle, &response);
1284 FindAndDeleteClientCB(cbNode);
1288 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1289 OIC_LOG(INFO, TAG, "Calling into application address space");
1291 OCClientResponse response =
1292 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1293 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1294 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1295 FixUpClientResponse(&response);
1296 response.resourceUri = responseInfo->info.resourceUri;
1297 memcpy(response.identity.id, responseInfo->info.identity.id,
1298 sizeof (response.identity.id));
1299 response.identity.id_length = responseInfo->info.identity.id_length;
1301 response.result = CAResponseToOCStackResult(responseInfo->result);
1303 if(responseInfo->info.payload &&
1304 responseInfo->info.payloadSize)
1306 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1307 // check the security resource
1308 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1310 type = PAYLOAD_TYPE_SECURITY;
1312 else if (cbNode->method == OC_REST_DISCOVER)
1314 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1315 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1317 type = PAYLOAD_TYPE_DISCOVERY;
1320 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1322 type = PAYLOAD_TYPE_DISCOVERY;
1325 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1327 type = PAYLOAD_TYPE_DEVICE;
1329 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1331 type = PAYLOAD_TYPE_PLATFORM;
1333 #ifdef ROUTING_GATEWAY
1334 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1336 type = PAYLOAD_TYPE_REPRESENTATION;
1339 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1341 type = PAYLOAD_TYPE_RD;
1344 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1346 type = PAYLOAD_TYPE_REPRESENTATION;
1351 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1352 cbNode->method, cbNode->requestUri);
1356 else if (cbNode->method == OC_REST_GET ||
1357 cbNode->method == OC_REST_PUT ||
1358 cbNode->method == OC_REST_POST ||
1359 cbNode->method == OC_REST_OBSERVE ||
1360 cbNode->method == OC_REST_OBSERVE_ALL ||
1361 cbNode->method == OC_REST_DELETE)
1363 if (cbNode->requestUri)
1365 char targetUri[MAX_URI_LENGTH];
1366 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1367 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1368 if (strcmp(targetUri, cbNode->requestUri) == 0)
1370 type = PAYLOAD_TYPE_RD;
1372 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1374 type = PAYLOAD_TYPE_PLATFORM;
1376 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1378 type = PAYLOAD_TYPE_DEVICE;
1380 if (type == PAYLOAD_TYPE_INVALID)
1382 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1383 cbNode->method, cbNode->requestUri);
1384 type = PAYLOAD_TYPE_REPRESENTATION;
1389 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1390 type = PAYLOAD_TYPE_REPRESENTATION;
1395 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1396 cbNode->method, cbNode->requestUri);
1400 if(OC_STACK_OK != OCParsePayload(&response.payload,
1402 responseInfo->info.payload,
1403 responseInfo->info.payloadSize))
1405 OIC_LOG(ERROR, TAG, "Error converting payload");
1406 OCPayloadDestroy(response.payload);
1411 response.numRcvdVendorSpecificHeaderOptions = 0;
1412 if(responseInfo->info.numOptions > 0)
1415 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1416 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1419 uint32_t observationOption;
1420 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1421 for (observationOption=0, i=0;
1422 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1426 (observationOption << 8) | optionData[i];
1428 response.sequenceNumber = observationOption;
1429 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1434 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1437 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1439 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1440 OCPayloadDestroy(response.payload);
1444 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1446 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1447 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1451 if (cbNode->method == OC_REST_OBSERVE &&
1452 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1453 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1454 response.sequenceNumber <= cbNode->sequenceNumber)
1456 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1457 response.sequenceNumber);
1461 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1464 cbNode->sequenceNumber = response.sequenceNumber;
1466 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1468 FindAndDeleteClientCB(cbNode);
1472 // To keep discovery callbacks active.
1473 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1474 MILLISECONDS_PER_SECOND);
1478 //Need to send ACK when the response is CON
1479 if(responseInfo->info.type == CA_MSG_CONFIRM)
1481 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1482 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1485 OCPayloadDestroy(response.payload);
1492 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1493 if(responseInfo->result == CA_EMPTY)
1495 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1496 if(responseInfo->info.type == CA_MSG_RESET)
1498 OIC_LOG(INFO, TAG, "This is a RESET");
1499 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1500 OC_OBSERVER_NOT_INTERESTED);
1502 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1504 OIC_LOG(INFO, TAG, "This is a pure ACK");
1505 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1506 OC_OBSERVER_STILL_INTERESTED);
1509 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1511 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1512 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1513 OC_OBSERVER_FAILED_COMM);
1518 if(!cbNode && !observer)
1520 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1521 || myStackMode == OC_GATEWAY)
1523 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1524 if(responseInfo->result == CA_EMPTY)
1526 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1530 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1531 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1532 CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1536 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1537 || myStackMode == OC_GATEWAY)
1539 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1540 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1542 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1543 responseInfo->info.messageId);
1545 if (responseInfo->info.type == CA_MSG_RESET)
1547 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1548 responseInfo->info.messageId);
1556 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1558 VERIFY_NON_NULL_NR(endPoint, FATAL);
1559 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1561 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1563 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1564 #ifdef ROUTING_GATEWAY
1565 bool needRIHandling = false;
1567 * Routing manager is going to update either of endpoint or response or both.
1568 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1569 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1572 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1574 if(ret != OC_STACK_OK || !needRIHandling)
1576 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1582 * Put source in sender endpoint so that the next packet from application can be routed to
1583 * proper destination and remove "RM" coap header option before passing request / response to
1584 * RI as this option will make no sense to either RI or application.
1586 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1587 (uint8_t *) &(responseInfo->info.numOptions),
1588 (CAEndpoint_t *) endPoint);
1591 OCHandleResponse(endPoint, responseInfo);
1593 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1597 * This function handles error response from CA
1598 * code shall be added to handle the errors
1600 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1602 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1604 if (NULL == endPoint)
1606 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1610 if (NULL == errorInfo)
1612 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1616 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1617 errorInfo->info.tokenLength, NULL, NULL);
1620 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1621 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1622 FixUpClientResponse(&response);
1623 response.resourceUri = errorInfo->info.resourceUri;
1624 memcpy(response.identity.id, errorInfo->info.identity.id,
1625 sizeof (response.identity.id));
1626 response.identity.id_length = errorInfo->info.identity.id_length;
1627 response.result = CAResultToOCStackResult(errorInfo->result);
1629 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1632 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1636 * This function sends out Direct Stack Responses. These are responses that are not coming
1637 * from the application entity handler. These responses have no payload and are usually ACKs,
1638 * RESETs or some error conditions that were caught by the stack.
1640 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1641 const CAResponseResult_t responseResult, const CAMessageType_t type,
1642 const uint8_t numOptions, const CAHeaderOption_t *options,
1643 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1644 CADataType_t dataType)
1646 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1647 CAResponseInfo_t respInfo = {
1648 .result = responseResult
1650 respInfo.info.messageId = coapID;
1651 respInfo.info.numOptions = numOptions;
1653 if (respInfo.info.numOptions)
1655 respInfo.info.options =
1656 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1657 memcpy (respInfo.info.options, options,
1658 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1662 respInfo.info.payload = NULL;
1663 respInfo.info.token = token;
1664 respInfo.info.tokenLength = tokenLength;
1665 respInfo.info.type = type;
1666 respInfo.info.resourceUri = OICStrdup (resourceUri);
1667 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1668 respInfo.info.dataType = dataType;
1670 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1671 // Add the destination to route option from the endpoint->routeData.
1672 bool doPost = false;
1673 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1674 if(OC_STACK_OK != result)
1676 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1681 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1682 CARequestInfo_t reqInfo = {.method = CA_POST };
1683 /* The following initialization is not done in a single initializer block as in
1684 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1685 * does not have designated initalizers. This is a work-around for now.
1687 reqInfo.info.type = CA_MSG_NONCONFIRM;
1688 reqInfo.info.messageId = coapID;
1689 reqInfo.info.tokenLength = tokenLength;
1690 reqInfo.info.token = token;
1691 reqInfo.info.numOptions = respInfo.info.numOptions;
1692 reqInfo.info.payload = NULL;
1693 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1694 if (reqInfo.info.numOptions)
1696 reqInfo.info.options =
1697 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1698 if (NULL == reqInfo.info.options)
1700 OIC_LOG(ERROR, TAG, "Calloc failed");
1701 return OC_STACK_NO_MEMORY;
1703 memcpy (reqInfo.info.options, respInfo.info.options,
1704 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1707 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1708 OICFree (reqInfo.info.resourceUri);
1709 OICFree (reqInfo.info.options);
1710 OICFree (respInfo.info.resourceUri);
1711 OICFree (respInfo.info.options);
1712 if (CA_STATUS_OK != caResult)
1714 OIC_LOG(ERROR, TAG, "CASendRequest error");
1715 return CAResultToOCResult(caResult);
1721 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1723 // resourceUri in the info field is cloned in the CA layer and
1724 // thus ownership is still here.
1725 OICFree (respInfo.info.resourceUri);
1726 OICFree (respInfo.info.options);
1727 if(CA_STATUS_OK != caResult)
1729 OIC_LOG(ERROR, TAG, "CASendResponse error");
1730 return CAResultToOCResult(caResult);
1733 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1737 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1739 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1740 OCStackResult result = OC_STACK_ERROR;
1741 if(!protocolRequest)
1743 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1744 return OC_STACK_INVALID_PARAM;
1747 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1748 protocolRequest->tokenLength);
1751 OIC_LOG(INFO, TAG, "This is a new Server Request");
1752 result = AddServerRequest(&request, protocolRequest->coapID,
1753 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1754 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1755 protocolRequest->observationOption, protocolRequest->qos,
1756 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1757 protocolRequest->payload, protocolRequest->requestToken,
1758 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1759 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1760 &protocolRequest->devAddr);
1761 if (OC_STACK_OK != result)
1763 OIC_LOG(ERROR, TAG, "Error adding server request");
1769 OIC_LOG(ERROR, TAG, "Out of Memory");
1770 return OC_STACK_NO_MEMORY;
1773 if(!protocolRequest->reqMorePacket)
1775 request->requestComplete = 1;
1780 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1783 if(request->requestComplete)
1785 OIC_LOG(INFO, TAG, "This Server Request is complete");
1786 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1787 OCResource *resource = NULL;
1788 result = DetermineResourceHandling (request, &resHandling, &resource);
1789 if (result == OC_STACK_OK)
1791 result = ProcessRequest(resHandling, resource, request);
1796 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1797 result = OC_STACK_CONTINUE;
1802 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1804 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1807 if (requestInfo->info.resourceUri &&
1808 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1810 HandleKeepAliveRequest(endPoint, requestInfo);
1815 OCStackResult requestResult = OC_STACK_ERROR;
1817 if(myStackMode == OC_CLIENT)
1819 //TODO: should the client be responding to requests?
1823 OCServerProtocolRequest serverRequest = {0};
1825 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1827 char * uriWithoutQuery = NULL;
1828 char * query = NULL;
1830 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1832 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1834 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1837 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1838 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1840 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1842 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1843 OICFree(uriWithoutQuery);
1847 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1848 OICFree(uriWithoutQuery);
1855 if(strlen(query) < MAX_QUERY_LENGTH)
1857 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1862 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1868 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1870 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1871 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1872 if (!serverRequest.payload)
1874 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1877 memcpy (serverRequest.payload, requestInfo->info.payload,
1878 requestInfo->info.payloadSize);
1882 serverRequest.reqTotalSize = 0;
1885 switch (requestInfo->method)
1888 serverRequest.method = OC_REST_GET;
1891 serverRequest.method = OC_REST_PUT;
1894 serverRequest.method = OC_REST_POST;
1897 serverRequest.method = OC_REST_DELETE;
1900 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1901 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1902 requestInfo->info.type, requestInfo->info.numOptions,
1903 requestInfo->info.options, requestInfo->info.token,
1904 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1906 OICFree(serverRequest.payload);
1910 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1911 requestInfo->info.tokenLength);
1913 serverRequest.tokenLength = requestInfo->info.tokenLength;
1914 if (serverRequest.tokenLength) {
1916 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1918 if (!serverRequest.requestToken)
1920 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1921 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1922 requestInfo->info.type, requestInfo->info.numOptions,
1923 requestInfo->info.options, requestInfo->info.token,
1924 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1926 OICFree(serverRequest.payload);
1929 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1932 switch (requestInfo->info.acceptFormat)
1934 case CA_FORMAT_APPLICATION_CBOR:
1935 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1937 case CA_FORMAT_UNDEFINED:
1938 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1941 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1944 if (requestInfo->info.type == CA_MSG_CONFIRM)
1946 serverRequest.qos = OC_HIGH_QOS;
1950 serverRequest.qos = OC_LOW_QOS;
1952 // CA does not need the following field
1953 // Are we sure CA does not need them? how is it responding to multicast
1954 serverRequest.delayedResNeeded = 0;
1956 serverRequest.coapID = requestInfo->info.messageId;
1958 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1960 // copy vendor specific header options
1961 uint8_t tempNum = (requestInfo->info.numOptions);
1963 // Assume no observation requested and it is a pure GET.
1964 // If obs registration/de-registration requested it'll be fetched from the
1965 // options in GetObserveHeaderOption()
1966 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1968 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1969 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1972 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1973 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1974 requestInfo->info.type, requestInfo->info.numOptions,
1975 requestInfo->info.options, requestInfo->info.token,
1976 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1978 OICFree(serverRequest.payload);
1979 OICFree(serverRequest.requestToken);
1982 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1983 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1985 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1986 sizeof(CAHeaderOption_t)*tempNum);
1989 requestResult = HandleStackRequests (&serverRequest);
1991 // Send ACK to client as precursor to slow response
1992 if (requestResult == OC_STACK_SLOW_RESOURCE)
1994 if (requestInfo->info.type == CA_MSG_CONFIRM)
1996 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1997 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2001 if (requestResult == OC_STACK_RESOURCE_ERROR
2002 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2004 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2006 else if(!OCResultToSuccess(requestResult))
2008 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2010 CAResponseResult_t stackResponse =
2011 OCToCAStackResult(requestResult, serverRequest.method);
2013 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2014 requestInfo->info.type, requestInfo->info.numOptions,
2015 requestInfo->info.options, requestInfo->info.token,
2016 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2019 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2020 // The token is copied in there, and is thus still owned by this function.
2021 OICFree(serverRequest.payload);
2022 OICFree(serverRequest.requestToken);
2023 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2026 //This function will be called back by CA layer when a request is received
2027 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2029 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2032 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2038 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2042 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2043 #ifdef ROUTING_GATEWAY
2044 bool needRIHandling = false;
2045 bool isEmptyMsg = false;
2047 * Routing manager is going to update either of endpoint or request or both.
2048 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2049 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2050 * destination. It can also remove "RM" coap header option before passing request / response to
2051 * RI as this option will make no sense to either RI or application.
2053 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2054 &needRIHandling, &isEmptyMsg);
2055 if(OC_STACK_OK != ret || !needRIHandling)
2057 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2063 * Put source in sender endpoint so that the next packet from application can be routed to
2064 * proper destination and remove RM header option.
2066 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2067 (uint8_t *) &(requestInfo->info.numOptions),
2068 (CAEndpoint_t *) endPoint);
2070 #ifdef ROUTING_GATEWAY
2074 * In Gateways, the MSGType in route option is used to check if the actual
2075 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2076 * EMPTY response is sent in the form of POST request which need to be changed
2077 * to a EMPTY response by RM. This translation is done in this part of the code.
2079 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2080 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2081 .info.messageId = requestInfo->info.messageId,
2082 .info.type = CA_MSG_ACKNOWLEDGE};
2083 OCHandleResponse(endPoint, &respInfo);
2089 // Normal handling of the packet
2090 OCHandleRequests(endPoint, requestInfo);
2092 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2095 bool validatePlatformInfo(OCPlatformInfo info)
2098 if (!info.platformID)
2100 OIC_LOG(ERROR, TAG, "No platform ID found.");
2104 if (info.manufacturerName)
2106 size_t lenManufacturerName = strlen(info.manufacturerName);
2108 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2110 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2116 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2120 if (info.manufacturerUrl)
2122 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2124 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2131 //-----------------------------------------------------------------------------
2133 //-----------------------------------------------------------------------------
2135 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2138 !raInfo->username ||
2139 !raInfo->hostname ||
2140 !raInfo->xmpp_domain)
2143 return OC_STACK_INVALID_PARAM;
2145 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2146 gRASetInfo = (result == OC_STACK_OK)? true : false;
2152 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2156 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2159 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2161 if(stackState == OC_STACK_INITIALIZED)
2163 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2164 OCStop() between them are ignored.");
2168 #ifndef ROUTING_GATEWAY
2169 if (OC_GATEWAY == mode)
2171 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2172 return OC_STACK_INVALID_PARAM;
2179 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2180 return OC_STACK_ERROR;
2184 OCStackResult result = OC_STACK_ERROR;
2185 OIC_LOG(INFO, TAG, "Entering OCInit");
2188 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2189 || (mode == OC_GATEWAY)))
2191 OIC_LOG(ERROR, TAG, "Invalid mode");
2192 return OC_STACK_ERROR;
2196 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2198 caglobals.client = true;
2200 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2202 caglobals.server = true;
2205 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2206 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2208 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2210 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2211 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2213 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2216 defaultDeviceHandler = NULL;
2217 defaultDeviceHandlerCallbackParameter = NULL;
2219 result = CAResultToOCResult(CAInitialize());
2220 VERIFY_SUCCESS(result, OC_STACK_OK);
2222 result = CAResultToOCResult(OCSelectNetwork());
2223 VERIFY_SUCCESS(result, OC_STACK_OK);
2225 switch (myStackMode)
2228 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2229 result = CAResultToOCResult(CAStartDiscoveryServer());
2230 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2233 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2234 result = CAResultToOCResult(CAStartListeningServer());
2235 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2237 case OC_CLIENT_SERVER:
2239 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2240 result = CAResultToOCResult(CAStartListeningServer());
2241 if(result == OC_STACK_OK)
2243 result = CAResultToOCResult(CAStartDiscoveryServer());
2247 VERIFY_SUCCESS(result, OC_STACK_OK);
2250 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2253 #ifdef WITH_PRESENCE
2254 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2255 #endif // WITH_PRESENCE
2257 //Update Stack state to initialized
2258 stackState = OC_STACK_INITIALIZED;
2260 // Initialize resource
2261 if(myStackMode != OC_CLIENT)
2263 result = initResources();
2266 // Initialize the SRM Policy Engine
2267 if(result == OC_STACK_OK)
2269 result = SRMInitPolicyEngine();
2270 // TODO after BeachHead delivery: consolidate into single SRMInit()
2272 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2273 RMSetStackMode(mode);
2274 #ifdef ROUTING_GATEWAY
2275 if (OC_GATEWAY == myStackMode)
2277 result = RMInitialize();
2283 if (result == OC_STACK_OK)
2285 result = InitializeKeepAlive(myStackMode);
2290 if(result != OC_STACK_OK)
2292 OIC_LOG(ERROR, TAG, "Stack initialization error");
2293 deleteAllResources();
2295 stackState = OC_STACK_UNINITIALIZED;
2300 OCStackResult OCStop()
2302 OIC_LOG(INFO, TAG, "Entering OCStop");
2304 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2306 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2309 else if (stackState != OC_STACK_INITIALIZED)
2311 OIC_LOG(ERROR, TAG, "Stack not initialized");
2312 return OC_STACK_ERROR;
2315 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2317 #ifdef WITH_PRESENCE
2318 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2319 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2320 presenceResource.presenceTTL = 0;
2321 #endif // WITH_PRESENCE
2323 #ifdef ROUTING_GATEWAY
2324 if (OC_GATEWAY == myStackMode)
2331 TerminateKeepAlive(myStackMode);
2334 // Free memory dynamically allocated for resources
2335 deleteAllResources();
2337 DeletePlatformInfo();
2339 // Remove all observers
2340 DeleteObserverList();
2341 // Remove all the client callbacks
2342 DeleteClientCBList();
2344 // De-init the SRM Policy Engine
2345 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2346 SRMDeInitPolicyEngine();
2349 stackState = OC_STACK_UNINITIALIZED;
2353 OCStackResult OCStartMulticastServer()
2355 if(stackState != OC_STACK_INITIALIZED)
2357 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2358 return OC_STACK_ERROR;
2360 CAResult_t ret = CAStartListeningServer();
2361 if (CA_STATUS_OK != ret)
2363 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2364 return OC_STACK_ERROR;
2369 OCStackResult OCStopMulticastServer()
2371 CAResult_t ret = CAStopListeningServer();
2372 if (CA_STATUS_OK != ret)
2374 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2375 return OC_STACK_ERROR;
2380 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2385 return CA_MSG_CONFIRM;
2390 return CA_MSG_NONCONFIRM;
2395 * A request uri consists of the following components in order:
2398 * CoAP over UDP prefix "coap://"
2399 * CoAP over TCP prefix "coap+tcp://"
2400 * CoAP over DTLS prefix "coaps://"
2401 * CoAP over TLS prefix "coaps+tcp://"
2403 * IPv6 address "[1234::5678]"
2404 * IPv4 address "192.168.1.1"
2405 * optional port ":5683"
2406 * resource uri "/oc/core..."
2408 * for PRESENCE requests, extract resource type.
2410 static OCStackResult ParseRequestUri(const char *fullUri,
2411 OCTransportAdapter adapter,
2412 OCTransportFlags flags,
2413 OCDevAddr **devAddr,
2415 char **resourceType)
2417 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2419 OCStackResult result = OC_STACK_OK;
2420 OCDevAddr *da = NULL;
2424 // provide defaults for all returned values
2431 *resourceUri = NULL;
2435 *resourceType = NULL;
2438 // delimit url prefix, if any
2439 const char *start = fullUri;
2440 char *slash2 = strstr(start, "//");
2445 char *slash = strchr(start, '/');
2448 return OC_STACK_INVALID_URI;
2451 // process url scheme
2452 size_t prefixLen = slash2 - fullUri;
2456 if (((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2457 || ((prefixLen == sizeof(COAPS_TCP) - 1) && (!strncmp(fullUri, COAPS_TCP, prefixLen))))
2463 // TODO: this logic should come in with unit tests exercising the various strings
2464 // processs url prefix, if any
2465 size_t urlLen = slash - start;
2469 if (urlLen && devAddr)
2470 { // construct OCDevAddr
2471 if (start[0] == '[')
2473 char *close = strchr(++start, ']');
2474 if (!close || close > slash)
2476 return OC_STACK_INVALID_URI;
2479 if (close[1] == ':')
2486 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2490 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2492 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2496 char *dot = strchr(start, '.');
2497 if (dot && dot < slash)
2499 colon = strchr(start, ':');
2500 end = (colon && colon < slash) ? colon : slash;
2505 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2509 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2511 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2519 if (len >= sizeof(da->addr))
2521 return OC_STACK_INVALID_URI;
2523 // collect port, if any
2524 if (colon && colon < slash)
2526 for (colon++; colon < slash; colon++)
2529 if (c < '0' || c > '9')
2531 return OC_STACK_INVALID_URI;
2533 port = 10 * port + c - '0';
2538 if (len >= sizeof(da->addr))
2540 return OC_STACK_INVALID_URI;
2543 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2546 return OC_STACK_NO_MEMORY;
2548 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2550 da->adapter = adapter;
2552 if (!strncmp(fullUri, "coaps", 5))
2554 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2559 // process resource uri, if any
2561 { // request uri and query
2562 size_t ulen = strlen(slash); // resource uri length
2563 size_t tlen = 0; // resource type length
2566 static const char strPresence[] = "/oic/ad?rt=";
2567 static const size_t lenPresence = sizeof(strPresence) - 1;
2568 if (!strncmp(slash, strPresence, lenPresence))
2570 type = slash + lenPresence;
2571 tlen = ulen - lenPresence;
2576 *resourceUri = (char *)OICMalloc(ulen + 1);
2579 result = OC_STACK_NO_MEMORY;
2582 strcpy(*resourceUri, slash);
2585 if (type && resourceType)
2587 *resourceType = (char *)OICMalloc(tlen + 1);
2590 result = OC_STACK_NO_MEMORY;
2594 OICStrcpy(*resourceType, (tlen+1), type);
2601 // free all returned values
2608 OICFree(*resourceUri);
2612 OICFree(*resourceType);
2617 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2622 char uri[CA_MAX_URI_LENGTH];
2624 FormCanonicalPresenceUri(endpoint, resourceUri, uri, isMulticast);
2626 *requestUri = OICStrdup(uri);
2629 return OC_STACK_NO_MEMORY;
2636 * Discover or Perform requests on a specified resource
2638 OCStackResult OCDoResource(OCDoHandle *handle,
2640 const char *requestUri,
2641 const OCDevAddr *destination,
2643 OCConnectivityType connectivityType,
2644 OCQualityOfService qos,
2645 OCCallbackData *cbData,
2646 OCHeaderOption *options,
2649 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2651 // Validate input parameters
2652 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2653 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2655 OCStackResult result = OC_STACK_ERROR;
2656 CAResult_t caResult;
2657 CAToken_t token = NULL;
2658 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2659 ClientCB *clientCB = NULL;
2660 OCDoHandle resHandle = NULL;
2661 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2662 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2664 OCTransportAdapter adapter;
2665 OCTransportFlags flags;
2666 // the request contents are put here
2667 CARequestInfo_t requestInfo = {.method = CA_GET};
2668 // requestUri will be parsed into the following three variables
2669 OCDevAddr *devAddr = NULL;
2670 char *resourceUri = NULL;
2671 char *resourceType = NULL;
2674 * Support original behavior with address on resourceUri argument.
2676 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2677 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2681 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2682 if (result != OC_STACK_OK)
2684 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2688 else if (!checkProxyUri(options, numOptions))
2690 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2697 case OC_REST_OBSERVE:
2698 case OC_REST_OBSERVE_ALL:
2699 case OC_REST_CANCEL_OBSERVE:
2700 requestInfo.method = CA_GET;
2703 requestInfo.method = CA_PUT;
2706 requestInfo.method = CA_POST;
2708 case OC_REST_DELETE:
2709 requestInfo.method = CA_DELETE;
2711 case OC_REST_DISCOVER:
2713 #ifdef WITH_PRESENCE
2714 case OC_REST_PRESENCE:
2716 if (destination || devAddr)
2718 requestInfo.isMulticast = false;
2722 tmpDevAddr.adapter = adapter;
2723 tmpDevAddr.flags = flags;
2724 destination = &tmpDevAddr;
2725 requestInfo.isMulticast = true;
2727 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
2728 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
2729 // replacing method type with GET.
2730 requestInfo.method = CA_GET;
2733 result = OC_STACK_INVALID_METHOD;
2737 if (!devAddr && !destination)
2739 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2740 result = OC_STACK_INVALID_PARAM;
2744 /* If not original behavior, use destination argument */
2745 if (destination && !devAddr)
2747 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2750 result = OC_STACK_NO_MEMORY;
2753 *devAddr = *destination;
2756 resHandle = GenerateInvocationHandle();
2759 result = OC_STACK_NO_MEMORY;
2763 caResult = CAGenerateToken(&token, tokenLength);
2764 if (caResult != CA_STATUS_OK)
2766 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2767 result= OC_STACK_ERROR;
2771 // fill in request data
2772 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2773 requestInfo.info.token = token;
2774 requestInfo.info.tokenLength = tokenLength;
2775 requestInfo.info.resourceUri = resourceUri;
2777 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2779 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2780 options, numOptions, OC_OBSERVE_REGISTER);
2781 if (result != OC_STACK_OK)
2785 requestInfo.info.numOptions = numOptions + 1;
2789 requestInfo.info.numOptions = numOptions;
2790 requestInfo.info.options =
2791 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2792 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2793 numOptions * sizeof(CAHeaderOption_t));
2796 CopyDevAddrToEndpoint(devAddr, &endpoint);
2801 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2804 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2807 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2811 requestInfo.info.payload = NULL;
2812 requestInfo.info.payloadSize = 0;
2813 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2816 // prepare for response
2817 #ifdef WITH_PRESENCE
2818 if (method == OC_REST_PRESENCE)
2820 char *presenceUri = NULL;
2821 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri,
2822 requestInfo.isMulticast);
2823 if (OC_STACK_OK != result)
2828 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2829 // Presence notification will form a canonical uri to
2830 // look for callbacks into the application.
2831 resourceUri = presenceUri;
2835 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2836 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2837 method, devAddr, resourceUri, resourceType, ttl);
2838 if (OC_STACK_OK != result)
2843 devAddr = NULL; // Client CB list entry now owns it
2844 resourceUri = NULL; // Client CB list entry now owns it
2845 resourceType = NULL; // Client CB list entry now owns it
2848 result = OCSendRequest(&endpoint, &requestInfo);
2849 if (OC_STACK_OK != result)
2856 *handle = resHandle;
2860 if (result != OC_STACK_OK)
2862 OIC_LOG(ERROR, TAG, "OCDoResource error");
2863 FindAndDeleteClientCB(clientCB);
2864 CADestroyToken(token);
2872 // This is the owner of the payload object, so we free it
2873 OCPayloadDestroy(payload);
2874 OICFree(requestInfo.info.payload);
2876 OICFree(resourceUri);
2877 OICFree(resourceType);
2878 OICFree(requestInfo.info.options);
2882 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2886 * This ftn is implemented one of two ways in the case of observation:
2888 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2889 * Remove the callback associated on client side.
2890 * When the next notification comes in from server,
2891 * reply with RESET message to server.
2892 * Keep in mind that the server will react to RESET only
2893 * if the last notification was sent as CON
2895 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2896 * and it is associated with an observe request
2897 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2898 * Send CON Observe request to server with
2899 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2900 * Remove the callback associated on client side.
2902 OCStackResult ret = OC_STACK_OK;
2903 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2904 CARequestInfo_t requestInfo = {.method = CA_GET};
2908 return OC_STACK_INVALID_PARAM;
2911 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2914 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2915 return OC_STACK_ERROR;
2918 switch (clientCB->method)
2920 case OC_REST_OBSERVE:
2921 case OC_REST_OBSERVE_ALL:
2923 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2925 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2927 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2929 FindAndDeleteClientCB(clientCB);
2933 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2935 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2936 requestInfo.info.token = clientCB->token;
2937 requestInfo.info.tokenLength = clientCB->tokenLength;
2939 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2940 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2942 return OC_STACK_ERROR;
2944 requestInfo.info.numOptions = numOptions + 1;
2945 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2948 ret = OCSendRequest(&endpoint, &requestInfo);
2950 if (requestInfo.info.options)
2952 OICFree (requestInfo.info.options);
2954 if (requestInfo.info.resourceUri)
2956 OICFree (requestInfo.info.resourceUri);
2961 case OC_REST_DISCOVER:
2962 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2963 clientCB->requestUri);
2964 FindAndDeleteClientCB(clientCB);
2967 #ifdef WITH_PRESENCE
2968 case OC_REST_PRESENCE:
2969 FindAndDeleteClientCB(clientCB);
2974 ret = OC_STACK_INVALID_METHOD;
2982 * @brief Register Persistent storage callback.
2983 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2985 * OC_STACK_OK - No errors; Success
2986 * OC_STACK_INVALID_PARAM - Invalid parameter
2988 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2990 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2991 if(!persistentStorageHandler)
2993 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2994 return OC_STACK_INVALID_PARAM;
2998 if( !persistentStorageHandler->open ||
2999 !persistentStorageHandler->close ||
3000 !persistentStorageHandler->read ||
3001 !persistentStorageHandler->unlink ||
3002 !persistentStorageHandler->write)
3004 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3005 return OC_STACK_INVALID_PARAM;
3008 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3011 #ifdef WITH_PRESENCE
3013 OCStackResult OCProcessPresence()
3015 OCStackResult result = OC_STACK_OK;
3017 // the following line floods the log with messages that are irrelevant
3018 // to most purposes. Uncomment as needed.
3019 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3020 ClientCB* cbNode = NULL;
3021 OCClientResponse clientResponse;
3022 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3024 LL_FOREACH(cbList, cbNode)
3026 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3031 uint32_t now = GetTicks(0);
3032 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3033 cbNode->presence->TTLlevel);
3034 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3036 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3041 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3043 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3044 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3046 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3048 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3050 clientResponse.sequenceNumber = 0;
3051 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3052 clientResponse.devAddr = *cbNode->devAddr;
3053 FixUpClientResponse(&clientResponse);
3054 clientResponse.payload = NULL;
3056 // Increment the TTLLevel (going to a next state), so we don't keep
3057 // sending presence notification to client.
3058 cbNode->presence->TTLlevel++;
3059 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3060 cbNode->presence->TTLlevel);
3062 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3063 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3065 FindAndDeleteClientCB(cbNode);
3069 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3074 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3075 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3076 CARequestInfo_t requestInfo = {.method = CA_GET};
3078 OIC_LOG(DEBUG, TAG, "time to test server presence");
3080 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3082 requestData.type = CA_MSG_NONCONFIRM;
3083 requestData.token = cbNode->token;
3084 requestData.tokenLength = cbNode->tokenLength;
3085 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3086 requestInfo.method = CA_GET;
3087 requestInfo.info = requestData;
3089 result = OCSendRequest(&endpoint, &requestInfo);
3090 if (OC_STACK_OK != result)
3095 cbNode->presence->TTLlevel++;
3096 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3099 if (result != OC_STACK_OK)
3101 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3106 #endif // WITH_PRESENCE
3108 OCStackResult OCProcess()
3110 #ifdef WITH_PRESENCE
3111 OCProcessPresence();
3113 CAHandleRequestResponse();
3115 #ifdef ROUTING_GATEWAY
3125 #ifdef WITH_PRESENCE
3126 OCStackResult OCStartPresence(const uint32_t ttl)
3128 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3129 OCChangeResourceProperty(
3130 &(((OCResource *)presenceResource.handle)->resourceProperties),
3133 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3135 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3136 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3140 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3141 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3145 presenceResource.presenceTTL = ttl;
3147 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3149 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3151 presenceState = OC_PRESENCE_INITIALIZED;
3153 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3155 CAToken_t caToken = NULL;
3156 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3157 if (caResult != CA_STATUS_OK)
3159 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3160 CADestroyToken(caToken);
3161 return OC_STACK_ERROR;
3164 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3165 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3166 CADestroyToken(caToken);
3169 // Each time OCStartPresence is called
3170 // a different random 32-bit integer number is used
3171 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3173 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3174 OC_PRESENCE_TRIGGER_CREATE);
3177 OCStackResult OCStopPresence()
3179 OCStackResult result = OC_STACK_ERROR;
3181 if(presenceResource.handle)
3183 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3185 // make resource inactive
3186 result = OCChangeResourceProperty(
3187 &(((OCResource *) presenceResource.handle)->resourceProperties),
3191 if(result != OC_STACK_OK)
3194 "Changing the presence resource properties to ACTIVE not successful");
3198 return SendStopNotification();
3202 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3203 void* callbackParameter)
3205 defaultDeviceHandler = entityHandler;
3206 defaultDeviceHandlerCallbackParameter = callbackParameter;
3211 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3213 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3215 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3217 if (validatePlatformInfo(platformInfo))
3219 return SavePlatformInfo(platformInfo);
3223 return OC_STACK_INVALID_PARAM;
3228 return OC_STACK_ERROR;
3232 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3234 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3236 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3238 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3239 return OC_STACK_INVALID_PARAM;
3242 if (deviceInfo.types)
3244 OCStringLL *type = deviceInfo.types;
3245 OCResource *resource = findResource((OCResource *) deviceResource);
3248 return OC_STACK_INVALID_PARAM;
3253 OCBindResourceTypeToResource(deviceResource, type->value);
3257 return SaveDeviceInfo(deviceInfo);
3260 OCStackResult OCCreateResource(OCResourceHandle *handle,
3261 const char *resourceTypeName,
3262 const char *resourceInterfaceName,
3263 const char *uri, OCEntityHandler entityHandler,
3264 void* callbackParam,
3265 uint8_t resourceProperties)
3268 OCResource *pointer = NULL;
3269 OCStackResult result = OC_STACK_ERROR;
3271 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3273 if(myStackMode == OC_CLIENT)
3275 return OC_STACK_INVALID_PARAM;
3277 // Validate parameters
3278 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3280 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3281 return OC_STACK_INVALID_URI;
3283 // Is it presented during resource discovery?
3284 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3286 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3287 return OC_STACK_INVALID_PARAM;
3290 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3292 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3296 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3298 // Make sure resourceProperties bitmask has allowed properties specified
3299 if (resourceProperties
3300 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3301 OC_EXPLICIT_DISCOVERABLE
3310 OIC_LOG(ERROR, TAG, "Invalid property");
3311 return OC_STACK_INVALID_PARAM;
3314 // If the headResource is NULL, then no resources have been created...
3315 pointer = headResource;
3318 // At least one resources is in the resource list, so we need to search for
3319 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3322 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3324 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3325 return OC_STACK_INVALID_PARAM;
3327 pointer = pointer->next;
3330 // Create the pointer and insert it into the resource list
3331 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3334 result = OC_STACK_NO_MEMORY;
3337 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3339 insertResource(pointer);
3342 pointer->uri = OICStrdup(uri);
3345 result = OC_STACK_NO_MEMORY;
3349 // Set properties. Set OC_ACTIVE
3350 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3353 // Add the resourcetype to the resource
3354 result = BindResourceTypeToResource(pointer, resourceTypeName);
3355 if (result != OC_STACK_OK)
3357 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3361 // Add the resourceinterface to the resource
3362 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3363 if (result != OC_STACK_OK)
3365 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3369 // If an entity handler has been passed, attach it to the newly created
3370 // resource. Otherwise, set the default entity handler.
3373 pointer->entityHandler = entityHandler;
3374 pointer->entityHandlerCallbackParam = callbackParam;
3378 pointer->entityHandler = defaultResourceEHandler;
3379 pointer->entityHandlerCallbackParam = NULL;
3382 // Initialize a pointer indicating child resources in case of collection
3383 pointer->rsrcChildResourcesHead = NULL;
3386 result = OC_STACK_OK;
3388 #ifdef WITH_PRESENCE
3389 if (presenceResource.handle)
3391 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3392 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3396 if (result != OC_STACK_OK)
3398 // Deep delete of resource and other dynamic elements that it contains
3399 deleteResource(pointer);
3404 OCStackResult OCBindResource(
3405 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3407 OCResource *resource = NULL;
3408 OCChildResource *tempChildResource = NULL;
3409 OCChildResource *newChildResource = NULL;
3411 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3413 // Validate parameters
3414 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3415 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3416 // Container cannot contain itself
3417 if (collectionHandle == resourceHandle)
3419 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3420 return OC_STACK_INVALID_PARAM;
3423 // Use the handle to find the resource in the resource linked list
3424 resource = findResource((OCResource *) collectionHandle);
3427 OIC_LOG(ERROR, TAG, "Collection handle not found");
3428 return OC_STACK_INVALID_PARAM;
3431 // Look for an open slot to add add the child resource.
3432 // If found, add it and return success
3434 tempChildResource = resource->rsrcChildResourcesHead;
3436 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3438 // TODO: what if one of child resource was deregistered without unbinding?
3439 tempChildResource = tempChildResource->next;
3442 // Do memory allocation for child resource
3443 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3444 if(!newChildResource)
3446 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3447 return OC_STACK_ERROR;
3450 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3451 newChildResource->next = NULL;
3453 if(!resource->rsrcChildResourcesHead)
3455 resource->rsrcChildResourcesHead = newChildResource;
3458 tempChildResource->next = newChildResource;
3461 OIC_LOG(INFO, TAG, "resource bound");
3463 #ifdef WITH_PRESENCE
3464 if (presenceResource.handle)
3466 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3467 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3468 OC_PRESENCE_TRIGGER_CHANGE);
3475 OCStackResult OCUnBindResource(
3476 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3478 OCResource *resource = NULL;
3479 OCChildResource *tempChildResource = NULL;
3480 OCChildResource *tempLastChildResource = NULL;
3482 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3484 // Validate parameters
3485 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3486 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3487 // Container cannot contain itself
3488 if (collectionHandle == resourceHandle)
3490 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3491 return OC_STACK_INVALID_PARAM;
3494 // Use the handle to find the resource in the resource linked list
3495 resource = findResource((OCResource *) collectionHandle);
3498 OIC_LOG(ERROR, TAG, "Collection handle not found");
3499 return OC_STACK_INVALID_PARAM;
3502 // Look for an open slot to add add the child resource.
3503 // If found, add it and return success
3504 if(!resource->rsrcChildResourcesHead)
3506 OIC_LOG(INFO, TAG, "resource not found in collection");
3508 // Unable to add resourceHandle, so return error
3509 return OC_STACK_ERROR;
3513 tempChildResource = resource->rsrcChildResourcesHead;
3515 while (tempChildResource)
3517 if(tempChildResource->rsrcResource == resourceHandle)
3519 // if resource going to be unbinded is the head one.
3520 if( tempChildResource == resource->rsrcChildResourcesHead )
3522 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3523 OICFree(resource->rsrcChildResourcesHead);
3524 resource->rsrcChildResourcesHead = temp;
3529 OCChildResource *temp = tempChildResource->next;
3530 OICFree(tempChildResource);
3531 tempLastChildResource->next = temp;
3535 OIC_LOG(INFO, TAG, "resource unbound");
3537 // Send notification when resource is unbounded successfully.
3538 #ifdef WITH_PRESENCE
3539 if (presenceResource.handle)
3541 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3542 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3543 OC_PRESENCE_TRIGGER_CHANGE);
3546 tempChildResource = NULL;
3547 tempLastChildResource = NULL;
3553 tempLastChildResource = tempChildResource;
3554 tempChildResource = tempChildResource->next;
3557 OIC_LOG(INFO, TAG, "resource not found in collection");
3559 tempChildResource = NULL;
3560 tempLastChildResource = NULL;
3562 // Unable to add resourceHandle, so return error
3563 return OC_STACK_ERROR;
3566 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3568 if (!resourceItemName)
3572 // Per RFC 6690 only registered values must follow the first rule below.
3573 // At this point in time the only values registered begin with "core", and
3574 // all other values are specified as opaque strings where multiple values
3575 // are separated by a space.
3576 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3578 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3580 if (resourceItemName[index] != '.'
3581 && resourceItemName[index] != '-'
3582 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3583 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3591 for (size_t index = 0; resourceItemName[index]; ++index)
3593 if (resourceItemName[index] == ' '
3594 || resourceItemName[index] == '\t'
3595 || resourceItemName[index] == '\r'
3596 || resourceItemName[index] == '\n')
3606 OCStackResult BindResourceTypeToResource(OCResource* resource,
3607 const char *resourceTypeName)
3609 OCResourceType *pointer = NULL;
3611 OCStackResult result = OC_STACK_ERROR;
3613 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3615 if (!ValidateResourceTypeInterface(resourceTypeName))
3617 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3618 return OC_STACK_INVALID_PARAM;
3621 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3624 result = OC_STACK_NO_MEMORY;
3628 str = OICStrdup(resourceTypeName);
3631 result = OC_STACK_NO_MEMORY;
3634 pointer->resourcetypename = str;
3635 pointer->next = NULL;
3637 insertResourceType(resource, pointer);
3638 result = OC_STACK_OK;
3641 if (result != OC_STACK_OK)
3650 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3651 const char *resourceInterfaceName)
3653 OCResourceInterface *pointer = NULL;
3655 OCStackResult result = OC_STACK_ERROR;
3657 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3659 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3661 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3662 return OC_STACK_INVALID_PARAM;
3665 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3667 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3670 result = OC_STACK_NO_MEMORY;
3674 str = OICStrdup(resourceInterfaceName);
3677 result = OC_STACK_NO_MEMORY;
3680 pointer->name = str;
3682 // Bind the resourceinterface to the resource
3683 insertResourceInterface(resource, pointer);
3685 result = OC_STACK_OK;
3688 if (result != OC_STACK_OK)
3697 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3698 const char *resourceTypeName)
3701 OCStackResult result = OC_STACK_ERROR;
3702 OCResource *resource = NULL;
3704 resource = findResource((OCResource *) handle);
3707 OIC_LOG(ERROR, TAG, "Resource not found");
3708 return OC_STACK_ERROR;
3711 result = BindResourceTypeToResource(resource, resourceTypeName);
3713 #ifdef WITH_PRESENCE
3714 if(presenceResource.handle)
3716 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3717 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3724 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3725 const char *resourceInterfaceName)
3728 OCStackResult result = OC_STACK_ERROR;
3729 OCResource *resource = NULL;
3731 resource = findResource((OCResource *) handle);
3734 OIC_LOG(ERROR, TAG, "Resource not found");
3735 return OC_STACK_ERROR;
3738 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3740 #ifdef WITH_PRESENCE
3741 if (presenceResource.handle)
3743 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3744 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3751 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3753 OCResource *pointer = headResource;
3755 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3759 *numResources = *numResources + 1;
3760 pointer = pointer->next;
3765 OCResourceHandle OCGetResourceHandle(uint8_t index)
3767 OCResource *pointer = headResource;
3769 for( uint8_t i = 0; i < index && pointer; ++i)
3771 pointer = pointer->next;
3773 return (OCResourceHandle) pointer;
3776 OCStackResult OCDeleteResource(OCResourceHandle handle)
3780 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3781 return OC_STACK_INVALID_PARAM;
3784 OCResource *resource = findResource((OCResource *) handle);
3785 if (resource == NULL)
3787 OIC_LOG(ERROR, TAG, "Resource not found");
3788 return OC_STACK_NO_RESOURCE;
3791 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3793 OIC_LOG(ERROR, TAG, "Error deleting resource");
3794 return OC_STACK_ERROR;
3800 const char *OCGetResourceUri(OCResourceHandle handle)
3802 OCResource *resource = NULL;
3804 resource = findResource((OCResource *) handle);
3807 return resource->uri;
3809 return (const char *) NULL;
3812 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3814 OCResource *resource = NULL;
3816 resource = findResource((OCResource *) handle);
3819 return resource->resourceProperties;
3821 return (OCResourceProperty)-1;
3824 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3825 uint8_t *numResourceTypes)
3827 OCResource *resource = NULL;
3828 OCResourceType *pointer = NULL;
3830 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3831 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3833 *numResourceTypes = 0;
3835 resource = findResource((OCResource *) handle);
3838 pointer = resource->rsrcType;
3841 *numResourceTypes = *numResourceTypes + 1;
3842 pointer = pointer->next;
3848 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3850 OCResourceType *resourceType = NULL;
3852 resourceType = findResourceTypeAtIndex(handle, index);
3855 return resourceType->resourcetypename;
3857 return (const char *) NULL;
3860 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3861 uint8_t *numResourceInterfaces)
3863 OCResourceInterface *pointer = NULL;
3864 OCResource *resource = NULL;
3866 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3867 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3869 *numResourceInterfaces = 0;
3870 resource = findResource((OCResource *) handle);
3873 pointer = resource->rsrcInterface;
3876 *numResourceInterfaces = *numResourceInterfaces + 1;
3877 pointer = pointer->next;
3883 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3885 OCResourceInterface *resourceInterface = NULL;
3887 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3888 if (resourceInterface)
3890 return resourceInterface->name;
3892 return (const char *) NULL;
3895 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3898 OCResource *resource = NULL;
3899 OCChildResource *tempChildResource = NULL;
3902 resource = findResource((OCResource *) collectionHandle);
3908 tempChildResource = resource->rsrcChildResourcesHead;
3910 while(tempChildResource)
3914 return tempChildResource->rsrcResource;
3917 tempChildResource = tempChildResource->next;
3920 // In this case, the number of resource handles in the collection exceeds the index
3921 tempChildResource = NULL;
3925 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3926 OCEntityHandler entityHandler,
3927 void* callbackParam)
3929 OCResource *resource = NULL;
3931 // Validate parameters
3932 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3934 // Use the handle to find the resource in the resource linked list
3935 resource = findResource((OCResource *)handle);
3938 OIC_LOG(ERROR, TAG, "Resource not found");
3939 return OC_STACK_ERROR;
3943 resource->entityHandler = entityHandler;
3944 resource->entityHandlerCallbackParam = callbackParam;
3946 #ifdef WITH_PRESENCE
3947 if (presenceResource.handle)
3949 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3950 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3957 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3959 OCResource *resource = NULL;
3961 resource = findResource((OCResource *)handle);
3964 OIC_LOG(ERROR, TAG, "Resource not found");
3969 return resource->entityHandler;
3972 void incrementSequenceNumber(OCResource * resPtr)
3974 // Increment the sequence number
3975 resPtr->sequenceNum += 1;
3976 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3978 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3983 #ifdef WITH_PRESENCE
3984 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3985 OCPresenceTrigger trigger)
3987 OCResource *resPtr = NULL;
3988 OCStackResult result = OC_STACK_ERROR;
3989 OCMethod method = OC_REST_PRESENCE;
3990 uint32_t maxAge = 0;
3991 resPtr = findResource((OCResource *) presenceResource.handle);
3994 return OC_STACK_NO_RESOURCE;
3997 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3999 maxAge = presenceResource.presenceTTL;
4001 result = SendAllObserverNotification(method, resPtr, maxAge,
4002 trigger, resourceType, OC_LOW_QOS);
4008 OCStackResult SendStopNotification()
4010 OCResource *resPtr = NULL;
4011 OCStackResult result = OC_STACK_ERROR;
4012 OCMethod method = OC_REST_PRESENCE;
4013 resPtr = findResource((OCResource *) presenceResource.handle);
4016 return OC_STACK_NO_RESOURCE;
4019 // maxAge is 0. ResourceType is NULL.
4020 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4026 #endif // WITH_PRESENCE
4027 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4029 OCResource *resPtr = NULL;
4030 OCStackResult result = OC_STACK_ERROR;
4031 OCMethod method = OC_REST_NOMETHOD;
4032 uint32_t maxAge = 0;
4034 OIC_LOG(INFO, TAG, "Notifying all observers");
4035 #ifdef WITH_PRESENCE
4036 if(handle == presenceResource.handle)
4040 #endif // WITH_PRESENCE
4041 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4043 // Verify that the resource exists
4044 resPtr = findResource ((OCResource *) handle);
4047 return OC_STACK_NO_RESOURCE;
4051 //only increment in the case of regular observing (not presence)
4052 incrementSequenceNumber(resPtr);
4053 method = OC_REST_OBSERVE;
4054 maxAge = MAX_OBSERVE_AGE;
4055 #ifdef WITH_PRESENCE
4056 result = SendAllObserverNotification (method, resPtr, maxAge,
4057 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4059 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4066 OCNotifyListOfObservers (OCResourceHandle handle,
4067 OCObservationId *obsIdList,
4068 uint8_t numberOfIds,
4069 const OCRepPayload *payload,
4070 OCQualityOfService qos)
4072 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4074 OCResource *resPtr = NULL;
4075 //TODO: we should allow the server to define this
4076 uint32_t maxAge = MAX_OBSERVE_AGE;
4078 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4079 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4080 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4082 resPtr = findResource ((OCResource *) handle);
4083 if (NULL == resPtr || myStackMode == OC_CLIENT)
4085 return OC_STACK_NO_RESOURCE;
4089 incrementSequenceNumber(resPtr);
4091 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4092 payload, maxAge, qos));
4095 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4097 OCStackResult result = OC_STACK_ERROR;
4098 OCServerRequest *serverRequest = NULL;
4100 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4102 // Validate input parameters
4103 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4104 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4107 // Get pointer to request info
4108 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4111 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4112 result = serverRequest->ehResponseHandler(ehResponse);
4118 //#ifdef DIRECT_PAIRING
4119 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4121 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4122 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4124 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4128 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4131 const OCDPDev_t* OCGetDirectPairedDevices()
4133 return (const OCDPDev_t*)DPGetPairedDevices();
4136 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4137 OCDirectPairingCB resultCallback)
4139 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4140 if(NULL == peer || NULL == pinNumber)
4142 OIC_LOG(ERROR, TAG, "Invalid parameters");
4143 return OC_STACK_INVALID_PARAM;
4145 if (NULL == resultCallback)
4147 OIC_LOG(ERROR, TAG, "Invalid callback");
4148 return OC_STACK_INVALID_CALLBACK;
4151 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4152 pinNumber, (OCDirectPairingResultCB)resultCallback);
4154 //#endif // DIRECT_PAIRING
4156 //-----------------------------------------------------------------------------
4157 // Private internal function definitions
4158 //-----------------------------------------------------------------------------
4159 static OCDoHandle GenerateInvocationHandle()
4161 OCDoHandle handle = NULL;
4162 // Generate token here, it will be deleted when the transaction is deleted
4163 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4166 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4172 #ifdef WITH_PRESENCE
4173 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4174 OCResourceProperty resourceProperties, uint8_t enable)
4178 return OC_STACK_INVALID_PARAM;
4180 if (resourceProperties
4181 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4183 OIC_LOG(ERROR, TAG, "Invalid property");
4184 return OC_STACK_INVALID_PARAM;
4188 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4192 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4198 OCStackResult initResources()
4200 OCStackResult result = OC_STACK_OK;
4202 headResource = NULL;
4203 tailResource = NULL;
4204 // Init Virtual Resources
4205 #ifdef WITH_PRESENCE
4206 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4208 result = OCCreateResource(&presenceResource.handle,
4209 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4211 OC_RSRVD_PRESENCE_URI,
4215 //make resource inactive
4216 result = OCChangeResourceProperty(
4217 &(((OCResource *) presenceResource.handle)->resourceProperties),
4220 #ifndef WITH_ARDUINO
4221 if (result == OC_STACK_OK)
4223 result = SRMInitSecureResources();
4227 if(result == OC_STACK_OK)
4229 CreateResetProfile();
4230 result = OCCreateResource(&deviceResource,
4231 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4232 OC_RSRVD_INTERFACE_DEFAULT,
4233 OC_RSRVD_DEVICE_URI,
4237 if(result == OC_STACK_OK)
4239 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4240 OC_RSRVD_INTERFACE_READ);
4244 if(result == OC_STACK_OK)
4246 result = OCCreateResource(&platformResource,
4247 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4248 OC_RSRVD_INTERFACE_DEFAULT,
4249 OC_RSRVD_PLATFORM_URI,
4253 if(result == OC_STACK_OK)
4255 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4256 OC_RSRVD_INTERFACE_READ);
4263 void insertResource(OCResource *resource)
4267 headResource = resource;
4268 tailResource = resource;
4272 tailResource->next = resource;
4273 tailResource = resource;
4275 resource->next = NULL;
4278 OCResource *findResource(OCResource *resource)
4280 OCResource *pointer = headResource;
4284 if (pointer == resource)
4288 pointer = pointer->next;
4293 void deleteAllResources()
4295 OCResource *pointer = headResource;
4296 OCResource *temp = NULL;
4300 temp = pointer->next;
4301 #ifdef WITH_PRESENCE
4302 if (pointer != (OCResource *) presenceResource.handle)
4304 #endif // WITH_PRESENCE
4305 deleteResource(pointer);
4306 #ifdef WITH_PRESENCE
4308 #endif // WITH_PRESENCE
4311 memset(&platformResource, 0, sizeof(platformResource));
4312 memset(&deviceResource, 0, sizeof(deviceResource));
4314 memset(&brokerResource, 0, sizeof(brokerResource));
4317 SRMDeInitSecureResources();
4319 #ifdef WITH_PRESENCE
4320 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4321 // presence notification attributed to their deletion to be processed.
4322 deleteResource((OCResource *) presenceResource.handle);
4323 memset(&presenceResource, 0, sizeof(presenceResource));
4324 #endif // WITH_PRESENCE
4327 OCStackResult deleteResource(OCResource *resource)
4329 OCResource *prev = NULL;
4330 OCResource *temp = NULL;
4333 OIC_LOG(DEBUG,TAG,"resource is NULL");
4334 return OC_STACK_INVALID_PARAM;
4337 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4339 temp = headResource;
4342 if (temp == resource)
4344 // Invalidate all Resource Properties.
4345 resource->resourceProperties = (OCResourceProperty) 0;
4346 #ifdef WITH_PRESENCE
4347 if(resource != (OCResource *) presenceResource.handle)
4349 #endif // WITH_PRESENCE
4350 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4351 #ifdef WITH_PRESENCE
4354 if(presenceResource.handle)
4356 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4357 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4360 // Only resource in list.
4361 if (temp == headResource && temp == tailResource)
4363 headResource = NULL;
4364 tailResource = NULL;
4367 else if (temp == headResource)
4369 headResource = temp->next;
4372 else if (temp == tailResource)
4374 tailResource = prev;
4375 tailResource->next = NULL;
4379 prev->next = temp->next;
4382 deleteResourceElements(temp);
4393 return OC_STACK_ERROR;
4396 void deleteResourceElements(OCResource *resource)
4403 OICFree(resource->uri);
4404 deleteResourceType(resource->rsrcType);
4405 deleteResourceInterface(resource->rsrcInterface);
4408 void deleteResourceType(OCResourceType *resourceType)
4410 OCResourceType *pointer = resourceType;
4411 OCResourceType *next = NULL;
4415 next = pointer->next;
4416 OICFree(pointer->resourcetypename);
4422 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4424 OCResourceInterface *pointer = resourceInterface;
4425 OCResourceInterface *next = NULL;
4429 next = pointer->next;
4430 OICFree(pointer->name);
4436 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4438 OCResourceType *pointer = NULL;
4439 OCResourceType *previous = NULL;
4440 if (!resource || !resourceType)
4444 // resource type list is empty.
4445 else if (!resource->rsrcType)
4447 resource->rsrcType = resourceType;
4451 pointer = resource->rsrcType;
4455 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4457 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4458 OICFree(resourceType->resourcetypename);
4459 OICFree(resourceType);
4463 pointer = pointer->next;
4468 previous->next = resourceType;
4471 resourceType->next = NULL;
4473 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4476 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4478 OCResource *resource = NULL;
4479 OCResourceType *pointer = NULL;
4481 // Find the specified resource
4482 resource = findResource((OCResource *) handle);
4488 // Make sure a resource has a resourcetype
4489 if (!resource->rsrcType)
4494 // Iterate through the list
4495 pointer = resource->rsrcType;
4496 for(uint8_t i = 0; i< index && pointer; ++i)
4498 pointer = pointer->next;
4503 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4505 if(resourceTypeList && resourceTypeName)
4507 OCResourceType * rtPointer = resourceTypeList;
4508 while(resourceTypeName && rtPointer)
4510 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4511 if(rtPointer->resourcetypename &&
4512 strcmp(resourceTypeName, (const char *)
4513 (rtPointer->resourcetypename)) == 0)
4517 rtPointer = rtPointer->next;
4525 * Insert a new interface into interface linked list only if not already present.
4526 * If alredy present, 2nd arg is free'd.
4527 * Default interface will always be first if present.
4529 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4531 OCResourceInterface *pointer = NULL;
4532 OCResourceInterface *previous = NULL;
4534 newInterface->next = NULL;
4536 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4538 if (!*firstInterface)
4540 // If first interface is not oic.if.baseline, by default add it as first interface type.
4541 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4543 *firstInterface = newInterface;
4547 OCStackResult result = BindResourceInterfaceToResource(resource,
4548 OC_RSRVD_INTERFACE_DEFAULT);
4549 if (result != OC_STACK_OK)
4551 OICFree(newInterface->name);
4552 OICFree(newInterface);
4555 if (*firstInterface)
4557 (*firstInterface)->next = newInterface;
4561 // If once add oic.if.baseline, later too below code take care of freeing memory.
4562 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4564 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4566 OICFree(newInterface->name);
4567 OICFree(newInterface);
4570 // This code will not hit anymore, keeping
4573 newInterface->next = *firstInterface;
4574 *firstInterface = newInterface;
4579 pointer = *firstInterface;
4582 if (strcmp(newInterface->name, pointer->name) == 0)
4584 OICFree(newInterface->name);
4585 OICFree(newInterface);
4589 pointer = pointer->next;
4594 previous->next = newInterface;
4599 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4602 OCResource *resource = NULL;
4603 OCResourceInterface *pointer = NULL;
4605 // Find the specified resource
4606 resource = findResource((OCResource *) handle);
4612 // Make sure a resource has a resourceinterface
4613 if (!resource->rsrcInterface)
4618 // Iterate through the list
4619 pointer = resource->rsrcInterface;
4621 for (uint8_t i = 0; i < index && pointer; ++i)
4623 pointer = pointer->next;
4629 * This function splits the uri using the '?' delimiter.
4630 * "uriWithoutQuery" is the block of characters between the beginning
4631 * till the delimiter or '\0' which ever comes first.
4632 * "query" is whatever is to the right of the delimiter if present.
4633 * No delimiter sets the query to NULL.
4634 * If either are present, they will be malloc'ed into the params 2, 3.
4635 * The first param, *uri is left untouched.
4637 * NOTE: This function does not account for whitespace at the end of the uri NOR
4638 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4639 * part of the query.
4641 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4645 return OC_STACK_INVALID_URI;
4647 if(!query || !uriWithoutQuery)
4649 return OC_STACK_INVALID_PARAM;
4653 *uriWithoutQuery = NULL;
4655 size_t uriWithoutQueryLen = 0;
4656 size_t queryLen = 0;
4657 size_t uriLen = strlen(uri);
4659 char *pointerToDelimiter = strstr(uri, "?");
4661 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4662 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4664 if (uriWithoutQueryLen)
4666 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4667 if (!*uriWithoutQuery)
4671 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4675 *query = (char *) OICCalloc(queryLen + 1, 1);
4678 OICFree(*uriWithoutQuery);
4679 *uriWithoutQuery = NULL;
4682 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4688 return OC_STACK_NO_MEMORY;
4691 static const OicUuid_t* OCGetServerInstanceID(void)
4693 static bool generated = false;
4694 static OicUuid_t sid;
4700 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4702 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4709 const char* OCGetServerInstanceIDString(void)
4711 static bool generated = false;
4712 static char sidStr[UUID_STRING_SIZE];
4719 const OicUuid_t *sid = OCGetServerInstanceID();
4720 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4722 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4730 CAResult_t OCSelectNetwork()
4732 CAResult_t retResult = CA_STATUS_FAILED;
4733 CAResult_t caResult = CA_STATUS_OK;
4735 CATransportAdapter_t connTypes[] = {
4737 CA_ADAPTER_RFCOMM_BTEDR,
4738 CA_ADAPTER_GATT_BTLE,
4741 ,CA_ADAPTER_REMOTE_ACCESS
4748 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4750 for(int i = 0; i < numConnTypes; i++)
4752 // If CA status is not initialized, CASelectNetwork() will not be called.
4753 if (caResult != CA_STATUS_NOT_INITIALIZED)
4755 caResult = CASelectNetwork(connTypes[i]);
4756 if (caResult == CA_STATUS_OK)
4758 retResult = CA_STATUS_OK;
4763 if (retResult != CA_STATUS_OK)
4765 return caResult; // Returns error of appropriate transport that failed fatally.
4771 OCStackResult CAResultToOCResult(CAResult_t caResult)
4777 case CA_STATUS_INVALID_PARAM:
4778 return OC_STACK_INVALID_PARAM;
4779 case CA_ADAPTER_NOT_ENABLED:
4780 return OC_STACK_ADAPTER_NOT_ENABLED;
4781 case CA_SERVER_STARTED_ALREADY:
4783 case CA_SERVER_NOT_STARTED:
4784 return OC_STACK_ERROR;
4785 case CA_DESTINATION_NOT_REACHABLE:
4786 return OC_STACK_COMM_ERROR;
4787 case CA_SOCKET_OPERATION_FAILED:
4788 return OC_STACK_COMM_ERROR;
4789 case CA_SEND_FAILED:
4790 return OC_STACK_COMM_ERROR;
4791 case CA_RECEIVE_FAILED:
4792 return OC_STACK_COMM_ERROR;
4793 case CA_MEMORY_ALLOC_FAILED:
4794 return OC_STACK_NO_MEMORY;
4795 case CA_REQUEST_TIMEOUT:
4796 return OC_STACK_TIMEOUT;
4797 case CA_DESTINATION_DISCONNECTED:
4798 return OC_STACK_COMM_ERROR;
4799 case CA_STATUS_FAILED:
4800 return OC_STACK_ERROR;
4801 case CA_NOT_SUPPORTED:
4802 return OC_STACK_NOTIMPL;
4804 return OC_STACK_ERROR;
4808 bool OCResultToSuccess(OCStackResult ocResult)
4813 case OC_STACK_RESOURCE_CREATED:
4814 case OC_STACK_RESOURCE_DELETED:
4815 case OC_STACK_CONTINUE:
4816 case OC_STACK_RESOURCE_CHANGED:
4817 case OC_STACK_SLOW_RESOURCE:
4825 OCStackResult OCSetProxyURI(const char *uri)
4827 return CAResultToOCResult(CASetProxyUri(uri));
4831 #if defined(RD_CLIENT) || defined(RD_SERVER)
4832 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
4834 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4836 OCResource *resource = NULL;
4838 resource = findResource((OCResource *) handle);
4841 OIC_LOG(ERROR, TAG, "Resource not found");
4842 return OC_STACK_ERROR;
4845 resource->ins = ins;
4850 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
4854 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
4858 OCResource *pointer = headResource;
4862 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
4864 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
4867 pointer = pointer->next;
4872 OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
4874 OCResource *resource = NULL;
4876 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4877 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
4879 resource = findResource((OCResource *) handle);
4882 *ins = resource->ins;
4885 return OC_STACK_ERROR;