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 else if(!OCResultToSuccess(requestResult))
2003 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2005 CAResponseResult_t stackResponse =
2006 OCToCAStackResult(requestResult, serverRequest.method);
2008 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2009 requestInfo->info.type, requestInfo->info.numOptions,
2010 requestInfo->info.options, requestInfo->info.token,
2011 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2014 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2015 // The token is copied in there, and is thus still owned by this function.
2016 OICFree(serverRequest.payload);
2017 OICFree(serverRequest.requestToken);
2018 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2021 //This function will be called back by CA layer when a request is received
2022 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2024 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2027 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2033 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2037 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2038 #ifdef ROUTING_GATEWAY
2039 bool needRIHandling = false;
2040 bool isEmptyMsg = false;
2042 * Routing manager is going to update either of endpoint or request or both.
2043 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2044 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2045 * destination. It can also remove "RM" coap header option before passing request / response to
2046 * RI as this option will make no sense to either RI or application.
2048 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2049 &needRIHandling, &isEmptyMsg);
2050 if(OC_STACK_OK != ret || !needRIHandling)
2052 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2058 * Put source in sender endpoint so that the next packet from application can be routed to
2059 * proper destination and remove RM header option.
2061 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2062 (uint8_t *) &(requestInfo->info.numOptions),
2063 (CAEndpoint_t *) endPoint);
2065 #ifdef ROUTING_GATEWAY
2069 * In Gateways, the MSGType in route option is used to check if the actual
2070 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2071 * EMPTY response is sent in the form of POST request which need to be changed
2072 * to a EMPTY response by RM. This translation is done in this part of the code.
2074 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2075 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2076 .info.messageId = requestInfo->info.messageId,
2077 .info.type = CA_MSG_ACKNOWLEDGE};
2078 OCHandleResponse(endPoint, &respInfo);
2084 // Normal handling of the packet
2085 OCHandleRequests(endPoint, requestInfo);
2087 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2090 bool validatePlatformInfo(OCPlatformInfo info)
2093 if (!info.platformID)
2095 OIC_LOG(ERROR, TAG, "No platform ID found.");
2099 if (info.manufacturerName)
2101 size_t lenManufacturerName = strlen(info.manufacturerName);
2103 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2105 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2111 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2115 if (info.manufacturerUrl)
2117 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2119 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2126 //-----------------------------------------------------------------------------
2128 //-----------------------------------------------------------------------------
2130 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2133 !raInfo->username ||
2134 !raInfo->hostname ||
2135 !raInfo->xmpp_domain)
2138 return OC_STACK_INVALID_PARAM;
2140 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2141 gRASetInfo = (result == OC_STACK_OK)? true : false;
2147 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2151 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2154 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2156 if(stackState == OC_STACK_INITIALIZED)
2158 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2159 OCStop() between them are ignored.");
2163 #ifndef ROUTING_GATEWAY
2164 if (OC_GATEWAY == mode)
2166 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2167 return OC_STACK_INVALID_PARAM;
2174 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2175 return OC_STACK_ERROR;
2179 OCStackResult result = OC_STACK_ERROR;
2180 OIC_LOG(INFO, TAG, "Entering OCInit");
2183 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2184 || (mode == OC_GATEWAY)))
2186 OIC_LOG(ERROR, TAG, "Invalid mode");
2187 return OC_STACK_ERROR;
2191 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2193 caglobals.client = true;
2195 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2197 caglobals.server = true;
2200 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2201 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2203 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2205 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2206 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2208 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2211 defaultDeviceHandler = NULL;
2212 defaultDeviceHandlerCallbackParameter = NULL;
2214 result = CAResultToOCResult(CAInitialize());
2215 VERIFY_SUCCESS(result, OC_STACK_OK);
2217 result = CAResultToOCResult(OCSelectNetwork());
2218 VERIFY_SUCCESS(result, OC_STACK_OK);
2220 switch (myStackMode)
2223 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2224 result = CAResultToOCResult(CAStartDiscoveryServer());
2225 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2228 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2229 result = CAResultToOCResult(CAStartListeningServer());
2230 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2232 case OC_CLIENT_SERVER:
2234 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2235 result = CAResultToOCResult(CAStartListeningServer());
2236 if(result == OC_STACK_OK)
2238 result = CAResultToOCResult(CAStartDiscoveryServer());
2242 VERIFY_SUCCESS(result, OC_STACK_OK);
2245 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2248 #ifdef WITH_PRESENCE
2249 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2250 #endif // WITH_PRESENCE
2252 //Update Stack state to initialized
2253 stackState = OC_STACK_INITIALIZED;
2255 // Initialize resource
2256 if(myStackMode != OC_CLIENT)
2258 result = initResources();
2261 // Initialize the SRM Policy Engine
2262 if(result == OC_STACK_OK)
2264 result = SRMInitPolicyEngine();
2265 // TODO after BeachHead delivery: consolidate into single SRMInit()
2267 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2268 RMSetStackMode(mode);
2269 #ifdef ROUTING_GATEWAY
2270 if (OC_GATEWAY == myStackMode)
2272 result = RMInitialize();
2278 if (result == OC_STACK_OK)
2280 result = InitializeKeepAlive(myStackMode);
2285 if(result != OC_STACK_OK)
2287 OIC_LOG(ERROR, TAG, "Stack initialization error");
2288 deleteAllResources();
2290 stackState = OC_STACK_UNINITIALIZED;
2295 OCStackResult OCStop()
2297 OIC_LOG(INFO, TAG, "Entering OCStop");
2299 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2301 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2304 else if (stackState != OC_STACK_INITIALIZED)
2306 OIC_LOG(ERROR, TAG, "Stack not initialized");
2307 return OC_STACK_ERROR;
2310 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2312 #ifdef WITH_PRESENCE
2313 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2314 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2315 presenceResource.presenceTTL = 0;
2316 #endif // WITH_PRESENCE
2318 #ifdef ROUTING_GATEWAY
2319 if (OC_GATEWAY == myStackMode)
2326 TerminateKeepAlive(myStackMode);
2329 // Free memory dynamically allocated for resources
2330 deleteAllResources();
2332 DeletePlatformInfo();
2334 // Remove all observers
2335 DeleteObserverList();
2336 // Remove all the client callbacks
2337 DeleteClientCBList();
2339 // De-init the SRM Policy Engine
2340 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2341 SRMDeInitPolicyEngine();
2344 stackState = OC_STACK_UNINITIALIZED;
2348 OCStackResult OCStartMulticastServer()
2350 if(stackState != OC_STACK_INITIALIZED)
2352 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2353 return OC_STACK_ERROR;
2355 CAResult_t ret = CAStartListeningServer();
2356 if (CA_STATUS_OK != ret)
2358 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2359 return OC_STACK_ERROR;
2364 OCStackResult OCStopMulticastServer()
2366 CAResult_t ret = CAStopListeningServer();
2367 if (CA_STATUS_OK != ret)
2369 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2370 return OC_STACK_ERROR;
2375 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2380 return CA_MSG_CONFIRM;
2385 return CA_MSG_NONCONFIRM;
2390 * A request uri consists of the following components in order:
2393 * CoAP over UDP prefix "coap://"
2394 * CoAP over TCP prefix "coap+tcp://"
2395 * CoAP over DTLS prefix "coaps://"
2396 * CoAP over TLS prefix "coaps+tcp://"
2398 * IPv6 address "[1234::5678]"
2399 * IPv4 address "192.168.1.1"
2400 * optional port ":5683"
2401 * resource uri "/oc/core..."
2403 * for PRESENCE requests, extract resource type.
2405 static OCStackResult ParseRequestUri(const char *fullUri,
2406 OCTransportAdapter adapter,
2407 OCTransportFlags flags,
2408 OCDevAddr **devAddr,
2410 char **resourceType)
2412 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2414 OCStackResult result = OC_STACK_OK;
2415 OCDevAddr *da = NULL;
2419 // provide defaults for all returned values
2426 *resourceUri = NULL;
2430 *resourceType = NULL;
2433 // delimit url prefix, if any
2434 const char *start = fullUri;
2435 char *slash2 = strstr(start, "//");
2440 char *slash = strchr(start, '/');
2443 return OC_STACK_INVALID_URI;
2446 // process url scheme
2447 size_t prefixLen = slash2 - fullUri;
2451 if (((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2452 || ((prefixLen == sizeof(COAPS_TCP) - 1) && (!strncmp(fullUri, COAPS_TCP, prefixLen))))
2458 // TODO: this logic should come in with unit tests exercising the various strings
2459 // processs url prefix, if any
2460 size_t urlLen = slash - start;
2464 if (urlLen && devAddr)
2465 { // construct OCDevAddr
2466 if (start[0] == '[')
2468 char *close = strchr(++start, ']');
2469 if (!close || close > slash)
2471 return OC_STACK_INVALID_URI;
2474 if (close[1] == ':')
2481 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2485 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2487 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2491 char *dot = strchr(start, '.');
2492 if (dot && dot < slash)
2494 colon = strchr(start, ':');
2495 end = (colon && colon < slash) ? colon : slash;
2500 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2504 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2506 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2514 if (len >= sizeof(da->addr))
2516 return OC_STACK_INVALID_URI;
2518 // collect port, if any
2519 if (colon && colon < slash)
2521 for (colon++; colon < slash; colon++)
2524 if (c < '0' || c > '9')
2526 return OC_STACK_INVALID_URI;
2528 port = 10 * port + c - '0';
2533 if (len >= sizeof(da->addr))
2535 return OC_STACK_INVALID_URI;
2538 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2541 return OC_STACK_NO_MEMORY;
2543 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2545 da->adapter = adapter;
2547 if (!strncmp(fullUri, "coaps", 5))
2549 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2554 // process resource uri, if any
2556 { // request uri and query
2557 size_t ulen = strlen(slash); // resource uri length
2558 size_t tlen = 0; // resource type length
2561 static const char strPresence[] = "/oic/ad?rt=";
2562 static const size_t lenPresence = sizeof(strPresence) - 1;
2563 if (!strncmp(slash, strPresence, lenPresence))
2565 type = slash + lenPresence;
2566 tlen = ulen - lenPresence;
2571 *resourceUri = (char *)OICMalloc(ulen + 1);
2574 result = OC_STACK_NO_MEMORY;
2577 strcpy(*resourceUri, slash);
2580 if (type && resourceType)
2582 *resourceType = (char *)OICMalloc(tlen + 1);
2585 result = OC_STACK_NO_MEMORY;
2589 OICStrcpy(*resourceType, (tlen+1), type);
2596 // free all returned values
2603 OICFree(*resourceUri);
2607 OICFree(*resourceType);
2612 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2617 char uri[CA_MAX_URI_LENGTH];
2619 FormCanonicalPresenceUri(endpoint, resourceUri, uri, isMulticast);
2621 *requestUri = OICStrdup(uri);
2624 return OC_STACK_NO_MEMORY;
2631 * Discover or Perform requests on a specified resource
2633 OCStackResult OCDoResource(OCDoHandle *handle,
2635 const char *requestUri,
2636 const OCDevAddr *destination,
2638 OCConnectivityType connectivityType,
2639 OCQualityOfService qos,
2640 OCCallbackData *cbData,
2641 OCHeaderOption *options,
2644 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2646 // Validate input parameters
2647 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2648 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2650 OCStackResult result = OC_STACK_ERROR;
2651 CAResult_t caResult;
2652 CAToken_t token = NULL;
2653 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2654 ClientCB *clientCB = NULL;
2655 OCDoHandle resHandle = NULL;
2656 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2657 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2659 OCTransportAdapter adapter;
2660 OCTransportFlags flags;
2661 // the request contents are put here
2662 CARequestInfo_t requestInfo = {.method = CA_GET};
2663 // requestUri will be parsed into the following three variables
2664 OCDevAddr *devAddr = NULL;
2665 char *resourceUri = NULL;
2666 char *resourceType = NULL;
2669 * Support original behavior with address on resourceUri argument.
2671 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2672 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2676 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2677 if (result != OC_STACK_OK)
2679 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2683 else if (!checkProxyUri(options, numOptions))
2685 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2692 case OC_REST_OBSERVE:
2693 case OC_REST_OBSERVE_ALL:
2694 case OC_REST_CANCEL_OBSERVE:
2695 requestInfo.method = CA_GET;
2698 requestInfo.method = CA_PUT;
2701 requestInfo.method = CA_POST;
2703 case OC_REST_DELETE:
2704 requestInfo.method = CA_DELETE;
2706 case OC_REST_DISCOVER:
2708 #ifdef WITH_PRESENCE
2709 case OC_REST_PRESENCE:
2711 if (destination || devAddr)
2713 requestInfo.isMulticast = false;
2717 tmpDevAddr.adapter = adapter;
2718 tmpDevAddr.flags = flags;
2719 destination = &tmpDevAddr;
2720 requestInfo.isMulticast = true;
2722 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
2723 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
2724 // replacing method type with GET.
2725 requestInfo.method = CA_GET;
2728 result = OC_STACK_INVALID_METHOD;
2732 if (!devAddr && !destination)
2734 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2735 result = OC_STACK_INVALID_PARAM;
2739 /* If not original behavior, use destination argument */
2740 if (destination && !devAddr)
2742 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2745 result = OC_STACK_NO_MEMORY;
2748 *devAddr = *destination;
2751 resHandle = GenerateInvocationHandle();
2754 result = OC_STACK_NO_MEMORY;
2758 caResult = CAGenerateToken(&token, tokenLength);
2759 if (caResult != CA_STATUS_OK)
2761 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2762 result= OC_STACK_ERROR;
2766 // fill in request data
2767 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2768 requestInfo.info.token = token;
2769 requestInfo.info.tokenLength = tokenLength;
2770 requestInfo.info.resourceUri = resourceUri;
2772 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2774 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2775 options, numOptions, OC_OBSERVE_REGISTER);
2776 if (result != OC_STACK_OK)
2780 requestInfo.info.numOptions = numOptions + 1;
2784 requestInfo.info.numOptions = numOptions;
2785 requestInfo.info.options =
2786 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2787 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2788 numOptions * sizeof(CAHeaderOption_t));
2791 CopyDevAddrToEndpoint(devAddr, &endpoint);
2796 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2799 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2802 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2806 requestInfo.info.payload = NULL;
2807 requestInfo.info.payloadSize = 0;
2808 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2811 // prepare for response
2812 #ifdef WITH_PRESENCE
2813 if (method == OC_REST_PRESENCE)
2815 char *presenceUri = NULL;
2816 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri,
2817 requestInfo.isMulticast);
2818 if (OC_STACK_OK != result)
2823 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2824 // Presence notification will form a canonical uri to
2825 // look for callbacks into the application.
2826 resourceUri = presenceUri;
2830 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2831 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2832 method, devAddr, resourceUri, resourceType, ttl);
2833 if (OC_STACK_OK != result)
2838 devAddr = NULL; // Client CB list entry now owns it
2839 resourceUri = NULL; // Client CB list entry now owns it
2840 resourceType = NULL; // Client CB list entry now owns it
2843 result = OCSendRequest(&endpoint, &requestInfo);
2844 if (OC_STACK_OK != result)
2851 *handle = resHandle;
2855 if (result != OC_STACK_OK)
2857 OIC_LOG(ERROR, TAG, "OCDoResource error");
2858 FindAndDeleteClientCB(clientCB);
2859 CADestroyToken(token);
2867 // This is the owner of the payload object, so we free it
2868 OCPayloadDestroy(payload);
2869 OICFree(requestInfo.info.payload);
2871 OICFree(resourceUri);
2872 OICFree(resourceType);
2873 OICFree(requestInfo.info.options);
2877 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2881 * This ftn is implemented one of two ways in the case of observation:
2883 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2884 * Remove the callback associated on client side.
2885 * When the next notification comes in from server,
2886 * reply with RESET message to server.
2887 * Keep in mind that the server will react to RESET only
2888 * if the last notification was sent as CON
2890 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2891 * and it is associated with an observe request
2892 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2893 * Send CON Observe request to server with
2894 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2895 * Remove the callback associated on client side.
2897 OCStackResult ret = OC_STACK_OK;
2898 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2899 CARequestInfo_t requestInfo = {.method = CA_GET};
2903 return OC_STACK_INVALID_PARAM;
2906 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2909 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2910 return OC_STACK_ERROR;
2913 switch (clientCB->method)
2915 case OC_REST_OBSERVE:
2916 case OC_REST_OBSERVE_ALL:
2918 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2920 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2922 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2924 FindAndDeleteClientCB(clientCB);
2928 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2930 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2931 requestInfo.info.token = clientCB->token;
2932 requestInfo.info.tokenLength = clientCB->tokenLength;
2934 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2935 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2937 return OC_STACK_ERROR;
2939 requestInfo.info.numOptions = numOptions + 1;
2940 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2943 ret = OCSendRequest(&endpoint, &requestInfo);
2945 if (requestInfo.info.options)
2947 OICFree (requestInfo.info.options);
2949 if (requestInfo.info.resourceUri)
2951 OICFree (requestInfo.info.resourceUri);
2956 case OC_REST_DISCOVER:
2957 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2958 clientCB->requestUri);
2959 FindAndDeleteClientCB(clientCB);
2962 #ifdef WITH_PRESENCE
2963 case OC_REST_PRESENCE:
2964 FindAndDeleteClientCB(clientCB);
2969 ret = OC_STACK_INVALID_METHOD;
2977 * @brief Register Persistent storage callback.
2978 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2980 * OC_STACK_OK - No errors; Success
2981 * OC_STACK_INVALID_PARAM - Invalid parameter
2983 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2985 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2986 if(!persistentStorageHandler)
2988 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2989 return OC_STACK_INVALID_PARAM;
2993 if( !persistentStorageHandler->open ||
2994 !persistentStorageHandler->close ||
2995 !persistentStorageHandler->read ||
2996 !persistentStorageHandler->unlink ||
2997 !persistentStorageHandler->write)
2999 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3000 return OC_STACK_INVALID_PARAM;
3003 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3006 #ifdef WITH_PRESENCE
3008 OCStackResult OCProcessPresence()
3010 OCStackResult result = OC_STACK_OK;
3012 // the following line floods the log with messages that are irrelevant
3013 // to most purposes. Uncomment as needed.
3014 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3015 ClientCB* cbNode = NULL;
3016 OCClientResponse clientResponse;
3017 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3019 LL_FOREACH(cbList, cbNode)
3021 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3026 uint32_t now = GetTicks(0);
3027 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3028 cbNode->presence->TTLlevel);
3029 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3031 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3036 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3038 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3039 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3041 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3043 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3045 clientResponse.sequenceNumber = 0;
3046 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3047 clientResponse.devAddr = *cbNode->devAddr;
3048 FixUpClientResponse(&clientResponse);
3049 clientResponse.payload = NULL;
3051 // Increment the TTLLevel (going to a next state), so we don't keep
3052 // sending presence notification to client.
3053 cbNode->presence->TTLlevel++;
3054 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3055 cbNode->presence->TTLlevel);
3057 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3058 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3060 FindAndDeleteClientCB(cbNode);
3064 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3069 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3070 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3071 CARequestInfo_t requestInfo = {.method = CA_GET};
3073 OIC_LOG(DEBUG, TAG, "time to test server presence");
3075 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3077 requestData.type = CA_MSG_NONCONFIRM;
3078 requestData.token = cbNode->token;
3079 requestData.tokenLength = cbNode->tokenLength;
3080 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3081 requestInfo.method = CA_GET;
3082 requestInfo.info = requestData;
3084 result = OCSendRequest(&endpoint, &requestInfo);
3085 if (OC_STACK_OK != result)
3090 cbNode->presence->TTLlevel++;
3091 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3094 if (result != OC_STACK_OK)
3096 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3101 #endif // WITH_PRESENCE
3103 OCStackResult OCProcess()
3105 #ifdef WITH_PRESENCE
3106 OCProcessPresence();
3108 CAHandleRequestResponse();
3110 #ifdef ROUTING_GATEWAY
3120 #ifdef WITH_PRESENCE
3121 OCStackResult OCStartPresence(const uint32_t ttl)
3123 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3124 OCChangeResourceProperty(
3125 &(((OCResource *)presenceResource.handle)->resourceProperties),
3128 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3130 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3131 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3135 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3136 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3140 presenceResource.presenceTTL = ttl;
3142 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3144 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3146 presenceState = OC_PRESENCE_INITIALIZED;
3148 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3150 CAToken_t caToken = NULL;
3151 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3152 if (caResult != CA_STATUS_OK)
3154 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3155 CADestroyToken(caToken);
3156 return OC_STACK_ERROR;
3159 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3160 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3161 CADestroyToken(caToken);
3164 // Each time OCStartPresence is called
3165 // a different random 32-bit integer number is used
3166 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3168 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3169 OC_PRESENCE_TRIGGER_CREATE);
3172 OCStackResult OCStopPresence()
3174 OCStackResult result = OC_STACK_ERROR;
3176 if(presenceResource.handle)
3178 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3180 // make resource inactive
3181 result = OCChangeResourceProperty(
3182 &(((OCResource *) presenceResource.handle)->resourceProperties),
3186 if(result != OC_STACK_OK)
3189 "Changing the presence resource properties to ACTIVE not successful");
3193 return SendStopNotification();
3197 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3198 void* callbackParameter)
3200 defaultDeviceHandler = entityHandler;
3201 defaultDeviceHandlerCallbackParameter = callbackParameter;
3206 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3208 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3210 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3212 if (validatePlatformInfo(platformInfo))
3214 return SavePlatformInfo(platformInfo);
3218 return OC_STACK_INVALID_PARAM;
3223 return OC_STACK_ERROR;
3227 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3229 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3231 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3233 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3234 return OC_STACK_INVALID_PARAM;
3237 if (deviceInfo.types)
3239 OCStringLL *type = deviceInfo.types;
3240 OCResource *resource = findResource((OCResource *) deviceResource);
3243 return OC_STACK_INVALID_PARAM;
3248 OCBindResourceTypeToResource(deviceResource, type->value);
3252 return SaveDeviceInfo(deviceInfo);
3255 OCStackResult OCCreateResource(OCResourceHandle *handle,
3256 const char *resourceTypeName,
3257 const char *resourceInterfaceName,
3258 const char *uri, OCEntityHandler entityHandler,
3259 void* callbackParam,
3260 uint8_t resourceProperties)
3263 OCResource *pointer = NULL;
3264 OCStackResult result = OC_STACK_ERROR;
3266 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3268 if(myStackMode == OC_CLIENT)
3270 return OC_STACK_INVALID_PARAM;
3272 // Validate parameters
3273 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3275 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3276 return OC_STACK_INVALID_URI;
3278 // Is it presented during resource discovery?
3279 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3281 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3282 return OC_STACK_INVALID_PARAM;
3285 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3287 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3291 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3293 // Make sure resourceProperties bitmask has allowed properties specified
3294 if (resourceProperties
3295 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3296 OC_EXPLICIT_DISCOVERABLE
3305 OIC_LOG(ERROR, TAG, "Invalid property");
3306 return OC_STACK_INVALID_PARAM;
3309 // If the headResource is NULL, then no resources have been created...
3310 pointer = headResource;
3313 // At least one resources is in the resource list, so we need to search for
3314 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3317 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3319 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3320 return OC_STACK_INVALID_PARAM;
3322 pointer = pointer->next;
3325 // Create the pointer and insert it into the resource list
3326 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3329 result = OC_STACK_NO_MEMORY;
3332 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3334 insertResource(pointer);
3337 pointer->uri = OICStrdup(uri);
3340 result = OC_STACK_NO_MEMORY;
3344 // Set properties. Set OC_ACTIVE
3345 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3348 // Add the resourcetype to the resource
3349 result = BindResourceTypeToResource(pointer, resourceTypeName);
3350 if (result != OC_STACK_OK)
3352 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3356 // Add the resourceinterface to the resource
3357 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3358 if (result != OC_STACK_OK)
3360 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3364 // If an entity handler has been passed, attach it to the newly created
3365 // resource. Otherwise, set the default entity handler.
3368 pointer->entityHandler = entityHandler;
3369 pointer->entityHandlerCallbackParam = callbackParam;
3373 pointer->entityHandler = defaultResourceEHandler;
3374 pointer->entityHandlerCallbackParam = NULL;
3377 // Initialize a pointer indicating child resources in case of collection
3378 pointer->rsrcChildResourcesHead = NULL;
3381 result = OC_STACK_OK;
3383 #ifdef WITH_PRESENCE
3384 if (presenceResource.handle)
3386 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3387 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3391 if (result != OC_STACK_OK)
3393 // Deep delete of resource and other dynamic elements that it contains
3394 deleteResource(pointer);
3399 OCStackResult OCBindResource(
3400 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3402 OCResource *resource = NULL;
3403 OCChildResource *tempChildResource = NULL;
3404 OCChildResource *newChildResource = NULL;
3406 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3408 // Validate parameters
3409 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3410 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3411 // Container cannot contain itself
3412 if (collectionHandle == resourceHandle)
3414 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3415 return OC_STACK_INVALID_PARAM;
3418 // Use the handle to find the resource in the resource linked list
3419 resource = findResource((OCResource *) collectionHandle);
3422 OIC_LOG(ERROR, TAG, "Collection handle not found");
3423 return OC_STACK_INVALID_PARAM;
3426 // Look for an open slot to add add the child resource.
3427 // If found, add it and return success
3429 tempChildResource = resource->rsrcChildResourcesHead;
3431 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3433 // TODO: what if one of child resource was deregistered without unbinding?
3434 tempChildResource = tempChildResource->next;
3437 // Do memory allocation for child resource
3438 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3439 if(!newChildResource)
3441 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3442 return OC_STACK_ERROR;
3445 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3446 newChildResource->next = NULL;
3448 if(!resource->rsrcChildResourcesHead)
3450 resource->rsrcChildResourcesHead = newChildResource;
3453 tempChildResource->next = newChildResource;
3456 OIC_LOG(INFO, TAG, "resource bound");
3458 #ifdef WITH_PRESENCE
3459 if (presenceResource.handle)
3461 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3462 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3463 OC_PRESENCE_TRIGGER_CHANGE);
3470 OCStackResult OCUnBindResource(
3471 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3473 OCResource *resource = NULL;
3474 OCChildResource *tempChildResource = NULL;
3475 OCChildResource *tempLastChildResource = NULL;
3477 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3479 // Validate parameters
3480 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3481 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3482 // Container cannot contain itself
3483 if (collectionHandle == resourceHandle)
3485 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3486 return OC_STACK_INVALID_PARAM;
3489 // Use the handle to find the resource in the resource linked list
3490 resource = findResource((OCResource *) collectionHandle);
3493 OIC_LOG(ERROR, TAG, "Collection handle not found");
3494 return OC_STACK_INVALID_PARAM;
3497 // Look for an open slot to add add the child resource.
3498 // If found, add it and return success
3499 if(!resource->rsrcChildResourcesHead)
3501 OIC_LOG(INFO, TAG, "resource not found in collection");
3503 // Unable to add resourceHandle, so return error
3504 return OC_STACK_ERROR;
3508 tempChildResource = resource->rsrcChildResourcesHead;
3510 while (tempChildResource)
3512 if(tempChildResource->rsrcResource == resourceHandle)
3514 // if resource going to be unbinded is the head one.
3515 if( tempChildResource == resource->rsrcChildResourcesHead )
3517 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3518 OICFree(resource->rsrcChildResourcesHead);
3519 resource->rsrcChildResourcesHead = temp;
3524 OCChildResource *temp = tempChildResource->next;
3525 OICFree(tempChildResource);
3526 tempLastChildResource->next = temp;
3530 OIC_LOG(INFO, TAG, "resource unbound");
3532 // Send notification when resource is unbounded successfully.
3533 #ifdef WITH_PRESENCE
3534 if (presenceResource.handle)
3536 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3537 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3538 OC_PRESENCE_TRIGGER_CHANGE);
3541 tempChildResource = NULL;
3542 tempLastChildResource = NULL;
3548 tempLastChildResource = tempChildResource;
3549 tempChildResource = tempChildResource->next;
3552 OIC_LOG(INFO, TAG, "resource not found in collection");
3554 tempChildResource = NULL;
3555 tempLastChildResource = NULL;
3557 // Unable to add resourceHandle, so return error
3558 return OC_STACK_ERROR;
3561 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3563 if (!resourceItemName)
3567 // Per RFC 6690 only registered values must follow the first rule below.
3568 // At this point in time the only values registered begin with "core", and
3569 // all other values are specified as opaque strings where multiple values
3570 // are separated by a space.
3571 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3573 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3575 if (resourceItemName[index] != '.'
3576 && resourceItemName[index] != '-'
3577 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3578 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3586 for (size_t index = 0; resourceItemName[index]; ++index)
3588 if (resourceItemName[index] == ' '
3589 || resourceItemName[index] == '\t'
3590 || resourceItemName[index] == '\r'
3591 || resourceItemName[index] == '\n')
3601 OCStackResult BindResourceTypeToResource(OCResource* resource,
3602 const char *resourceTypeName)
3604 OCResourceType *pointer = NULL;
3606 OCStackResult result = OC_STACK_ERROR;
3608 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3610 if (!ValidateResourceTypeInterface(resourceTypeName))
3612 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3613 return OC_STACK_INVALID_PARAM;
3616 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3619 result = OC_STACK_NO_MEMORY;
3623 str = OICStrdup(resourceTypeName);
3626 result = OC_STACK_NO_MEMORY;
3629 pointer->resourcetypename = str;
3630 pointer->next = NULL;
3632 insertResourceType(resource, pointer);
3633 result = OC_STACK_OK;
3636 if (result != OC_STACK_OK)
3645 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3646 const char *resourceInterfaceName)
3648 OCResourceInterface *pointer = NULL;
3650 OCStackResult result = OC_STACK_ERROR;
3652 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3654 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3656 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3657 return OC_STACK_INVALID_PARAM;
3660 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3662 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3665 result = OC_STACK_NO_MEMORY;
3669 str = OICStrdup(resourceInterfaceName);
3672 result = OC_STACK_NO_MEMORY;
3675 pointer->name = str;
3677 // Bind the resourceinterface to the resource
3678 insertResourceInterface(resource, pointer);
3680 result = OC_STACK_OK;
3683 if (result != OC_STACK_OK)
3692 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3693 const char *resourceTypeName)
3696 OCStackResult result = OC_STACK_ERROR;
3697 OCResource *resource = NULL;
3699 resource = findResource((OCResource *) handle);
3702 OIC_LOG(ERROR, TAG, "Resource not found");
3703 return OC_STACK_ERROR;
3706 result = BindResourceTypeToResource(resource, resourceTypeName);
3708 #ifdef WITH_PRESENCE
3709 if(presenceResource.handle)
3711 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3712 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3719 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3720 const char *resourceInterfaceName)
3723 OCStackResult result = OC_STACK_ERROR;
3724 OCResource *resource = NULL;
3726 resource = findResource((OCResource *) handle);
3729 OIC_LOG(ERROR, TAG, "Resource not found");
3730 return OC_STACK_ERROR;
3733 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3735 #ifdef WITH_PRESENCE
3736 if (presenceResource.handle)
3738 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3739 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3746 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3748 OCResource *pointer = headResource;
3750 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3754 *numResources = *numResources + 1;
3755 pointer = pointer->next;
3760 OCResourceHandle OCGetResourceHandle(uint8_t index)
3762 OCResource *pointer = headResource;
3764 for( uint8_t i = 0; i < index && pointer; ++i)
3766 pointer = pointer->next;
3768 return (OCResourceHandle) pointer;
3771 OCStackResult OCDeleteResource(OCResourceHandle handle)
3775 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3776 return OC_STACK_INVALID_PARAM;
3779 OCResource *resource = findResource((OCResource *) handle);
3780 if (resource == NULL)
3782 OIC_LOG(ERROR, TAG, "Resource not found");
3783 return OC_STACK_NO_RESOURCE;
3786 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3788 OIC_LOG(ERROR, TAG, "Error deleting resource");
3789 return OC_STACK_ERROR;
3795 const char *OCGetResourceUri(OCResourceHandle handle)
3797 OCResource *resource = NULL;
3799 resource = findResource((OCResource *) handle);
3802 return resource->uri;
3804 return (const char *) NULL;
3807 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3809 OCResource *resource = NULL;
3811 resource = findResource((OCResource *) handle);
3814 return resource->resourceProperties;
3816 return (OCResourceProperty)-1;
3819 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3820 uint8_t *numResourceTypes)
3822 OCResource *resource = NULL;
3823 OCResourceType *pointer = NULL;
3825 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3826 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3828 *numResourceTypes = 0;
3830 resource = findResource((OCResource *) handle);
3833 pointer = resource->rsrcType;
3836 *numResourceTypes = *numResourceTypes + 1;
3837 pointer = pointer->next;
3843 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3845 OCResourceType *resourceType = NULL;
3847 resourceType = findResourceTypeAtIndex(handle, index);
3850 return resourceType->resourcetypename;
3852 return (const char *) NULL;
3855 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3856 uint8_t *numResourceInterfaces)
3858 OCResourceInterface *pointer = NULL;
3859 OCResource *resource = NULL;
3861 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3862 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3864 *numResourceInterfaces = 0;
3865 resource = findResource((OCResource *) handle);
3868 pointer = resource->rsrcInterface;
3871 *numResourceInterfaces = *numResourceInterfaces + 1;
3872 pointer = pointer->next;
3878 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3880 OCResourceInterface *resourceInterface = NULL;
3882 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3883 if (resourceInterface)
3885 return resourceInterface->name;
3887 return (const char *) NULL;
3890 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3893 OCResource *resource = NULL;
3894 OCChildResource *tempChildResource = NULL;
3897 resource = findResource((OCResource *) collectionHandle);
3903 tempChildResource = resource->rsrcChildResourcesHead;
3905 while(tempChildResource)
3909 return tempChildResource->rsrcResource;
3912 tempChildResource = tempChildResource->next;
3915 // In this case, the number of resource handles in the collection exceeds the index
3916 tempChildResource = NULL;
3920 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3921 OCEntityHandler entityHandler,
3922 void* callbackParam)
3924 OCResource *resource = NULL;
3926 // Validate parameters
3927 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3929 // Use the handle to find the resource in the resource linked list
3930 resource = findResource((OCResource *)handle);
3933 OIC_LOG(ERROR, TAG, "Resource not found");
3934 return OC_STACK_ERROR;
3938 resource->entityHandler = entityHandler;
3939 resource->entityHandlerCallbackParam = callbackParam;
3941 #ifdef WITH_PRESENCE
3942 if (presenceResource.handle)
3944 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3945 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3952 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3954 OCResource *resource = NULL;
3956 resource = findResource((OCResource *)handle);
3959 OIC_LOG(ERROR, TAG, "Resource not found");
3964 return resource->entityHandler;
3967 void incrementSequenceNumber(OCResource * resPtr)
3969 // Increment the sequence number
3970 resPtr->sequenceNum += 1;
3971 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3973 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3978 #ifdef WITH_PRESENCE
3979 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3980 OCPresenceTrigger trigger)
3982 OCResource *resPtr = NULL;
3983 OCStackResult result = OC_STACK_ERROR;
3984 OCMethod method = OC_REST_PRESENCE;
3985 uint32_t maxAge = 0;
3986 resPtr = findResource((OCResource *) presenceResource.handle);
3989 return OC_STACK_NO_RESOURCE;
3992 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3994 maxAge = presenceResource.presenceTTL;
3996 result = SendAllObserverNotification(method, resPtr, maxAge,
3997 trigger, resourceType, OC_LOW_QOS);
4003 OCStackResult SendStopNotification()
4005 OCResource *resPtr = NULL;
4006 OCStackResult result = OC_STACK_ERROR;
4007 OCMethod method = OC_REST_PRESENCE;
4008 resPtr = findResource((OCResource *) presenceResource.handle);
4011 return OC_STACK_NO_RESOURCE;
4014 // maxAge is 0. ResourceType is NULL.
4015 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4021 #endif // WITH_PRESENCE
4022 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4024 OCResource *resPtr = NULL;
4025 OCStackResult result = OC_STACK_ERROR;
4026 OCMethod method = OC_REST_NOMETHOD;
4027 uint32_t maxAge = 0;
4029 OIC_LOG(INFO, TAG, "Notifying all observers");
4030 #ifdef WITH_PRESENCE
4031 if(handle == presenceResource.handle)
4035 #endif // WITH_PRESENCE
4036 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4038 // Verify that the resource exists
4039 resPtr = findResource ((OCResource *) handle);
4042 return OC_STACK_NO_RESOURCE;
4046 //only increment in the case of regular observing (not presence)
4047 incrementSequenceNumber(resPtr);
4048 method = OC_REST_OBSERVE;
4049 maxAge = MAX_OBSERVE_AGE;
4050 #ifdef WITH_PRESENCE
4051 result = SendAllObserverNotification (method, resPtr, maxAge,
4052 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4054 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4061 OCNotifyListOfObservers (OCResourceHandle handle,
4062 OCObservationId *obsIdList,
4063 uint8_t numberOfIds,
4064 const OCRepPayload *payload,
4065 OCQualityOfService qos)
4067 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4069 OCResource *resPtr = NULL;
4070 //TODO: we should allow the server to define this
4071 uint32_t maxAge = MAX_OBSERVE_AGE;
4073 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4074 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4075 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4077 resPtr = findResource ((OCResource *) handle);
4078 if (NULL == resPtr || myStackMode == OC_CLIENT)
4080 return OC_STACK_NO_RESOURCE;
4084 incrementSequenceNumber(resPtr);
4086 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4087 payload, maxAge, qos));
4090 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4092 OCStackResult result = OC_STACK_ERROR;
4093 OCServerRequest *serverRequest = NULL;
4095 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4097 // Validate input parameters
4098 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4099 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4102 // Get pointer to request info
4103 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4106 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4107 result = serverRequest->ehResponseHandler(ehResponse);
4113 //#ifdef DIRECT_PAIRING
4114 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4116 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4117 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4119 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4123 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4126 const OCDPDev_t* OCGetDirectPairedDevices()
4128 return (const OCDPDev_t*)DPGetPairedDevices();
4131 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4132 OCDirectPairingCB resultCallback)
4134 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4135 if(NULL == peer || NULL == pinNumber)
4137 OIC_LOG(ERROR, TAG, "Invalid parameters");
4138 return OC_STACK_INVALID_PARAM;
4140 if (NULL == resultCallback)
4142 OIC_LOG(ERROR, TAG, "Invalid callback");
4143 return OC_STACK_INVALID_CALLBACK;
4146 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4147 pinNumber, (OCDirectPairingResultCB)resultCallback);
4149 //#endif // DIRECT_PAIRING
4151 //-----------------------------------------------------------------------------
4152 // Private internal function definitions
4153 //-----------------------------------------------------------------------------
4154 static OCDoHandle GenerateInvocationHandle()
4156 OCDoHandle handle = NULL;
4157 // Generate token here, it will be deleted when the transaction is deleted
4158 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4161 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4167 #ifdef WITH_PRESENCE
4168 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4169 OCResourceProperty resourceProperties, uint8_t enable)
4173 return OC_STACK_INVALID_PARAM;
4175 if (resourceProperties
4176 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4178 OIC_LOG(ERROR, TAG, "Invalid property");
4179 return OC_STACK_INVALID_PARAM;
4183 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4187 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4193 OCStackResult initResources()
4195 OCStackResult result = OC_STACK_OK;
4197 headResource = NULL;
4198 tailResource = NULL;
4199 // Init Virtual Resources
4200 #ifdef WITH_PRESENCE
4201 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4203 result = OCCreateResource(&presenceResource.handle,
4204 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4206 OC_RSRVD_PRESENCE_URI,
4210 //make resource inactive
4211 result = OCChangeResourceProperty(
4212 &(((OCResource *) presenceResource.handle)->resourceProperties),
4215 #ifndef WITH_ARDUINO
4216 if (result == OC_STACK_OK)
4218 result = SRMInitSecureResources();
4222 if(result == OC_STACK_OK)
4224 CreateResetProfile();
4225 result = OCCreateResource(&deviceResource,
4226 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4227 OC_RSRVD_INTERFACE_DEFAULT,
4228 OC_RSRVD_DEVICE_URI,
4232 if(result == OC_STACK_OK)
4234 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4235 OC_RSRVD_INTERFACE_READ);
4239 if(result == OC_STACK_OK)
4241 result = OCCreateResource(&platformResource,
4242 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4243 OC_RSRVD_INTERFACE_DEFAULT,
4244 OC_RSRVD_PLATFORM_URI,
4248 if(result == OC_STACK_OK)
4250 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4251 OC_RSRVD_INTERFACE_READ);
4258 void insertResource(OCResource *resource)
4262 headResource = resource;
4263 tailResource = resource;
4267 tailResource->next = resource;
4268 tailResource = resource;
4270 resource->next = NULL;
4273 OCResource *findResource(OCResource *resource)
4275 OCResource *pointer = headResource;
4279 if (pointer == resource)
4283 pointer = pointer->next;
4288 void deleteAllResources()
4290 OCResource *pointer = headResource;
4291 OCResource *temp = NULL;
4295 temp = pointer->next;
4296 #ifdef WITH_PRESENCE
4297 if (pointer != (OCResource *) presenceResource.handle)
4299 #endif // WITH_PRESENCE
4300 deleteResource(pointer);
4301 #ifdef WITH_PRESENCE
4303 #endif // WITH_PRESENCE
4306 memset(&platformResource, 0, sizeof(platformResource));
4307 memset(&deviceResource, 0, sizeof(deviceResource));
4309 memset(&brokerResource, 0, sizeof(brokerResource));
4312 SRMDeInitSecureResources();
4314 #ifdef WITH_PRESENCE
4315 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4316 // presence notification attributed to their deletion to be processed.
4317 deleteResource((OCResource *) presenceResource.handle);
4318 memset(&presenceResource, 0, sizeof(presenceResource));
4319 #endif // WITH_PRESENCE
4322 OCStackResult deleteResource(OCResource *resource)
4324 OCResource *prev = NULL;
4325 OCResource *temp = NULL;
4328 OIC_LOG(DEBUG,TAG,"resource is NULL");
4329 return OC_STACK_INVALID_PARAM;
4332 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4334 temp = headResource;
4337 if (temp == resource)
4339 // Invalidate all Resource Properties.
4340 resource->resourceProperties = (OCResourceProperty) 0;
4341 #ifdef WITH_PRESENCE
4342 if(resource != (OCResource *) presenceResource.handle)
4344 #endif // WITH_PRESENCE
4345 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4346 #ifdef WITH_PRESENCE
4349 if(presenceResource.handle)
4351 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4352 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4355 // Only resource in list.
4356 if (temp == headResource && temp == tailResource)
4358 headResource = NULL;
4359 tailResource = NULL;
4362 else if (temp == headResource)
4364 headResource = temp->next;
4367 else if (temp == tailResource)
4369 tailResource = prev;
4370 tailResource->next = NULL;
4374 prev->next = temp->next;
4377 deleteResourceElements(temp);
4388 return OC_STACK_ERROR;
4391 void deleteResourceElements(OCResource *resource)
4398 OICFree(resource->uri);
4399 deleteResourceType(resource->rsrcType);
4400 deleteResourceInterface(resource->rsrcInterface);
4403 void deleteResourceType(OCResourceType *resourceType)
4405 OCResourceType *pointer = resourceType;
4406 OCResourceType *next = NULL;
4410 next = pointer->next;
4411 OICFree(pointer->resourcetypename);
4417 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4419 OCResourceInterface *pointer = resourceInterface;
4420 OCResourceInterface *next = NULL;
4424 next = pointer->next;
4425 OICFree(pointer->name);
4431 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4433 OCResourceType *pointer = NULL;
4434 OCResourceType *previous = NULL;
4435 if (!resource || !resourceType)
4439 // resource type list is empty.
4440 else if (!resource->rsrcType)
4442 resource->rsrcType = resourceType;
4446 pointer = resource->rsrcType;
4450 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4452 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4453 OICFree(resourceType->resourcetypename);
4454 OICFree(resourceType);
4458 pointer = pointer->next;
4463 previous->next = resourceType;
4466 resourceType->next = NULL;
4468 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4471 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4473 OCResource *resource = NULL;
4474 OCResourceType *pointer = NULL;
4476 // Find the specified resource
4477 resource = findResource((OCResource *) handle);
4483 // Make sure a resource has a resourcetype
4484 if (!resource->rsrcType)
4489 // Iterate through the list
4490 pointer = resource->rsrcType;
4491 for(uint8_t i = 0; i< index && pointer; ++i)
4493 pointer = pointer->next;
4498 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4500 if(resourceTypeList && resourceTypeName)
4502 OCResourceType * rtPointer = resourceTypeList;
4503 while(resourceTypeName && rtPointer)
4505 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4506 if(rtPointer->resourcetypename &&
4507 strcmp(resourceTypeName, (const char *)
4508 (rtPointer->resourcetypename)) == 0)
4512 rtPointer = rtPointer->next;
4520 * Insert a new interface into interface linked list only if not already present.
4521 * If alredy present, 2nd arg is free'd.
4522 * Default interface will always be first if present.
4524 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4526 OCResourceInterface *pointer = NULL;
4527 OCResourceInterface *previous = NULL;
4529 newInterface->next = NULL;
4531 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4533 if (!*firstInterface)
4535 // If first interface is not oic.if.baseline, by default add it as first interface type.
4536 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4538 *firstInterface = newInterface;
4542 OCStackResult result = BindResourceInterfaceToResource(resource,
4543 OC_RSRVD_INTERFACE_DEFAULT);
4544 if (result != OC_STACK_OK)
4546 OICFree(newInterface->name);
4547 OICFree(newInterface);
4550 if (*firstInterface)
4552 (*firstInterface)->next = newInterface;
4556 // If once add oic.if.baseline, later too below code take care of freeing memory.
4557 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4559 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4561 OICFree(newInterface->name);
4562 OICFree(newInterface);
4565 // This code will not hit anymore, keeping
4568 newInterface->next = *firstInterface;
4569 *firstInterface = newInterface;
4574 pointer = *firstInterface;
4577 if (strcmp(newInterface->name, pointer->name) == 0)
4579 OICFree(newInterface->name);
4580 OICFree(newInterface);
4584 pointer = pointer->next;
4589 previous->next = newInterface;
4594 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4597 OCResource *resource = NULL;
4598 OCResourceInterface *pointer = NULL;
4600 // Find the specified resource
4601 resource = findResource((OCResource *) handle);
4607 // Make sure a resource has a resourceinterface
4608 if (!resource->rsrcInterface)
4613 // Iterate through the list
4614 pointer = resource->rsrcInterface;
4616 for (uint8_t i = 0; i < index && pointer; ++i)
4618 pointer = pointer->next;
4624 * This function splits the uri using the '?' delimiter.
4625 * "uriWithoutQuery" is the block of characters between the beginning
4626 * till the delimiter or '\0' which ever comes first.
4627 * "query" is whatever is to the right of the delimiter if present.
4628 * No delimiter sets the query to NULL.
4629 * If either are present, they will be malloc'ed into the params 2, 3.
4630 * The first param, *uri is left untouched.
4632 * NOTE: This function does not account for whitespace at the end of the uri NOR
4633 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4634 * part of the query.
4636 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4640 return OC_STACK_INVALID_URI;
4642 if(!query || !uriWithoutQuery)
4644 return OC_STACK_INVALID_PARAM;
4648 *uriWithoutQuery = NULL;
4650 size_t uriWithoutQueryLen = 0;
4651 size_t queryLen = 0;
4652 size_t uriLen = strlen(uri);
4654 char *pointerToDelimiter = strstr(uri, "?");
4656 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4657 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4659 if (uriWithoutQueryLen)
4661 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4662 if (!*uriWithoutQuery)
4666 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4670 *query = (char *) OICCalloc(queryLen + 1, 1);
4673 OICFree(*uriWithoutQuery);
4674 *uriWithoutQuery = NULL;
4677 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4683 return OC_STACK_NO_MEMORY;
4686 static const OicUuid_t* OCGetServerInstanceID(void)
4688 static bool generated = false;
4689 static OicUuid_t sid;
4695 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4697 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4704 const char* OCGetServerInstanceIDString(void)
4706 static bool generated = false;
4707 static char sidStr[UUID_STRING_SIZE];
4714 const OicUuid_t *sid = OCGetServerInstanceID();
4715 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4717 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4725 CAResult_t OCSelectNetwork()
4727 CAResult_t retResult = CA_STATUS_FAILED;
4728 CAResult_t caResult = CA_STATUS_OK;
4730 CATransportAdapter_t connTypes[] = {
4732 CA_ADAPTER_RFCOMM_BTEDR,
4733 CA_ADAPTER_GATT_BTLE,
4736 ,CA_ADAPTER_REMOTE_ACCESS
4743 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4745 for(int i = 0; i < numConnTypes; i++)
4747 // If CA status is not initialized, CASelectNetwork() will not be called.
4748 if (caResult != CA_STATUS_NOT_INITIALIZED)
4750 caResult = CASelectNetwork(connTypes[i]);
4751 if (caResult == CA_STATUS_OK)
4753 retResult = CA_STATUS_OK;
4758 if (retResult != CA_STATUS_OK)
4760 return caResult; // Returns error of appropriate transport that failed fatally.
4766 OCStackResult CAResultToOCResult(CAResult_t caResult)
4772 case CA_STATUS_INVALID_PARAM:
4773 return OC_STACK_INVALID_PARAM;
4774 case CA_ADAPTER_NOT_ENABLED:
4775 return OC_STACK_ADAPTER_NOT_ENABLED;
4776 case CA_SERVER_STARTED_ALREADY:
4778 case CA_SERVER_NOT_STARTED:
4779 return OC_STACK_ERROR;
4780 case CA_DESTINATION_NOT_REACHABLE:
4781 return OC_STACK_COMM_ERROR;
4782 case CA_SOCKET_OPERATION_FAILED:
4783 return OC_STACK_COMM_ERROR;
4784 case CA_SEND_FAILED:
4785 return OC_STACK_COMM_ERROR;
4786 case CA_RECEIVE_FAILED:
4787 return OC_STACK_COMM_ERROR;
4788 case CA_MEMORY_ALLOC_FAILED:
4789 return OC_STACK_NO_MEMORY;
4790 case CA_REQUEST_TIMEOUT:
4791 return OC_STACK_TIMEOUT;
4792 case CA_DESTINATION_DISCONNECTED:
4793 return OC_STACK_COMM_ERROR;
4794 case CA_STATUS_FAILED:
4795 return OC_STACK_ERROR;
4796 case CA_NOT_SUPPORTED:
4797 return OC_STACK_NOTIMPL;
4799 return OC_STACK_ERROR;
4803 bool OCResultToSuccess(OCStackResult ocResult)
4808 case OC_STACK_RESOURCE_CREATED:
4809 case OC_STACK_RESOURCE_DELETED:
4810 case OC_STACK_CONTINUE:
4811 case OC_STACK_RESOURCE_CHANGED:
4812 case OC_STACK_SLOW_RESOURCE:
4820 OCStackResult OCSetProxyURI(const char *uri)
4822 return CAResultToOCResult(CASetProxyUri(uri));
4826 #if defined(RD_CLIENT) || defined(RD_SERVER)
4827 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
4829 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4831 OCResource *resource = NULL;
4833 resource = findResource((OCResource *) handle);
4836 OIC_LOG(ERROR, TAG, "Resource not found");
4837 return OC_STACK_ERROR;
4840 resource->ins = ins;
4845 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
4849 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
4853 OCResource *pointer = headResource;
4857 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
4859 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
4862 pointer = pointer->next;
4867 OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
4869 OCResource *resource = NULL;
4871 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4872 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
4874 resource = findResource((OCResource *) handle);
4877 *ins = resource->ins;
4880 return OC_STACK_ERROR;