1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //-----------------------------------------------------------------------------
24 //-----------------------------------------------------------------------------
26 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
27 // causes header files to expose definitions
28 // corresponding to the POSIX.1-2001 base
29 // specification (excluding the XSI extension).
30 // For POSIX.1-2001 base specification,
31 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
32 #define _POSIX_C_SOURCE 200112L
33 #ifndef __STDC_FORMAT_MACROS
34 #define __STDC_FORMAT_MACROS
36 #ifndef __STDC_LIMIT_MACROS
37 #define __STDC_LIMIT_MACROS
44 #include "ocstackinternal.h"
45 #include "ocresourcehandler.h"
46 #include "occlientcb.h"
47 #include "ocobserve.h"
49 #include "oic_malloc.h"
50 #include "oic_string.h"
52 #include "ocserverrequest.h"
53 #include "secureresourcemanager.h"
54 #include "psinterface.h"
55 #include "doxmresource.h"
57 #include "cainterface.h"
58 #include "ocpayload.h"
59 #include "ocpayloadcbor.h"
60 #include "platform_features.h"
62 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
63 #include "routingutility.h"
64 #ifdef ROUTING_GATEWAY
65 #include "routingmanager.h"
70 #include "oickeepalive.h"
73 //#ifdef DIRECT_PAIRING
74 #include "directpairing.h"
77 #ifdef HAVE_ARDUINO_TIME_H
80 #ifdef HAVE_SYS_TIME_H
83 #include "coap_time.h"
87 #ifdef HAVE_ARPA_INET_H
88 #include <arpa/inet.h>
92 #define UINT32_MAX (0xFFFFFFFFUL)
95 //-----------------------------------------------------------------------------
97 //-----------------------------------------------------------------------------
100 OC_STACK_UNINITIALIZED = 0,
101 OC_STACK_INITIALIZED,
102 OC_STACK_UNINIT_IN_PROGRESS
108 OC_PRESENCE_UNINITIALIZED = 0,
109 OC_PRESENCE_INITIALIZED
113 //-----------------------------------------------------------------------------
115 //-----------------------------------------------------------------------------
116 static OCStackState stackState = OC_STACK_UNINITIALIZED;
118 OCResource *headResource = NULL;
119 static OCResource *tailResource = NULL;
120 static OCResourceHandle platformResource = {0};
121 static OCResourceHandle deviceResource = {0};
123 static OCResourceHandle brokerResource = {0};
127 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
128 static PresenceResource presenceResource = {0};
129 static uint8_t PresenceTimeOutSize = 0;
130 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
133 static OCMode myStackMode;
135 //TODO: revisit this design
136 static bool gRASetInfo = false;
138 OCDeviceEntityHandler defaultDeviceHandler;
139 void* defaultDeviceHandlerCallbackParameter = NULL;
140 static const char COAP_TCP[] = "coap+tcp:";
141 static const char 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 uint32_t GetTicks(uint32_t afterMilliSeconds)
427 // Guard against overflow of uint32_t
428 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
429 COAP_TICKS_PER_SECOND)
431 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
439 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
441 VERIFY_NON_NULL_NR(in, FATAL);
442 VERIFY_NON_NULL_NR(out, FATAL);
444 out->adapter = (OCTransportAdapter)in->adapter;
445 out->flags = CAToOCTransportFlags(in->flags);
446 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
447 out->port = in->port;
448 out->ifindex = in->ifindex;
449 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
450 /* This assert is to prevent accidental mismatch between address size macros defined in
451 * RI and CA and cause crash here. */
452 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
453 "Address size mismatch between RI and CA");
454 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
458 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
460 VERIFY_NON_NULL_NR(in, FATAL);
461 VERIFY_NON_NULL_NR(out, FATAL);
463 out->adapter = (CATransportAdapter_t)in->adapter;
464 out->flags = OCToCATransportFlags(in->flags);
465 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
466 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
467 /* This assert is to prevent accidental mismatch between address size macros defined in
468 * RI and CA and cause crash here. */
469 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
470 "Address size mismatch between RI and CA");
471 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
473 out->port = in->port;
474 out->ifindex = in->ifindex;
477 void FixUpClientResponse(OCClientResponse *cr)
479 VERIFY_NON_NULL_NR(cr, FATAL);
481 cr->addr = &cr->devAddr;
482 cr->connType = (OCConnectivityType)
483 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
486 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
488 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
489 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
491 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
492 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
493 if (OC_STACK_OK != rmResult)
495 OIC_LOG(ERROR, TAG, "Add destination option failed");
500 // OC stack prefer CBOR encoded payloads.
501 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
502 CAResult_t result = CASendRequest(object, requestInfo);
503 if(CA_STATUS_OK != result)
505 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
506 return CAResultToOCResult(result);
510 //-----------------------------------------------------------------------------
511 // Internal API function
512 //-----------------------------------------------------------------------------
514 // This internal function is called to update the stack with the status of
515 // observers and communication failures
516 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
518 OCStackResult result = OC_STACK_ERROR;
519 ResourceObserver * observer = NULL;
520 OCEntityHandlerRequest ehRequest = {0};
524 case OC_OBSERVER_NOT_INTERESTED:
525 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
526 observer = GetObserverUsingToken (token, tokenLength);
529 result = FormOCEntityHandlerRequest(&ehRequest,
530 (OCRequestHandle)NULL,
533 (OCResourceHandle)NULL,
534 NULL, PAYLOAD_TYPE_REPRESENTATION,
536 OC_OBSERVE_DEREGISTER,
539 if(result != OC_STACK_OK)
543 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
544 observer->resource->entityHandlerCallbackParam);
547 result = DeleteObserverUsingToken (token, tokenLength);
548 if(result == OC_STACK_OK)
550 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
554 result = OC_STACK_OK;
555 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
559 case OC_OBSERVER_STILL_INTERESTED:
560 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
561 observer = GetObserverUsingToken (token, tokenLength);
564 observer->forceHighQos = 0;
565 observer->failedCommCount = 0;
566 result = OC_STACK_OK;
570 result = OC_STACK_OBSERVER_NOT_FOUND;
574 case OC_OBSERVER_FAILED_COMM:
575 OIC_LOG(DEBUG, TAG, "observer is unreachable");
576 observer = GetObserverUsingToken (token, tokenLength);
579 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
581 result = FormOCEntityHandlerRequest(&ehRequest,
582 (OCRequestHandle)NULL,
585 (OCResourceHandle)NULL,
586 NULL, PAYLOAD_TYPE_REPRESENTATION,
588 OC_OBSERVE_DEREGISTER,
591 if(result != OC_STACK_OK)
593 return OC_STACK_ERROR;
595 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
596 observer->resource->entityHandlerCallbackParam);
598 result = DeleteObserverUsingToken (token, tokenLength);
599 if(result == OC_STACK_OK)
601 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
605 result = OC_STACK_OK;
606 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
611 observer->failedCommCount++;
612 result = OC_STACK_CONTINUE;
614 observer->forceHighQos = 1;
615 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
619 OIC_LOG(ERROR, TAG, "Unknown status");
620 result = OC_STACK_ERROR;
626 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
628 OCStackResult ret = OC_STACK_ERROR;
632 case CA_ADAPTER_NOT_ENABLED:
633 case CA_SERVER_NOT_STARTED:
634 ret = OC_STACK_ADAPTER_NOT_ENABLED;
636 case CA_MEMORY_ALLOC_FAILED:
637 ret = OC_STACK_NO_MEMORY;
639 case CA_STATUS_INVALID_PARAM:
640 ret = OC_STACK_INVALID_PARAM;
648 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
650 OCStackResult ret = OC_STACK_ERROR;
654 ret = OC_STACK_RESOURCE_CREATED;
657 ret = OC_STACK_RESOURCE_DELETED;
660 ret = OC_STACK_RESOURCE_CHANGED;
667 ret = OC_STACK_INVALID_QUERY;
669 case CA_UNAUTHORIZED_REQ:
670 ret = OC_STACK_UNAUTHORIZED_REQ;
673 ret = OC_STACK_INVALID_OPTION;
676 ret = OC_STACK_NO_RESOURCE;
678 case CA_RETRANSMIT_TIMEOUT:
679 ret = OC_STACK_COMM_ERROR;
681 case CA_REQUEST_ENTITY_TOO_LARGE:
682 ret = OC_STACK_TOO_LARGE_REQ;
690 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
692 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
701 // This Response Code is like HTTP 204 "No Content" but only used in
702 // response to POST and PUT requests.
706 // This Response Code is like HTTP 200 "OK" but only used in response to
711 // This should not happen but,
712 // give it a value just in case but output an error
714 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
718 case OC_STACK_RESOURCE_CREATED:
721 case OC_STACK_RESOURCE_DELETED:
724 case OC_STACK_RESOURCE_CHANGED:
727 case OC_STACK_INVALID_QUERY:
730 case OC_STACK_INVALID_OPTION:
733 case OC_STACK_NO_RESOURCE:
736 case OC_STACK_COMM_ERROR:
737 ret = CA_RETRANSMIT_TIMEOUT;
739 case OC_STACK_UNAUTHORIZED_REQ:
740 ret = CA_UNAUTHORIZED_REQ;
748 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
750 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
752 // supply default behavior.
753 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
755 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
757 if ((caFlags & OC_MASK_SCOPE) == 0)
759 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
764 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
766 return (OCTransportFlags)caFlags;
769 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
771 uint32_t lowerBound = 0;
772 uint32_t higherBound = 0;
774 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
776 return OC_STACK_INVALID_PARAM;
779 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
781 cbNode->presence->TTL = maxAgeSeconds;
783 for (int index = 0; index < PresenceTimeOutSize; index++)
785 // Guard against overflow
786 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
789 lowerBound = GetTicks((PresenceTimeOut[index] *
790 cbNode->presence->TTL *
791 MILLISECONDS_PER_SECOND)/100);
795 lowerBound = GetTicks(UINT32_MAX);
798 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
801 higherBound = GetTicks((PresenceTimeOut[index + 1] *
802 cbNode->presence->TTL *
803 MILLISECONDS_PER_SECOND)/100);
807 higherBound = GetTicks(UINT32_MAX);
810 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
812 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
813 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
814 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
817 cbNode->presence->TTLlevel = 0;
819 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
823 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
825 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
827 return OC_RSRVD_TRIGGER_CREATE;
829 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
831 return OC_RSRVD_TRIGGER_CHANGE;
835 return OC_RSRVD_TRIGGER_DELETE;
839 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
843 return OC_PRESENCE_TRIGGER_CREATE;
845 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
847 return OC_PRESENCE_TRIGGER_CREATE;
849 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
851 return OC_PRESENCE_TRIGGER_CHANGE;
855 return OC_PRESENCE_TRIGGER_DELETE;
860 * Encode an address string to match RFC 6874.
862 * @param outputAddress a char array to be written with the encoded string.
864 * @param outputSize size of outputAddress buffer.
866 * @param inputAddress a char array of size <= CA_MAX_URI_LENGTH
867 * containing a valid IPv6 address string.
869 * @return OC_STACK_OK if encoding succeeded.
870 * Else an error occured.
872 OCStackResult encodeAddressForRFC6874(char *outputAddress,
874 const char *inputAddress)
876 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
877 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
879 size_t inputLength = strnlen(inputAddress, outputSize);
881 // inputSize includes the null terminator
882 size_t inputSize = inputLength + 1;
884 if (inputSize > outputSize)
886 OIC_LOG_V(ERROR, TAG,
887 "encodeAddressForRFC6874 failed: "
888 "outputSize (%zu) < inputSize (%zu)",
889 outputSize, inputSize);
891 return OC_STACK_ERROR;
894 char* percentChar = strchr(inputAddress, '%');
896 // If there is no '%' character, then no change is required to the string.
897 if (NULL == percentChar)
899 OICStrcpy(outputAddress, outputSize, inputAddress);
903 const char* addressPart = &inputAddress[0];
904 const char* scopeIdPart = percentChar + 1;
906 // Sanity check to make sure this string doesn't have more '%' characters
907 if (NULL != strchr(scopeIdPart, '%'))
909 return OC_STACK_ERROR;
912 // If no string follows the first '%', then the input was invalid.
913 if (scopeIdPart[0] == '\0')
915 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
916 return OC_STACK_ERROR;
919 // Check to see if the string is already encoded
920 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
922 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
923 return OC_STACK_ERROR;
926 // Fail if we don't have room for encoded string's two additional chars
927 if (outputSize < (inputSize + 2))
929 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: encoded output will not fit!");
930 return OC_STACK_ERROR;
933 // Restore the null terminator with an escaped '%' character, per RFC 6874
934 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
935 strcat(outputAddress, "%25");
936 strcat(outputAddress, scopeIdPart);
942 * The cononical presence allows constructed URIs to be string compared.
944 * requestUri must be a char array of size CA_MAX_URI_LENGTH
946 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
947 char *presenceUri, bool isMulticast)
949 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
950 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
951 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
955 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
956 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
959 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
960 if (ep->adapter == CA_ADAPTER_IP)
962 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
964 if ('\0' == ep->addr[0]) // multicast
966 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
970 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
972 OCStackResult result = encodeAddressForRFC6874(addressEncoded,
973 sizeof(addressEncoded),
976 if (OC_STACK_OK != result)
981 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
982 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
987 if ('\0' == ep->addr[0]) // multicast
989 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
990 ep->port = OC_MULTICAST_PORT;
992 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
993 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
997 // might work for other adapters (untested, but better than nothing)
998 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
999 OC_RSRVD_PRESENCE_URI);
1003 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1004 const CAResponseInfo_t *responseInfo)
1006 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1007 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1009 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1010 ClientCB * cbNode = NULL;
1011 char *resourceTypeName = NULL;
1012 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1013 OCStackResult result = OC_STACK_ERROR;
1014 uint32_t maxAge = 0;
1016 char presenceUri[CA_MAX_URI_LENGTH];
1018 int presenceSubscribe = 0;
1019 int multicastPresenceSubscribe = 0;
1021 if (responseInfo->result != CA_CONTENT)
1023 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1024 return OC_STACK_ERROR;
1027 response.payload = NULL;
1028 response.result = OC_STACK_OK;
1030 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1031 FixUpClientResponse(&response);
1033 if (responseInfo->info.payload)
1035 result = OCParsePayload(&response.payload,
1036 PAYLOAD_TYPE_PRESENCE,
1037 responseInfo->info.payload,
1038 responseInfo->info.payloadSize);
1040 if(result != OC_STACK_OK)
1042 OIC_LOG(ERROR, TAG, "Presence parse failed");
1045 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1047 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1048 result = OC_STACK_ERROR;
1051 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1052 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1053 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1056 // check for unicast presence
1057 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri,
1058 responseInfo->isMulticast);
1059 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1061 return OC_STACK_INVALID_URI;
1063 OIC_LOG(ERROR, TAG, "check for unicast presence");
1064 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1067 presenceSubscribe = 1;
1071 // check for multicast presence
1072 OIC_LOG(ERROR, TAG, "check for multicast presence");
1073 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1076 multicastPresenceSubscribe = 1;
1080 if (!presenceSubscribe && !multicastPresenceSubscribe)
1082 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1086 if (presenceSubscribe)
1088 if(cbNode->sequenceNumber == response.sequenceNumber)
1090 OIC_LOG(INFO, TAG, "No presence change");
1091 ResetPresenceTTL(cbNode, maxAge);
1092 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1098 OIC_LOG(INFO, TAG, "Stopping presence");
1099 response.result = OC_STACK_PRESENCE_STOPPED;
1100 if(cbNode->presence)
1102 OICFree(cbNode->presence->timeOut);
1103 OICFree(cbNode->presence);
1104 cbNode->presence = NULL;
1109 if(!cbNode->presence)
1111 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1113 if(!(cbNode->presence))
1115 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1116 result = OC_STACK_NO_MEMORY;
1120 VERIFY_NON_NULL_V(cbNode->presence);
1121 cbNode->presence->timeOut = NULL;
1122 cbNode->presence->timeOut = (uint32_t *)
1123 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1124 if(!(cbNode->presence->timeOut)){
1126 "Could not allocate memory for cbNode->presence->timeOut");
1127 OICFree(cbNode->presence);
1128 result = OC_STACK_NO_MEMORY;
1133 ResetPresenceTTL(cbNode, maxAge);
1135 cbNode->sequenceNumber = response.sequenceNumber;
1137 // Ensure that a filter is actually applied.
1138 if( resourceTypeName && cbNode->filterResourceType)
1140 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1149 // This is the multicast case
1150 OCMulticastNode* mcNode = NULL;
1151 mcNode = GetMCPresenceNode(presenceUri);
1155 if(mcNode->nonce == response.sequenceNumber)
1157 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1160 mcNode->nonce = response.sequenceNumber;
1164 OIC_LOG(INFO, TAG, "Stopping presence");
1165 response.result = OC_STACK_PRESENCE_STOPPED;
1170 char* uri = OICStrdup(presenceUri);
1174 "No Memory for URI to store in the presence node");
1175 result = OC_STACK_NO_MEMORY;
1179 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1180 if(result == OC_STACK_NO_MEMORY)
1183 "No Memory for Multicast Presence Node");
1187 // presence node now owns uri
1192 // Ensure that a filter is actually applied.
1193 if(resourceTypeName && cbNode->filterResourceType)
1195 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1196 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1202 OIC_LOG(INFO, TAG, "Callback for presence");
1204 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1206 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1208 FindAndDeleteClientCB(cbNode);
1212 OCPayloadDestroy(response.payload);
1216 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1218 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1220 if(responseInfo->info.resourceUri &&
1221 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1223 HandlePresenceResponse(endPoint, responseInfo);
1227 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1228 responseInfo->info.tokenLength, NULL, NULL);
1230 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1231 responseInfo->info.tokenLength);
1235 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1236 if(responseInfo->result == CA_EMPTY)
1238 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1239 // We do not have a case for the client to receive a RESET
1240 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1242 //This is the case of receiving an ACK on a request to a slow resource!
1243 OIC_LOG(INFO, TAG, "This is a pure ACK");
1244 //TODO: should we inform the client
1245 // app that at least the request was received at the server?
1248 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1250 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1251 OIC_LOG(INFO, TAG, "Calling into application address space");
1253 OCClientResponse response =
1254 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1255 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1256 FixUpClientResponse(&response);
1257 response.resourceUri = responseInfo->info.resourceUri;
1258 memcpy(response.identity.id, responseInfo->info.identity.id,
1259 sizeof (response.identity.id));
1260 response.identity.id_length = responseInfo->info.identity.id_length;
1262 response.result = CAResponseToOCStackResult(responseInfo->result);
1263 cbNode->callBack(cbNode->context,
1264 cbNode->handle, &response);
1265 FindAndDeleteClientCB(cbNode);
1269 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1270 OIC_LOG(INFO, TAG, "Calling into application address space");
1272 OCClientResponse response =
1273 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1274 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1275 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1276 FixUpClientResponse(&response);
1277 response.resourceUri = responseInfo->info.resourceUri;
1278 memcpy(response.identity.id, responseInfo->info.identity.id,
1279 sizeof (response.identity.id));
1280 response.identity.id_length = responseInfo->info.identity.id_length;
1282 response.result = CAResponseToOCStackResult(responseInfo->result);
1284 if(responseInfo->info.payload &&
1285 responseInfo->info.payloadSize)
1287 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1288 // check the security resource
1289 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1291 type = PAYLOAD_TYPE_SECURITY;
1293 else if (cbNode->method == OC_REST_DISCOVER)
1295 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1296 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1298 type = PAYLOAD_TYPE_DISCOVERY;
1301 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1303 type = PAYLOAD_TYPE_DISCOVERY;
1306 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1308 type = PAYLOAD_TYPE_DEVICE;
1310 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1312 type = PAYLOAD_TYPE_PLATFORM;
1314 #ifdef ROUTING_GATEWAY
1315 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1317 type = PAYLOAD_TYPE_REPRESENTATION;
1320 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1322 type = PAYLOAD_TYPE_RD;
1325 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1327 type = PAYLOAD_TYPE_REPRESENTATION;
1332 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1333 cbNode->method, cbNode->requestUri);
1337 else if (cbNode->method == OC_REST_GET ||
1338 cbNode->method == OC_REST_PUT ||
1339 cbNode->method == OC_REST_POST ||
1340 cbNode->method == OC_REST_OBSERVE ||
1341 cbNode->method == OC_REST_OBSERVE_ALL ||
1342 cbNode->method == OC_REST_DELETE)
1344 char targetUri[MAX_URI_LENGTH];
1345 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1346 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1347 if (strcmp(targetUri, cbNode->requestUri) == 0)
1349 type = PAYLOAD_TYPE_RD;
1351 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1353 type = PAYLOAD_TYPE_PLATFORM;
1355 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1357 type = PAYLOAD_TYPE_DEVICE;
1359 if (type == PAYLOAD_TYPE_INVALID)
1361 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1362 cbNode->method, cbNode->requestUri);
1363 type = PAYLOAD_TYPE_REPRESENTATION;
1368 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1369 cbNode->method, cbNode->requestUri);
1373 if(OC_STACK_OK != OCParsePayload(&response.payload,
1375 responseInfo->info.payload,
1376 responseInfo->info.payloadSize))
1378 OIC_LOG(ERROR, TAG, "Error converting payload");
1379 OCPayloadDestroy(response.payload);
1384 response.numRcvdVendorSpecificHeaderOptions = 0;
1385 if(responseInfo->info.numOptions > 0)
1388 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1389 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1392 uint32_t observationOption;
1393 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1394 for (observationOption=0, i=0;
1395 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1399 (observationOption << 8) | optionData[i];
1401 response.sequenceNumber = observationOption;
1402 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1407 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1410 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1412 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1413 OCPayloadDestroy(response.payload);
1417 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1419 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1420 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1424 if (cbNode->method == OC_REST_OBSERVE &&
1425 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1426 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1427 response.sequenceNumber <= cbNode->sequenceNumber)
1429 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1430 response.sequenceNumber);
1434 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1437 cbNode->sequenceNumber = response.sequenceNumber;
1439 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1441 FindAndDeleteClientCB(cbNode);
1445 // To keep discovery callbacks active.
1446 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1447 MILLISECONDS_PER_SECOND);
1451 //Need to send ACK when the response is CON
1452 if(responseInfo->info.type == CA_MSG_CONFIRM)
1454 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1455 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1458 OCPayloadDestroy(response.payload);
1465 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1466 if(responseInfo->result == CA_EMPTY)
1468 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1469 if(responseInfo->info.type == CA_MSG_RESET)
1471 OIC_LOG(INFO, TAG, "This is a RESET");
1472 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1473 OC_OBSERVER_NOT_INTERESTED);
1475 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1477 OIC_LOG(INFO, TAG, "This is a pure ACK");
1478 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1479 OC_OBSERVER_STILL_INTERESTED);
1482 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1484 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1485 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1486 OC_OBSERVER_FAILED_COMM);
1491 if(!cbNode && !observer)
1493 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1494 || myStackMode == OC_GATEWAY)
1496 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1497 if(responseInfo->result == CA_EMPTY)
1499 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1503 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1504 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1505 CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1509 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1510 || myStackMode == OC_GATEWAY)
1512 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1513 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1515 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1516 responseInfo->info.messageId);
1518 if (responseInfo->info.type == CA_MSG_RESET)
1520 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1521 responseInfo->info.messageId);
1529 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1531 VERIFY_NON_NULL_NR(endPoint, FATAL);
1532 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1534 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1536 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1537 #ifdef ROUTING_GATEWAY
1538 bool needRIHandling = false;
1540 * Routing manager is going to update either of endpoint or response or both.
1541 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1542 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1545 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1547 if(ret != OC_STACK_OK || !needRIHandling)
1549 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1555 * Put source in sender endpoint so that the next packet from application can be routed to
1556 * proper destination and remove "RM" coap header option before passing request / response to
1557 * RI as this option will make no sense to either RI or application.
1559 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1560 (uint8_t *) &(responseInfo->info.numOptions),
1561 (CAEndpoint_t *) endPoint);
1564 OCHandleResponse(endPoint, responseInfo);
1566 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1570 * This function handles error response from CA
1571 * code shall be added to handle the errors
1573 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1575 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1577 if (NULL == endPoint)
1579 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1583 if (NULL == errorInfo)
1585 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1589 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1590 errorInfo->info.tokenLength, NULL, NULL);
1593 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1594 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1595 FixUpClientResponse(&response);
1596 response.resourceUri = errorInfo->info.resourceUri;
1597 memcpy(response.identity.id, errorInfo->info.identity.id,
1598 sizeof (response.identity.id));
1599 response.identity.id_length = errorInfo->info.identity.id_length;
1600 response.result = CAResultToOCStackResult(errorInfo->result);
1602 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1605 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1609 * This function sends out Direct Stack Responses. These are responses that are not coming
1610 * from the application entity handler. These responses have no payload and are usually ACKs,
1611 * RESETs or some error conditions that were caught by the stack.
1613 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1614 const CAResponseResult_t responseResult, const CAMessageType_t type,
1615 const uint8_t numOptions, const CAHeaderOption_t *options,
1616 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1617 CADataType_t dataType)
1619 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1620 CAResponseInfo_t respInfo = {
1621 .result = responseResult
1623 respInfo.info.messageId = coapID;
1624 respInfo.info.numOptions = numOptions;
1626 if (respInfo.info.numOptions)
1628 respInfo.info.options =
1629 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1630 memcpy (respInfo.info.options, options,
1631 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1635 respInfo.info.payload = NULL;
1636 respInfo.info.token = token;
1637 respInfo.info.tokenLength = tokenLength;
1638 respInfo.info.type = type;
1639 respInfo.info.resourceUri = OICStrdup (resourceUri);
1640 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1641 respInfo.info.dataType = dataType;
1643 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1644 // Add the destination to route option from the endpoint->routeData.
1645 bool doPost = false;
1646 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1647 if(OC_STACK_OK != result)
1649 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1654 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1655 CARequestInfo_t reqInfo = {.method = CA_POST };
1656 /* The following initialization is not done in a single initializer block as in
1657 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1658 * does not have designated initalizers. This is a work-around for now.
1660 reqInfo.info.type = CA_MSG_NONCONFIRM;
1661 reqInfo.info.messageId = coapID;
1662 reqInfo.info.tokenLength = tokenLength;
1663 reqInfo.info.token = token;
1664 reqInfo.info.numOptions = respInfo.info.numOptions;
1665 reqInfo.info.payload = NULL;
1666 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1667 if (reqInfo.info.numOptions)
1669 reqInfo.info.options =
1670 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1671 if (NULL == reqInfo.info.options)
1673 OIC_LOG(ERROR, TAG, "Calloc failed");
1674 return OC_STACK_NO_MEMORY;
1676 memcpy (reqInfo.info.options, respInfo.info.options,
1677 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1680 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1681 OICFree (reqInfo.info.resourceUri);
1682 OICFree (reqInfo.info.options);
1683 OICFree (respInfo.info.resourceUri);
1684 OICFree (respInfo.info.options);
1685 if (CA_STATUS_OK != caResult)
1687 OIC_LOG(ERROR, TAG, "CASendRequest error");
1688 return CAResultToOCResult(caResult);
1694 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1696 // resourceUri in the info field is cloned in the CA layer and
1697 // thus ownership is still here.
1698 OICFree (respInfo.info.resourceUri);
1699 OICFree (respInfo.info.options);
1700 if(CA_STATUS_OK != caResult)
1702 OIC_LOG(ERROR, TAG, "CASendResponse error");
1703 return CAResultToOCResult(caResult);
1706 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1710 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1712 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1713 OCStackResult result = OC_STACK_ERROR;
1714 if(!protocolRequest)
1716 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1717 return OC_STACK_INVALID_PARAM;
1720 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1721 protocolRequest->tokenLength);
1724 OIC_LOG(INFO, TAG, "This is a new Server Request");
1725 result = AddServerRequest(&request, protocolRequest->coapID,
1726 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1727 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1728 protocolRequest->observationOption, protocolRequest->qos,
1729 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1730 protocolRequest->payload, protocolRequest->requestToken,
1731 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1732 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1733 &protocolRequest->devAddr);
1734 if (OC_STACK_OK != result)
1736 OIC_LOG(ERROR, TAG, "Error adding server request");
1742 OIC_LOG(ERROR, TAG, "Out of Memory");
1743 return OC_STACK_NO_MEMORY;
1746 if(!protocolRequest->reqMorePacket)
1748 request->requestComplete = 1;
1753 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1756 if(request->requestComplete)
1758 OIC_LOG(INFO, TAG, "This Server Request is complete");
1759 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1760 OCResource *resource = NULL;
1761 result = DetermineResourceHandling (request, &resHandling, &resource);
1762 if (result == OC_STACK_OK)
1764 result = ProcessRequest(resHandling, resource, request);
1769 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1770 result = OC_STACK_CONTINUE;
1775 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1777 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1780 if (requestInfo->info.resourceUri &&
1781 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1783 HandleKeepAliveRequest(endPoint, requestInfo);
1788 OCStackResult requestResult = OC_STACK_ERROR;
1790 if(myStackMode == OC_CLIENT)
1792 //TODO: should the client be responding to requests?
1796 OCServerProtocolRequest serverRequest = {0};
1798 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1800 char * uriWithoutQuery = NULL;
1801 char * query = NULL;
1803 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1805 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1807 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1810 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1811 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1813 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1815 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1816 OICFree(uriWithoutQuery);
1820 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1821 OICFree(uriWithoutQuery);
1828 if(strlen(query) < MAX_QUERY_LENGTH)
1830 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1835 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1841 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1843 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1844 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1845 if (!serverRequest.payload)
1847 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1850 memcpy (serverRequest.payload, requestInfo->info.payload,
1851 requestInfo->info.payloadSize);
1855 serverRequest.reqTotalSize = 0;
1858 switch (requestInfo->method)
1861 serverRequest.method = OC_REST_GET;
1864 serverRequest.method = OC_REST_PUT;
1867 serverRequest.method = OC_REST_POST;
1870 serverRequest.method = OC_REST_DELETE;
1873 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1874 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1875 requestInfo->info.type, requestInfo->info.numOptions,
1876 requestInfo->info.options, requestInfo->info.token,
1877 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1879 OICFree(serverRequest.payload);
1883 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1884 requestInfo->info.tokenLength);
1886 serverRequest.tokenLength = requestInfo->info.tokenLength;
1887 if (serverRequest.tokenLength) {
1889 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1891 if (!serverRequest.requestToken)
1893 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1894 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1895 requestInfo->info.type, requestInfo->info.numOptions,
1896 requestInfo->info.options, requestInfo->info.token,
1897 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1899 OICFree(serverRequest.payload);
1902 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1905 switch (requestInfo->info.acceptFormat)
1907 case CA_FORMAT_APPLICATION_CBOR:
1908 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1910 case CA_FORMAT_UNDEFINED:
1911 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1914 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1917 if (requestInfo->info.type == CA_MSG_CONFIRM)
1919 serverRequest.qos = OC_HIGH_QOS;
1923 serverRequest.qos = OC_LOW_QOS;
1925 // CA does not need the following field
1926 // Are we sure CA does not need them? how is it responding to multicast
1927 serverRequest.delayedResNeeded = 0;
1929 serverRequest.coapID = requestInfo->info.messageId;
1931 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1933 // copy vendor specific header options
1934 uint8_t tempNum = (requestInfo->info.numOptions);
1936 // Assume no observation requested and it is a pure GET.
1937 // If obs registration/de-registration requested it'll be fetched from the
1938 // options in GetObserveHeaderOption()
1939 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1941 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1942 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1945 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1946 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1947 requestInfo->info.type, requestInfo->info.numOptions,
1948 requestInfo->info.options, requestInfo->info.token,
1949 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1951 OICFree(serverRequest.payload);
1952 OICFree(serverRequest.requestToken);
1955 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1956 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1958 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1959 sizeof(CAHeaderOption_t)*tempNum);
1962 requestResult = HandleStackRequests (&serverRequest);
1964 // Send ACK to client as precursor to slow response
1965 if (requestResult == OC_STACK_SLOW_RESOURCE)
1967 if (requestInfo->info.type == CA_MSG_CONFIRM)
1969 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1970 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
1974 else if(!OCResultToSuccess(requestResult))
1976 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1978 CAResponseResult_t stackResponse =
1979 OCToCAStackResult(requestResult, serverRequest.method);
1981 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1982 requestInfo->info.type, requestInfo->info.numOptions,
1983 requestInfo->info.options, requestInfo->info.token,
1984 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1987 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1988 // The token is copied in there, and is thus still owned by this function.
1989 OICFree(serverRequest.payload);
1990 OICFree(serverRequest.requestToken);
1991 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1994 //This function will be called back by CA layer when a request is received
1995 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1997 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2000 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2006 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2010 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2011 #ifdef ROUTING_GATEWAY
2012 bool needRIHandling = false;
2013 bool isEmptyMsg = false;
2015 * Routing manager is going to update either of endpoint or request or both.
2016 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2017 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2018 * destination. It can also remove "RM" coap header option before passing request / response to
2019 * RI as this option will make no sense to either RI or application.
2021 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2022 &needRIHandling, &isEmptyMsg);
2023 if(OC_STACK_OK != ret || !needRIHandling)
2025 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2031 * Put source in sender endpoint so that the next packet from application can be routed to
2032 * proper destination and remove RM header option.
2034 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2035 (uint8_t *) &(requestInfo->info.numOptions),
2036 (CAEndpoint_t *) endPoint);
2038 #ifdef ROUTING_GATEWAY
2042 * In Gateways, the MSGType in route option is used to check if the actual
2043 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2044 * EMPTY response is sent in the form of POST request which need to be changed
2045 * to a EMPTY response by RM. This translation is done in this part of the code.
2047 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2048 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2049 .info.messageId = requestInfo->info.messageId,
2050 .info.type = CA_MSG_ACKNOWLEDGE};
2051 OCHandleResponse(endPoint, &respInfo);
2057 // Normal handling of the packet
2058 OCHandleRequests(endPoint, requestInfo);
2060 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2063 bool validatePlatformInfo(OCPlatformInfo info)
2066 if (!info.platformID)
2068 OIC_LOG(ERROR, TAG, "No platform ID found.");
2072 if (info.manufacturerName)
2074 size_t lenManufacturerName = strlen(info.manufacturerName);
2076 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2078 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2084 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2088 if (info.manufacturerUrl)
2090 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2092 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2099 //-----------------------------------------------------------------------------
2101 //-----------------------------------------------------------------------------
2103 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2106 !raInfo->username ||
2107 !raInfo->hostname ||
2108 !raInfo->xmpp_domain)
2111 return OC_STACK_INVALID_PARAM;
2113 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2114 gRASetInfo = (result == OC_STACK_OK)? true : false;
2120 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2124 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2127 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2129 if(stackState == OC_STACK_INITIALIZED)
2131 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2132 OCStop() between them are ignored.");
2136 #ifndef ROUTING_GATEWAY
2137 if (OC_GATEWAY == mode)
2139 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2140 return OC_STACK_INVALID_PARAM;
2147 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2148 return OC_STACK_ERROR;
2152 OCStackResult result = OC_STACK_ERROR;
2153 OIC_LOG(INFO, TAG, "Entering OCInit");
2156 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2157 || (mode == OC_GATEWAY)))
2159 OIC_LOG(ERROR, TAG, "Invalid mode");
2160 return OC_STACK_ERROR;
2164 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2166 caglobals.client = true;
2168 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2170 caglobals.server = true;
2173 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2174 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2176 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2178 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2179 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2181 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2184 defaultDeviceHandler = NULL;
2185 defaultDeviceHandlerCallbackParameter = NULL;
2187 result = CAResultToOCResult(CAInitialize());
2188 VERIFY_SUCCESS(result, OC_STACK_OK);
2190 result = CAResultToOCResult(OCSelectNetwork());
2191 VERIFY_SUCCESS(result, OC_STACK_OK);
2193 switch (myStackMode)
2196 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2197 result = CAResultToOCResult(CAStartDiscoveryServer());
2198 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2201 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2202 result = CAResultToOCResult(CAStartListeningServer());
2203 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2205 case OC_CLIENT_SERVER:
2207 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2208 result = CAResultToOCResult(CAStartListeningServer());
2209 if(result == OC_STACK_OK)
2211 result = CAResultToOCResult(CAStartDiscoveryServer());
2215 VERIFY_SUCCESS(result, OC_STACK_OK);
2218 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2221 #ifdef WITH_PRESENCE
2222 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2223 #endif // WITH_PRESENCE
2225 //Update Stack state to initialized
2226 stackState = OC_STACK_INITIALIZED;
2228 // Initialize resource
2229 if(myStackMode != OC_CLIENT)
2231 result = initResources();
2234 // Initialize the SRM Policy Engine
2235 if(result == OC_STACK_OK)
2237 result = SRMInitPolicyEngine();
2238 // TODO after BeachHead delivery: consolidate into single SRMInit()
2240 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2241 RMSetStackMode(mode);
2242 #ifdef ROUTING_GATEWAY
2243 if (OC_GATEWAY == myStackMode)
2245 result = RMInitialize();
2251 if (result == OC_STACK_OK)
2253 result = InitializeKeepAlive(myStackMode);
2258 if(result != OC_STACK_OK)
2260 OIC_LOG(ERROR, TAG, "Stack initialization error");
2261 deleteAllResources();
2263 stackState = OC_STACK_UNINITIALIZED;
2268 OCStackResult OCStop()
2270 OIC_LOG(INFO, TAG, "Entering OCStop");
2272 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2274 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2277 else if (stackState != OC_STACK_INITIALIZED)
2279 OIC_LOG(ERROR, TAG, "Stack not initialized");
2280 return OC_STACK_ERROR;
2283 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2285 #ifdef WITH_PRESENCE
2286 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2287 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2288 presenceResource.presenceTTL = 0;
2289 #endif // WITH_PRESENCE
2291 #ifdef ROUTING_GATEWAY
2292 if (OC_GATEWAY == myStackMode)
2299 TerminateKeepAlive(myStackMode);
2302 // Free memory dynamically allocated for resources
2303 deleteAllResources();
2305 DeletePlatformInfo();
2307 // Remove all observers
2308 DeleteObserverList();
2309 // Remove all the client callbacks
2310 DeleteClientCBList();
2312 // De-init the SRM Policy Engine
2313 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2314 SRMDeInitPolicyEngine();
2317 stackState = OC_STACK_UNINITIALIZED;
2321 OCStackResult OCStartMulticastServer()
2323 if(stackState != OC_STACK_INITIALIZED)
2325 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2326 return OC_STACK_ERROR;
2328 CAResult_t ret = CAStartListeningServer();
2329 if (CA_STATUS_OK != ret)
2331 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2332 return OC_STACK_ERROR;
2337 OCStackResult OCStopMulticastServer()
2339 CAResult_t ret = CAStopListeningServer();
2340 if (CA_STATUS_OK != ret)
2342 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2343 return OC_STACK_ERROR;
2348 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2353 return CA_MSG_CONFIRM;
2358 return CA_MSG_NONCONFIRM;
2363 * A request uri consists of the following components in order:
2366 * CoAP over UDP prefix "coap://"
2367 * CoAP over TCP prefix "coap+tcp://"
2368 * CoAP over DTLS prefix "coaps://"
2369 * CoAP over TLS prefix "coaps+tcp://"
2371 * IPv6 address "[1234::5678]"
2372 * IPv4 address "192.168.1.1"
2373 * optional port ":5683"
2374 * resource uri "/oc/core..."
2376 * for PRESENCE requests, extract resource type.
2378 static OCStackResult ParseRequestUri(const char *fullUri,
2379 OCTransportAdapter adapter,
2380 OCTransportFlags flags,
2381 OCDevAddr **devAddr,
2383 char **resourceType)
2385 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2387 OCStackResult result = OC_STACK_OK;
2388 OCDevAddr *da = NULL;
2392 // provide defaults for all returned values
2399 *resourceUri = NULL;
2403 *resourceType = NULL;
2406 // delimit url prefix, if any
2407 const char *start = fullUri;
2408 char *slash2 = strstr(start, "//");
2413 char *slash = strchr(start, '/');
2416 return OC_STACK_INVALID_URI;
2419 // process url scheme
2420 size_t prefixLen = slash2 - fullUri;
2424 if (((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2425 || ((prefixLen == sizeof(COAPS_TCP) - 1) && (!strncmp(fullUri, COAPS_TCP, prefixLen))))
2431 // TODO: this logic should come in with unit tests exercising the various strings
2432 // processs url prefix, if any
2433 size_t urlLen = slash - start;
2437 if (urlLen && devAddr)
2438 { // construct OCDevAddr
2439 if (start[0] == '[')
2441 char *close = strchr(++start, ']');
2442 if (!close || close > slash)
2444 return OC_STACK_INVALID_URI;
2447 if (close[1] == ':')
2454 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2458 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2460 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2464 char *dot = strchr(start, '.');
2465 if (dot && dot < slash)
2467 colon = strchr(start, ':');
2468 end = (colon && colon < slash) ? colon : slash;
2473 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2477 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2479 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2487 if (len >= sizeof(da->addr))
2489 return OC_STACK_INVALID_URI;
2491 // collect port, if any
2492 if (colon && colon < slash)
2494 for (colon++; colon < slash; colon++)
2497 if (c < '0' || c > '9')
2499 return OC_STACK_INVALID_URI;
2501 port = 10 * port + c - '0';
2506 if (len >= sizeof(da->addr))
2508 return OC_STACK_INVALID_URI;
2511 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2514 return OC_STACK_NO_MEMORY;
2516 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2518 da->adapter = adapter;
2520 if (!strncmp(fullUri, "coaps", 5))
2522 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2527 // process resource uri, if any
2529 { // request uri and query
2530 size_t ulen = strlen(slash); // resource uri length
2531 size_t tlen = 0; // resource type length
2534 static const char strPresence[] = "/oic/ad?rt=";
2535 static const size_t lenPresence = sizeof(strPresence) - 1;
2536 if (!strncmp(slash, strPresence, lenPresence))
2538 type = slash + lenPresence;
2539 tlen = ulen - lenPresence;
2544 *resourceUri = (char *)OICMalloc(ulen + 1);
2547 result = OC_STACK_NO_MEMORY;
2550 strcpy(*resourceUri, slash);
2553 if (type && resourceType)
2555 *resourceType = (char *)OICMalloc(tlen + 1);
2558 result = OC_STACK_NO_MEMORY;
2562 OICStrcpy(*resourceType, (tlen+1), type);
2569 // free all returned values
2576 OICFree(*resourceUri);
2580 OICFree(*resourceType);
2585 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2590 char uri[CA_MAX_URI_LENGTH];
2592 FormCanonicalPresenceUri(endpoint, resourceUri, uri, isMulticast);
2594 *requestUri = OICStrdup(uri);
2597 return OC_STACK_NO_MEMORY;
2604 * Discover or Perform requests on a specified resource
2606 OCStackResult OCDoResource(OCDoHandle *handle,
2608 const char *requestUri,
2609 const OCDevAddr *destination,
2611 OCConnectivityType connectivityType,
2612 OCQualityOfService qos,
2613 OCCallbackData *cbData,
2614 OCHeaderOption *options,
2617 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2619 // Validate input parameters
2620 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2621 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2622 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2624 OCStackResult result = OC_STACK_ERROR;
2625 CAResult_t caResult;
2626 CAToken_t token = NULL;
2627 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2628 ClientCB *clientCB = NULL;
2629 OCDoHandle resHandle = NULL;
2630 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2631 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2633 OCTransportAdapter adapter;
2634 OCTransportFlags flags;
2635 // the request contents are put here
2636 CARequestInfo_t requestInfo = {.method = CA_GET};
2637 // requestUri will be parsed into the following three variables
2638 OCDevAddr *devAddr = NULL;
2639 char *resourceUri = NULL;
2640 char *resourceType = NULL;
2643 * Support original behavior with address on resourceUri argument.
2645 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2646 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2648 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2649 if (result != OC_STACK_OK)
2651 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2658 case OC_REST_OBSERVE:
2659 case OC_REST_OBSERVE_ALL:
2660 case OC_REST_CANCEL_OBSERVE:
2661 requestInfo.method = CA_GET;
2664 requestInfo.method = CA_PUT;
2667 requestInfo.method = CA_POST;
2669 case OC_REST_DELETE:
2670 requestInfo.method = CA_DELETE;
2672 case OC_REST_DISCOVER:
2674 #ifdef WITH_PRESENCE
2675 case OC_REST_PRESENCE:
2677 if (destination || devAddr)
2679 requestInfo.isMulticast = false;
2683 tmpDevAddr.adapter = adapter;
2684 tmpDevAddr.flags = flags;
2685 destination = &tmpDevAddr;
2686 requestInfo.isMulticast = true;
2688 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
2689 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
2690 // replacing method type with GET.
2691 requestInfo.method = CA_GET;
2694 result = OC_STACK_INVALID_METHOD;
2698 if (!devAddr && !destination)
2700 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2701 result = OC_STACK_INVALID_PARAM;
2705 /* If not original behavior, use destination argument */
2706 if (destination && !devAddr)
2708 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2711 result = OC_STACK_NO_MEMORY;
2714 *devAddr = *destination;
2717 resHandle = GenerateInvocationHandle();
2720 result = OC_STACK_NO_MEMORY;
2724 caResult = CAGenerateToken(&token, tokenLength);
2725 if (caResult != CA_STATUS_OK)
2727 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2728 result= OC_STACK_ERROR;
2732 // fill in request data
2733 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2734 requestInfo.info.token = token;
2735 requestInfo.info.tokenLength = tokenLength;
2736 requestInfo.info.resourceUri = resourceUri;
2738 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2740 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2741 options, numOptions, OC_OBSERVE_REGISTER);
2742 if (result != OC_STACK_OK)
2746 requestInfo.info.numOptions = numOptions + 1;
2750 requestInfo.info.numOptions = numOptions;
2751 requestInfo.info.options =
2752 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2753 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2754 numOptions * sizeof(CAHeaderOption_t));
2757 CopyDevAddrToEndpoint(devAddr, &endpoint);
2762 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2765 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2768 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2772 requestInfo.info.payload = NULL;
2773 requestInfo.info.payloadSize = 0;
2774 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2777 // prepare for response
2778 #ifdef WITH_PRESENCE
2779 if (method == OC_REST_PRESENCE)
2781 char *presenceUri = NULL;
2782 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri,
2783 requestInfo.isMulticast);
2784 if (OC_STACK_OK != result)
2789 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2790 // Presence notification will form a canonical uri to
2791 // look for callbacks into the application.
2792 resourceUri = presenceUri;
2796 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2797 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2798 method, devAddr, resourceUri, resourceType, ttl);
2799 if (OC_STACK_OK != result)
2804 devAddr = NULL; // Client CB list entry now owns it
2805 resourceUri = NULL; // Client CB list entry now owns it
2806 resourceType = NULL; // Client CB list entry now owns it
2809 result = OCSendRequest(&endpoint, &requestInfo);
2810 if (OC_STACK_OK != result)
2817 *handle = resHandle;
2821 if (result != OC_STACK_OK)
2823 OIC_LOG(ERROR, TAG, "OCDoResource error");
2824 FindAndDeleteClientCB(clientCB);
2825 CADestroyToken(token);
2833 // This is the owner of the payload object, so we free it
2834 OCPayloadDestroy(payload);
2835 OICFree(requestInfo.info.payload);
2837 OICFree(resourceUri);
2838 OICFree(resourceType);
2839 OICFree(requestInfo.info.options);
2843 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2847 * This ftn is implemented one of two ways in the case of observation:
2849 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2850 * Remove the callback associated on client side.
2851 * When the next notification comes in from server,
2852 * reply with RESET message to server.
2853 * Keep in mind that the server will react to RESET only
2854 * if the last notification was sent as CON
2856 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2857 * and it is associated with an observe request
2858 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2859 * Send CON Observe request to server with
2860 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2861 * Remove the callback associated on client side.
2863 OCStackResult ret = OC_STACK_OK;
2864 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2865 CARequestInfo_t requestInfo = {.method = CA_GET};
2869 return OC_STACK_INVALID_PARAM;
2872 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2875 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2876 return OC_STACK_ERROR;
2879 switch (clientCB->method)
2881 case OC_REST_OBSERVE:
2882 case OC_REST_OBSERVE_ALL:
2884 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2886 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2888 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2890 FindAndDeleteClientCB(clientCB);
2894 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2896 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2897 requestInfo.info.token = clientCB->token;
2898 requestInfo.info.tokenLength = clientCB->tokenLength;
2900 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2901 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2903 return OC_STACK_ERROR;
2905 requestInfo.info.numOptions = numOptions + 1;
2906 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2909 ret = OCSendRequest(&endpoint, &requestInfo);
2911 if (requestInfo.info.options)
2913 OICFree (requestInfo.info.options);
2915 if (requestInfo.info.resourceUri)
2917 OICFree (requestInfo.info.resourceUri);
2922 case OC_REST_DISCOVER:
2923 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2924 clientCB->requestUri);
2925 FindAndDeleteClientCB(clientCB);
2928 #ifdef WITH_PRESENCE
2929 case OC_REST_PRESENCE:
2930 FindAndDeleteClientCB(clientCB);
2935 ret = OC_STACK_INVALID_METHOD;
2943 * @brief Register Persistent storage callback.
2944 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2946 * OC_STACK_OK - No errors; Success
2947 * OC_STACK_INVALID_PARAM - Invalid parameter
2949 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2951 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2952 if(!persistentStorageHandler)
2954 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2955 return OC_STACK_INVALID_PARAM;
2959 if( !persistentStorageHandler->open ||
2960 !persistentStorageHandler->close ||
2961 !persistentStorageHandler->read ||
2962 !persistentStorageHandler->unlink ||
2963 !persistentStorageHandler->write)
2965 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2966 return OC_STACK_INVALID_PARAM;
2969 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2972 #ifdef WITH_PRESENCE
2974 OCStackResult OCProcessPresence()
2976 OCStackResult result = OC_STACK_OK;
2978 // the following line floods the log with messages that are irrelevant
2979 // to most purposes. Uncomment as needed.
2980 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2981 ClientCB* cbNode = NULL;
2982 OCClientResponse clientResponse;
2983 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2985 LL_FOREACH(cbList, cbNode)
2987 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2992 uint32_t now = GetTicks(0);
2993 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2994 cbNode->presence->TTLlevel);
2995 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2997 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3002 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3004 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3005 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3007 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3009 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3011 clientResponse.sequenceNumber = 0;
3012 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3013 clientResponse.devAddr = *cbNode->devAddr;
3014 FixUpClientResponse(&clientResponse);
3015 clientResponse.payload = NULL;
3017 // Increment the TTLLevel (going to a next state), so we don't keep
3018 // sending presence notification to client.
3019 cbNode->presence->TTLlevel++;
3020 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3021 cbNode->presence->TTLlevel);
3023 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3024 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3026 FindAndDeleteClientCB(cbNode);
3030 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3035 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3036 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3037 CARequestInfo_t requestInfo = {.method = CA_GET};
3039 OIC_LOG(DEBUG, TAG, "time to test server presence");
3041 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3043 requestData.type = CA_MSG_NONCONFIRM;
3044 requestData.token = cbNode->token;
3045 requestData.tokenLength = cbNode->tokenLength;
3046 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3047 requestInfo.method = CA_GET;
3048 requestInfo.info = requestData;
3050 result = OCSendRequest(&endpoint, &requestInfo);
3051 if (OC_STACK_OK != result)
3056 cbNode->presence->TTLlevel++;
3057 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3060 if (result != OC_STACK_OK)
3062 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3067 #endif // WITH_PRESENCE
3069 OCStackResult OCProcess()
3071 #ifdef WITH_PRESENCE
3072 OCProcessPresence();
3074 CAHandleRequestResponse();
3076 #ifdef ROUTING_GATEWAY
3086 #ifdef WITH_PRESENCE
3087 OCStackResult OCStartPresence(const uint32_t ttl)
3089 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3090 OCChangeResourceProperty(
3091 &(((OCResource *)presenceResource.handle)->resourceProperties),
3094 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3096 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3097 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3101 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3102 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3106 presenceResource.presenceTTL = ttl;
3108 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3110 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3112 presenceState = OC_PRESENCE_INITIALIZED;
3114 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3116 CAToken_t caToken = NULL;
3117 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3118 if (caResult != CA_STATUS_OK)
3120 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3121 CADestroyToken(caToken);
3122 return OC_STACK_ERROR;
3125 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3126 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3127 CADestroyToken(caToken);
3130 // Each time OCStartPresence is called
3131 // a different random 32-bit integer number is used
3132 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3134 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3135 OC_PRESENCE_TRIGGER_CREATE);
3138 OCStackResult OCStopPresence()
3140 OCStackResult result = OC_STACK_ERROR;
3142 if(presenceResource.handle)
3144 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3146 // make resource inactive
3147 result = OCChangeResourceProperty(
3148 &(((OCResource *) presenceResource.handle)->resourceProperties),
3152 if(result != OC_STACK_OK)
3155 "Changing the presence resource properties to ACTIVE not successful");
3159 return SendStopNotification();
3163 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3164 void* callbackParameter)
3166 defaultDeviceHandler = entityHandler;
3167 defaultDeviceHandlerCallbackParameter = callbackParameter;
3172 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3174 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3176 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3178 if (validatePlatformInfo(platformInfo))
3180 return SavePlatformInfo(platformInfo);
3184 return OC_STACK_INVALID_PARAM;
3189 return OC_STACK_ERROR;
3193 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3195 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3197 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3199 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3200 return OC_STACK_INVALID_PARAM;
3203 if (deviceInfo.types)
3205 OCStringLL *type = deviceInfo.types;
3206 OCResource *resource = findResource((OCResource *) deviceResource);
3209 return OC_STACK_INVALID_PARAM;
3214 OCBindResourceTypeToResource(deviceResource, type->value);
3218 return SaveDeviceInfo(deviceInfo);
3221 OCStackResult OCCreateResource(OCResourceHandle *handle,
3222 const char *resourceTypeName,
3223 const char *resourceInterfaceName,
3224 const char *uri, OCEntityHandler entityHandler,
3225 void* callbackParam,
3226 uint8_t resourceProperties)
3229 OCResource *pointer = NULL;
3230 OCStackResult result = OC_STACK_ERROR;
3232 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3234 if(myStackMode == OC_CLIENT)
3236 return OC_STACK_INVALID_PARAM;
3238 // Validate parameters
3239 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3241 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3242 return OC_STACK_INVALID_URI;
3244 // Is it presented during resource discovery?
3245 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3247 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3248 return OC_STACK_INVALID_PARAM;
3251 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3253 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3257 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3259 // Make sure resourceProperties bitmask has allowed properties specified
3260 if (resourceProperties
3261 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3262 OC_EXPLICIT_DISCOVERABLE
3271 OIC_LOG(ERROR, TAG, "Invalid property");
3272 return OC_STACK_INVALID_PARAM;
3275 // If the headResource is NULL, then no resources have been created...
3276 pointer = headResource;
3279 // At least one resources is in the resource list, so we need to search for
3280 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3283 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3285 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3286 return OC_STACK_INVALID_PARAM;
3288 pointer = pointer->next;
3291 // Create the pointer and insert it into the resource list
3292 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3295 result = OC_STACK_NO_MEMORY;
3298 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3300 insertResource(pointer);
3303 pointer->uri = OICStrdup(uri);
3306 result = OC_STACK_NO_MEMORY;
3310 // Set properties. Set OC_ACTIVE
3311 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3314 // Add the resourcetype to the resource
3315 result = BindResourceTypeToResource(pointer, resourceTypeName);
3316 if (result != OC_STACK_OK)
3318 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3322 // Add the resourceinterface to the resource
3323 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3324 if (result != OC_STACK_OK)
3326 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3330 // If an entity handler has been passed, attach it to the newly created
3331 // resource. Otherwise, set the default entity handler.
3334 pointer->entityHandler = entityHandler;
3335 pointer->entityHandlerCallbackParam = callbackParam;
3339 pointer->entityHandler = defaultResourceEHandler;
3340 pointer->entityHandlerCallbackParam = NULL;
3343 // Initialize a pointer indicating child resources in case of collection
3344 pointer->rsrcChildResourcesHead = NULL;
3347 result = OC_STACK_OK;
3349 #ifdef WITH_PRESENCE
3350 if (presenceResource.handle)
3352 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3353 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3357 if (result != OC_STACK_OK)
3359 // Deep delete of resource and other dynamic elements that it contains
3360 deleteResource(pointer);
3365 OCStackResult OCBindResource(
3366 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3368 OCResource *resource = NULL;
3369 OCChildResource *tempChildResource = NULL;
3370 OCChildResource *newChildResource = NULL;
3372 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3374 // Validate parameters
3375 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3376 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3377 // Container cannot contain itself
3378 if (collectionHandle == resourceHandle)
3380 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3381 return OC_STACK_INVALID_PARAM;
3384 // Use the handle to find the resource in the resource linked list
3385 resource = findResource((OCResource *) collectionHandle);
3388 OIC_LOG(ERROR, TAG, "Collection handle not found");
3389 return OC_STACK_INVALID_PARAM;
3392 // Look for an open slot to add add the child resource.
3393 // If found, add it and return success
3395 tempChildResource = resource->rsrcChildResourcesHead;
3397 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3399 // TODO: what if one of child resource was deregistered without unbinding?
3400 tempChildResource = tempChildResource->next;
3403 // Do memory allocation for child resource
3404 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3405 if(!newChildResource)
3407 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3408 return OC_STACK_ERROR;
3411 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3412 newChildResource->next = NULL;
3414 if(!resource->rsrcChildResourcesHead)
3416 resource->rsrcChildResourcesHead = newChildResource;
3419 tempChildResource->next = newChildResource;
3422 OIC_LOG(INFO, TAG, "resource bound");
3424 #ifdef WITH_PRESENCE
3425 if (presenceResource.handle)
3427 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3428 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3429 OC_PRESENCE_TRIGGER_CHANGE);
3436 OCStackResult OCUnBindResource(
3437 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3439 OCResource *resource = NULL;
3440 OCChildResource *tempChildResource = NULL;
3441 OCChildResource *tempLastChildResource = NULL;
3443 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3445 // Validate parameters
3446 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3447 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3448 // Container cannot contain itself
3449 if (collectionHandle == resourceHandle)
3451 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3452 return OC_STACK_INVALID_PARAM;
3455 // Use the handle to find the resource in the resource linked list
3456 resource = findResource((OCResource *) collectionHandle);
3459 OIC_LOG(ERROR, TAG, "Collection handle not found");
3460 return OC_STACK_INVALID_PARAM;
3463 // Look for an open slot to add add the child resource.
3464 // If found, add it and return success
3465 if(!resource->rsrcChildResourcesHead)
3467 OIC_LOG(INFO, TAG, "resource not found in collection");
3469 // Unable to add resourceHandle, so return error
3470 return OC_STACK_ERROR;
3474 tempChildResource = resource->rsrcChildResourcesHead;
3476 while (tempChildResource)
3478 if(tempChildResource->rsrcResource == resourceHandle)
3480 // if resource going to be unbinded is the head one.
3481 if( tempChildResource == resource->rsrcChildResourcesHead )
3483 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3484 OICFree(resource->rsrcChildResourcesHead);
3485 resource->rsrcChildResourcesHead = temp;
3490 OCChildResource *temp = tempChildResource->next;
3491 OICFree(tempChildResource);
3492 tempLastChildResource->next = temp;
3496 OIC_LOG(INFO, TAG, "resource unbound");
3498 // Send notification when resource is unbounded successfully.
3499 #ifdef WITH_PRESENCE
3500 if (presenceResource.handle)
3502 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3503 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3504 OC_PRESENCE_TRIGGER_CHANGE);
3507 tempChildResource = NULL;
3508 tempLastChildResource = NULL;
3514 tempLastChildResource = tempChildResource;
3515 tempChildResource = tempChildResource->next;
3518 OIC_LOG(INFO, TAG, "resource not found in collection");
3520 tempChildResource = NULL;
3521 tempLastChildResource = NULL;
3523 // Unable to add resourceHandle, so return error
3524 return OC_STACK_ERROR;
3527 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3529 if (!resourceItemName)
3533 // Per RFC 6690 only registered values must follow the first rule below.
3534 // At this point in time the only values registered begin with "core", and
3535 // all other values are specified as opaque strings where multiple values
3536 // are separated by a space.
3537 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3539 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3541 if (resourceItemName[index] != '.'
3542 && resourceItemName[index] != '-'
3543 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3544 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3552 for (size_t index = 0; resourceItemName[index]; ++index)
3554 if (resourceItemName[index] == ' '
3555 || resourceItemName[index] == '\t'
3556 || resourceItemName[index] == '\r'
3557 || resourceItemName[index] == '\n')
3567 OCStackResult BindResourceTypeToResource(OCResource* resource,
3568 const char *resourceTypeName)
3570 OCResourceType *pointer = NULL;
3572 OCStackResult result = OC_STACK_ERROR;
3574 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3576 if (!ValidateResourceTypeInterface(resourceTypeName))
3578 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3579 return OC_STACK_INVALID_PARAM;
3582 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3585 result = OC_STACK_NO_MEMORY;
3589 str = OICStrdup(resourceTypeName);
3592 result = OC_STACK_NO_MEMORY;
3595 pointer->resourcetypename = str;
3596 pointer->next = NULL;
3598 insertResourceType(resource, pointer);
3599 result = OC_STACK_OK;
3602 if (result != OC_STACK_OK)
3611 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3612 const char *resourceInterfaceName)
3614 OCResourceInterface *pointer = NULL;
3616 OCStackResult result = OC_STACK_ERROR;
3618 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3620 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3622 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3623 return OC_STACK_INVALID_PARAM;
3626 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3628 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3631 result = OC_STACK_NO_MEMORY;
3635 str = OICStrdup(resourceInterfaceName);
3638 result = OC_STACK_NO_MEMORY;
3641 pointer->name = str;
3643 // Bind the resourceinterface to the resource
3644 insertResourceInterface(resource, pointer);
3646 result = OC_STACK_OK;
3649 if (result != OC_STACK_OK)
3658 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3659 const char *resourceTypeName)
3662 OCStackResult result = OC_STACK_ERROR;
3663 OCResource *resource = NULL;
3665 resource = findResource((OCResource *) handle);
3668 OIC_LOG(ERROR, TAG, "Resource not found");
3669 return OC_STACK_ERROR;
3672 result = BindResourceTypeToResource(resource, resourceTypeName);
3674 #ifdef WITH_PRESENCE
3675 if(presenceResource.handle)
3677 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3678 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3685 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3686 const char *resourceInterfaceName)
3689 OCStackResult result = OC_STACK_ERROR;
3690 OCResource *resource = NULL;
3692 resource = findResource((OCResource *) handle);
3695 OIC_LOG(ERROR, TAG, "Resource not found");
3696 return OC_STACK_ERROR;
3699 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3701 #ifdef WITH_PRESENCE
3702 if (presenceResource.handle)
3704 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3705 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3712 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3714 OCResource *pointer = headResource;
3716 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3720 *numResources = *numResources + 1;
3721 pointer = pointer->next;
3726 OCResourceHandle OCGetResourceHandle(uint8_t index)
3728 OCResource *pointer = headResource;
3730 for( uint8_t i = 0; i < index && pointer; ++i)
3732 pointer = pointer->next;
3734 return (OCResourceHandle) pointer;
3737 OCStackResult OCDeleteResource(OCResourceHandle handle)
3741 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3742 return OC_STACK_INVALID_PARAM;
3745 OCResource *resource = findResource((OCResource *) handle);
3746 if (resource == NULL)
3748 OIC_LOG(ERROR, TAG, "Resource not found");
3749 return OC_STACK_NO_RESOURCE;
3752 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3754 OIC_LOG(ERROR, TAG, "Error deleting resource");
3755 return OC_STACK_ERROR;
3761 const char *OCGetResourceUri(OCResourceHandle handle)
3763 OCResource *resource = NULL;
3765 resource = findResource((OCResource *) handle);
3768 return resource->uri;
3770 return (const char *) NULL;
3773 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3775 OCResource *resource = NULL;
3777 resource = findResource((OCResource *) handle);
3780 return resource->resourceProperties;
3782 return (OCResourceProperty)-1;
3785 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3786 uint8_t *numResourceTypes)
3788 OCResource *resource = NULL;
3789 OCResourceType *pointer = NULL;
3791 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3792 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3794 *numResourceTypes = 0;
3796 resource = findResource((OCResource *) handle);
3799 pointer = resource->rsrcType;
3802 *numResourceTypes = *numResourceTypes + 1;
3803 pointer = pointer->next;
3809 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3811 OCResourceType *resourceType = NULL;
3813 resourceType = findResourceTypeAtIndex(handle, index);
3816 return resourceType->resourcetypename;
3818 return (const char *) NULL;
3821 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3822 uint8_t *numResourceInterfaces)
3824 OCResourceInterface *pointer = NULL;
3825 OCResource *resource = NULL;
3827 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3828 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3830 *numResourceInterfaces = 0;
3831 resource = findResource((OCResource *) handle);
3834 pointer = resource->rsrcInterface;
3837 *numResourceInterfaces = *numResourceInterfaces + 1;
3838 pointer = pointer->next;
3844 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3846 OCResourceInterface *resourceInterface = NULL;
3848 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3849 if (resourceInterface)
3851 return resourceInterface->name;
3853 return (const char *) NULL;
3856 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3859 OCResource *resource = NULL;
3860 OCChildResource *tempChildResource = NULL;
3863 resource = findResource((OCResource *) collectionHandle);
3869 tempChildResource = resource->rsrcChildResourcesHead;
3871 while(tempChildResource)
3875 return tempChildResource->rsrcResource;
3878 tempChildResource = tempChildResource->next;
3881 // In this case, the number of resource handles in the collection exceeds the index
3882 tempChildResource = NULL;
3886 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3887 OCEntityHandler entityHandler,
3888 void* callbackParam)
3890 OCResource *resource = NULL;
3892 // Validate parameters
3893 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3895 // Use the handle to find the resource in the resource linked list
3896 resource = findResource((OCResource *)handle);
3899 OIC_LOG(ERROR, TAG, "Resource not found");
3900 return OC_STACK_ERROR;
3904 resource->entityHandler = entityHandler;
3905 resource->entityHandlerCallbackParam = callbackParam;
3907 #ifdef WITH_PRESENCE
3908 if (presenceResource.handle)
3910 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3911 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3918 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3920 OCResource *resource = NULL;
3922 resource = findResource((OCResource *)handle);
3925 OIC_LOG(ERROR, TAG, "Resource not found");
3930 return resource->entityHandler;
3933 void incrementSequenceNumber(OCResource * resPtr)
3935 // Increment the sequence number
3936 resPtr->sequenceNum += 1;
3937 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3939 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3944 #ifdef WITH_PRESENCE
3945 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3946 OCPresenceTrigger trigger)
3948 OCResource *resPtr = NULL;
3949 OCStackResult result = OC_STACK_ERROR;
3950 OCMethod method = OC_REST_PRESENCE;
3951 uint32_t maxAge = 0;
3952 resPtr = findResource((OCResource *) presenceResource.handle);
3955 return OC_STACK_NO_RESOURCE;
3958 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3960 maxAge = presenceResource.presenceTTL;
3962 result = SendAllObserverNotification(method, resPtr, maxAge,
3963 trigger, resourceType, OC_LOW_QOS);
3969 OCStackResult SendStopNotification()
3971 OCResource *resPtr = NULL;
3972 OCStackResult result = OC_STACK_ERROR;
3973 OCMethod method = OC_REST_PRESENCE;
3974 resPtr = findResource((OCResource *) presenceResource.handle);
3977 return OC_STACK_NO_RESOURCE;
3980 // maxAge is 0. ResourceType is NULL.
3981 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3987 #endif // WITH_PRESENCE
3988 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3990 OCResource *resPtr = NULL;
3991 OCStackResult result = OC_STACK_ERROR;
3992 OCMethod method = OC_REST_NOMETHOD;
3993 uint32_t maxAge = 0;
3995 OIC_LOG(INFO, TAG, "Notifying all observers");
3996 #ifdef WITH_PRESENCE
3997 if(handle == presenceResource.handle)
4001 #endif // WITH_PRESENCE
4002 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4004 // Verify that the resource exists
4005 resPtr = findResource ((OCResource *) handle);
4008 return OC_STACK_NO_RESOURCE;
4012 //only increment in the case of regular observing (not presence)
4013 incrementSequenceNumber(resPtr);
4014 method = OC_REST_OBSERVE;
4015 maxAge = MAX_OBSERVE_AGE;
4016 #ifdef WITH_PRESENCE
4017 result = SendAllObserverNotification (method, resPtr, maxAge,
4018 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4020 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4027 OCNotifyListOfObservers (OCResourceHandle handle,
4028 OCObservationId *obsIdList,
4029 uint8_t numberOfIds,
4030 const OCRepPayload *payload,
4031 OCQualityOfService qos)
4033 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4035 OCResource *resPtr = NULL;
4036 //TODO: we should allow the server to define this
4037 uint32_t maxAge = MAX_OBSERVE_AGE;
4039 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4040 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4041 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4043 resPtr = findResource ((OCResource *) handle);
4044 if (NULL == resPtr || myStackMode == OC_CLIENT)
4046 return OC_STACK_NO_RESOURCE;
4050 incrementSequenceNumber(resPtr);
4052 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4053 payload, maxAge, qos));
4056 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4058 OCStackResult result = OC_STACK_ERROR;
4059 OCServerRequest *serverRequest = NULL;
4061 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4063 // Validate input parameters
4064 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4065 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4068 // Get pointer to request info
4069 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4072 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4073 result = serverRequest->ehResponseHandler(ehResponse);
4079 //#ifdef DIRECT_PAIRING
4080 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4082 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4083 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4085 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4089 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4092 const OCDPDev_t* OCGetDirectPairedDevices()
4094 return (const OCDPDev_t*)DPGetPairedDevices();
4097 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4098 OCDirectPairingCB resultCallback)
4100 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4101 if(NULL == peer || NULL == pinNumber)
4103 OIC_LOG(ERROR, TAG, "Invalid parameters");
4104 return OC_STACK_INVALID_PARAM;
4106 if (NULL == resultCallback)
4108 OIC_LOG(ERROR, TAG, "Invalid callback");
4109 return OC_STACK_INVALID_CALLBACK;
4112 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4113 pinNumber, (OCDirectPairingResultCB)resultCallback);
4115 //#endif // DIRECT_PAIRING
4117 //-----------------------------------------------------------------------------
4118 // Private internal function definitions
4119 //-----------------------------------------------------------------------------
4120 static OCDoHandle GenerateInvocationHandle()
4122 OCDoHandle handle = NULL;
4123 // Generate token here, it will be deleted when the transaction is deleted
4124 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4127 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4133 #ifdef WITH_PRESENCE
4134 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4135 OCResourceProperty resourceProperties, uint8_t enable)
4139 return OC_STACK_INVALID_PARAM;
4141 if (resourceProperties
4142 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4144 OIC_LOG(ERROR, TAG, "Invalid property");
4145 return OC_STACK_INVALID_PARAM;
4149 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4153 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4159 OCStackResult initResources()
4161 OCStackResult result = OC_STACK_OK;
4163 headResource = NULL;
4164 tailResource = NULL;
4165 // Init Virtual Resources
4166 #ifdef WITH_PRESENCE
4167 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4169 result = OCCreateResource(&presenceResource.handle,
4170 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4172 OC_RSRVD_PRESENCE_URI,
4176 //make resource inactive
4177 result = OCChangeResourceProperty(
4178 &(((OCResource *) presenceResource.handle)->resourceProperties),
4181 #ifndef WITH_ARDUINO
4182 if (result == OC_STACK_OK)
4184 result = SRMInitSecureResources();
4188 if(result == OC_STACK_OK)
4190 CreateResetProfile();
4191 result = OCCreateResource(&deviceResource,
4192 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4193 OC_RSRVD_INTERFACE_DEFAULT,
4194 OC_RSRVD_DEVICE_URI,
4198 if(result == OC_STACK_OK)
4200 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4201 OC_RSRVD_INTERFACE_READ);
4205 if(result == OC_STACK_OK)
4207 result = OCCreateResource(&platformResource,
4208 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4209 OC_RSRVD_INTERFACE_DEFAULT,
4210 OC_RSRVD_PLATFORM_URI,
4214 if(result == OC_STACK_OK)
4216 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4217 OC_RSRVD_INTERFACE_READ);
4224 void insertResource(OCResource *resource)
4228 headResource = resource;
4229 tailResource = resource;
4233 tailResource->next = resource;
4234 tailResource = resource;
4236 resource->next = NULL;
4239 OCResource *findResource(OCResource *resource)
4241 OCResource *pointer = headResource;
4245 if (pointer == resource)
4249 pointer = pointer->next;
4254 void deleteAllResources()
4256 OCResource *pointer = headResource;
4257 OCResource *temp = NULL;
4261 temp = pointer->next;
4262 #ifdef WITH_PRESENCE
4263 if (pointer != (OCResource *) presenceResource.handle)
4265 #endif // WITH_PRESENCE
4266 deleteResource(pointer);
4267 #ifdef WITH_PRESENCE
4269 #endif // WITH_PRESENCE
4272 memset(&platformResource, 0, sizeof(platformResource));
4273 memset(&deviceResource, 0, sizeof(deviceResource));
4275 memset(&brokerResource, 0, sizeof(brokerResource));
4278 SRMDeInitSecureResources();
4280 #ifdef WITH_PRESENCE
4281 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4282 // presence notification attributed to their deletion to be processed.
4283 deleteResource((OCResource *) presenceResource.handle);
4284 memset(&presenceResource, 0, sizeof(presenceResource));
4285 #endif // WITH_PRESENCE
4288 OCStackResult deleteResource(OCResource *resource)
4290 OCResource *prev = NULL;
4291 OCResource *temp = NULL;
4294 OIC_LOG(DEBUG,TAG,"resource is NULL");
4295 return OC_STACK_INVALID_PARAM;
4298 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4300 temp = headResource;
4303 if (temp == resource)
4305 // Invalidate all Resource Properties.
4306 resource->resourceProperties = (OCResourceProperty) 0;
4307 #ifdef WITH_PRESENCE
4308 if(resource != (OCResource *) presenceResource.handle)
4310 #endif // WITH_PRESENCE
4311 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4312 #ifdef WITH_PRESENCE
4315 if(presenceResource.handle)
4317 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4318 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4321 // Only resource in list.
4322 if (temp == headResource && temp == tailResource)
4324 headResource = NULL;
4325 tailResource = NULL;
4328 else if (temp == headResource)
4330 headResource = temp->next;
4333 else if (temp == tailResource)
4335 tailResource = prev;
4336 tailResource->next = NULL;
4340 prev->next = temp->next;
4343 deleteResourceElements(temp);
4354 return OC_STACK_ERROR;
4357 void deleteResourceElements(OCResource *resource)
4364 OICFree(resource->uri);
4365 deleteResourceType(resource->rsrcType);
4366 deleteResourceInterface(resource->rsrcInterface);
4369 void deleteResourceType(OCResourceType *resourceType)
4371 OCResourceType *pointer = resourceType;
4372 OCResourceType *next = NULL;
4376 next = pointer->next;
4377 OICFree(pointer->resourcetypename);
4383 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4385 OCResourceInterface *pointer = resourceInterface;
4386 OCResourceInterface *next = NULL;
4390 next = pointer->next;
4391 OICFree(pointer->name);
4397 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4399 OCResourceType *pointer = NULL;
4400 OCResourceType *previous = NULL;
4401 if (!resource || !resourceType)
4405 // resource type list is empty.
4406 else if (!resource->rsrcType)
4408 resource->rsrcType = resourceType;
4412 pointer = resource->rsrcType;
4416 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4418 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4419 OICFree(resourceType->resourcetypename);
4420 OICFree(resourceType);
4424 pointer = pointer->next;
4429 previous->next = resourceType;
4432 resourceType->next = NULL;
4434 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4437 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4439 OCResource *resource = NULL;
4440 OCResourceType *pointer = NULL;
4442 // Find the specified resource
4443 resource = findResource((OCResource *) handle);
4449 // Make sure a resource has a resourcetype
4450 if (!resource->rsrcType)
4455 // Iterate through the list
4456 pointer = resource->rsrcType;
4457 for(uint8_t i = 0; i< index && pointer; ++i)
4459 pointer = pointer->next;
4464 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4466 if(resourceTypeList && resourceTypeName)
4468 OCResourceType * rtPointer = resourceTypeList;
4469 while(resourceTypeName && rtPointer)
4471 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4472 if(rtPointer->resourcetypename &&
4473 strcmp(resourceTypeName, (const char *)
4474 (rtPointer->resourcetypename)) == 0)
4478 rtPointer = rtPointer->next;
4486 * Insert a new interface into interface linked list only if not already present.
4487 * If alredy present, 2nd arg is free'd.
4488 * Default interface will always be first if present.
4490 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4492 OCResourceInterface *pointer = NULL;
4493 OCResourceInterface *previous = NULL;
4495 newInterface->next = NULL;
4497 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4499 if (!*firstInterface)
4501 // If first interface is not oic.if.baseline, by default add it as first interface type.
4502 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4504 *firstInterface = newInterface;
4508 OCStackResult result = BindResourceInterfaceToResource(resource,
4509 OC_RSRVD_INTERFACE_DEFAULT);
4510 if (result != OC_STACK_OK)
4512 OICFree(newInterface->name);
4513 OICFree(newInterface);
4516 if (*firstInterface)
4518 (*firstInterface)->next = newInterface;
4522 // If once add oic.if.baseline, later too below code take care of freeing memory.
4523 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4525 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4527 OICFree(newInterface->name);
4528 OICFree(newInterface);
4531 // This code will not hit anymore, keeping
4534 newInterface->next = *firstInterface;
4535 *firstInterface = newInterface;
4540 pointer = *firstInterface;
4543 if (strcmp(newInterface->name, pointer->name) == 0)
4545 OICFree(newInterface->name);
4546 OICFree(newInterface);
4550 pointer = pointer->next;
4555 previous->next = newInterface;
4560 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4563 OCResource *resource = NULL;
4564 OCResourceInterface *pointer = NULL;
4566 // Find the specified resource
4567 resource = findResource((OCResource *) handle);
4573 // Make sure a resource has a resourceinterface
4574 if (!resource->rsrcInterface)
4579 // Iterate through the list
4580 pointer = resource->rsrcInterface;
4582 for (uint8_t i = 0; i < index && pointer; ++i)
4584 pointer = pointer->next;
4590 * This function splits the uri using the '?' delimiter.
4591 * "uriWithoutQuery" is the block of characters between the beginning
4592 * till the delimiter or '\0' which ever comes first.
4593 * "query" is whatever is to the right of the delimiter if present.
4594 * No delimiter sets the query to NULL.
4595 * If either are present, they will be malloc'ed into the params 2, 3.
4596 * The first param, *uri is left untouched.
4598 * NOTE: This function does not account for whitespace at the end of the uri NOR
4599 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4600 * part of the query.
4602 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4606 return OC_STACK_INVALID_URI;
4608 if(!query || !uriWithoutQuery)
4610 return OC_STACK_INVALID_PARAM;
4614 *uriWithoutQuery = NULL;
4616 size_t uriWithoutQueryLen = 0;
4617 size_t queryLen = 0;
4618 size_t uriLen = strlen(uri);
4620 char *pointerToDelimiter = strstr(uri, "?");
4622 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4623 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4625 if (uriWithoutQueryLen)
4627 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4628 if (!*uriWithoutQuery)
4632 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4636 *query = (char *) OICCalloc(queryLen + 1, 1);
4639 OICFree(*uriWithoutQuery);
4640 *uriWithoutQuery = NULL;
4643 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4649 return OC_STACK_NO_MEMORY;
4652 static const OicUuid_t* OCGetServerInstanceID(void)
4654 static bool generated = false;
4655 static OicUuid_t sid;
4661 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4663 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4670 const char* OCGetServerInstanceIDString(void)
4672 static bool generated = false;
4673 static char sidStr[UUID_STRING_SIZE];
4680 const OicUuid_t *sid = OCGetServerInstanceID();
4681 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4683 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4691 CAResult_t OCSelectNetwork()
4693 CAResult_t retResult = CA_STATUS_FAILED;
4694 CAResult_t caResult = CA_STATUS_OK;
4696 CATransportAdapter_t connTypes[] = {
4698 CA_ADAPTER_RFCOMM_BTEDR,
4699 CA_ADAPTER_GATT_BTLE,
4702 ,CA_ADAPTER_REMOTE_ACCESS
4709 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4711 for(int i = 0; i < numConnTypes; i++)
4713 // If CA status is not initialized, CASelectNetwork() will not be called.
4714 if (caResult != CA_STATUS_NOT_INITIALIZED)
4716 caResult = CASelectNetwork(connTypes[i]);
4717 if (caResult == CA_STATUS_OK)
4719 retResult = CA_STATUS_OK;
4724 if (retResult != CA_STATUS_OK)
4726 return caResult; // Returns error of appropriate transport that failed fatally.
4732 OCStackResult CAResultToOCResult(CAResult_t caResult)
4738 case CA_STATUS_INVALID_PARAM:
4739 return OC_STACK_INVALID_PARAM;
4740 case CA_ADAPTER_NOT_ENABLED:
4741 return OC_STACK_ADAPTER_NOT_ENABLED;
4742 case CA_SERVER_STARTED_ALREADY:
4744 case CA_SERVER_NOT_STARTED:
4745 return OC_STACK_ERROR;
4746 case CA_DESTINATION_NOT_REACHABLE:
4747 return OC_STACK_COMM_ERROR;
4748 case CA_SOCKET_OPERATION_FAILED:
4749 return OC_STACK_COMM_ERROR;
4750 case CA_SEND_FAILED:
4751 return OC_STACK_COMM_ERROR;
4752 case CA_RECEIVE_FAILED:
4753 return OC_STACK_COMM_ERROR;
4754 case CA_MEMORY_ALLOC_FAILED:
4755 return OC_STACK_NO_MEMORY;
4756 case CA_REQUEST_TIMEOUT:
4757 return OC_STACK_TIMEOUT;
4758 case CA_DESTINATION_DISCONNECTED:
4759 return OC_STACK_COMM_ERROR;
4760 case CA_STATUS_FAILED:
4761 return OC_STACK_ERROR;
4762 case CA_NOT_SUPPORTED:
4763 return OC_STACK_NOTIMPL;
4765 return OC_STACK_ERROR;
4769 bool OCResultToSuccess(OCStackResult ocResult)
4774 case OC_STACK_RESOURCE_CREATED:
4775 case OC_STACK_RESOURCE_DELETED:
4776 case OC_STACK_CONTINUE:
4777 case OC_STACK_RESOURCE_CHANGED:
4778 case OC_STACK_SLOW_RESOURCE:
4785 #if defined(RD_CLIENT) || defined(RD_SERVER)
4786 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
4788 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4790 OCResource *resource = NULL;
4792 resource = findResource((OCResource *) handle);
4795 OIC_LOG(ERROR, TAG, "Resource not found");
4796 return OC_STACK_ERROR;
4799 resource->ins = ins;
4804 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
4808 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
4812 OCResource *pointer = headResource;
4816 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
4818 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
4821 pointer = pointer->next;
4826 OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
4828 OCResource *resource = NULL;
4830 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4831 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
4833 resource = findResource((OCResource *) handle);
4836 *ins = resource->ins;
4839 return OC_STACK_ERROR;