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 OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
124 static PresenceResource presenceResource = {0};
125 static uint8_t PresenceTimeOutSize = 0;
126 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
129 static OCMode myStackMode;
131 //TODO: revisit this design
132 static bool gRASetInfo = false;
134 OCDeviceEntityHandler defaultDeviceHandler;
135 void* defaultDeviceHandlerCallbackParameter = NULL;
136 static const char COAP_TCP[] = "coap+tcp:";
137 static const char CORESPEC[] = "core";
139 //-----------------------------------------------------------------------------
141 //-----------------------------------------------------------------------------
142 #define TAG "OIC_RI_STACK"
143 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
144 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
145 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
146 TAG, #arg " is NULL"); return (retVal); } }
147 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
148 TAG, #arg " is NULL"); return; } }
149 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
152 //TODO: we should allow the server to define this
153 #define MAX_OBSERVE_AGE (0x2FFFFUL)
155 #define MILLISECONDS_PER_SECOND (1000)
157 //-----------------------------------------------------------------------------
158 // Private internal function prototypes
159 //-----------------------------------------------------------------------------
162 * Generate handle of OCDoResource invocation for callback management.
164 * @return Generated OCDoResource handle.
166 static OCDoHandle GenerateInvocationHandle();
169 * Initialize resource data structures, variables, etc.
171 * @return ::OC_STACK_OK on success, some other value upon failure.
173 static OCStackResult initResources();
176 * Add a resource to the end of the linked list of resources.
178 * @param resource Resource to be added
180 static void insertResource(OCResource *resource);
183 * Find a resource in the linked list of resources.
185 * @param resource Resource to be found.
186 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
189 static OCResource *findResource(OCResource *resource);
192 * Insert a resource type into a resource's resource type linked list.
193 * If resource type already exists, it will not be inserted and the
194 * resourceType will be free'd.
195 * resourceType->next should be null to avoid memory leaks.
196 * Function returns silently for null args.
198 * @param resource Resource where resource type is to be inserted.
199 * @param resourceType Resource type to be inserted.
201 static void insertResourceType(OCResource *resource,
202 OCResourceType *resourceType);
205 * Get a resource type at the specified index within a resource.
207 * @param handle Handle of resource.
208 * @param index Index of resource type.
210 * @return Pointer to resource type if found, NULL otherwise.
212 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
216 * Insert a resource interface into a resource's resource interface linked list.
217 * If resource interface already exists, it will not be inserted and the
218 * resourceInterface will be free'd.
219 * resourceInterface->next should be null to avoid memory leaks.
221 * @param resource Resource where resource interface is to be inserted.
222 * @param resourceInterface Resource interface to be inserted.
224 static void insertResourceInterface(OCResource *resource,
225 OCResourceInterface *resourceInterface);
228 * Get a resource interface at the specified index within a resource.
230 * @param handle Handle of resource.
231 * @param index Index of resource interface.
233 * @return Pointer to resource interface if found, NULL otherwise.
235 static OCResourceInterface *findResourceInterfaceAtIndex(
236 OCResourceHandle handle, uint8_t index);
239 * Delete all of the dynamically allocated elements that were created for the resource type.
241 * @param resourceType Specified resource type.
243 static void deleteResourceType(OCResourceType *resourceType);
246 * Delete all of the dynamically allocated elements that were created for the resource interface.
248 * @param resourceInterface Specified resource interface.
250 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
253 * Delete all of the dynamically allocated elements that were created for the resource.
255 * @param resource Specified resource.
257 static void deleteResourceElements(OCResource *resource);
260 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
263 * @param handle Handle of resource to be deleted.
265 * @return ::OC_STACK_OK on success, some other value upon failure.
267 static OCStackResult deleteResource(OCResource *resource);
270 * Delete all of the resources in the resource list.
272 static void deleteAllResources();
275 * Increment resource sequence number. Handles rollover.
277 * @param resPtr Pointer to resource.
279 static void incrementSequenceNumber(OCResource * resPtr);
282 * Attempts to initialize every network interface that the CA Layer might have compiled in.
284 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
285 * return something other than @ref CA_STATUS_OK, then this function fails.
287 * @return ::CA_STATUS_OK on success, some other value upon failure.
289 static CAResult_t OCSelectNetwork();
292 * Get the CoAP ticks after the specified number of milli-seconds.
294 * @param afterMilliSeconds Milli-seconds.
298 static uint32_t GetTicks(uint32_t afterMilliSeconds);
301 * Convert CAResult_t to OCStackResult.
303 * @param caResult CAResult_t code.
304 * @return ::OC_STACK_OK on success, some other value upon failure.
306 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
309 * Convert CAResponseResult_t to OCStackResult.
311 * @param caCode CAResponseResult_t code.
312 * @return ::OC_STACK_OK on success, some other value upon failure.
314 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
317 * Convert OCStackResult to CAResponseResult_t.
319 * @param caCode OCStackResult code.
320 * @param method OCMethod method the return code replies to.
321 * @return ::CA_CONTENT on OK, some other value upon failure.
323 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
326 * Convert OCTransportFlags_t to CATransportModifiers_t.
328 * @param ocConType OCTransportFlags_t input.
329 * @return CATransportFlags
331 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
334 * Convert CATransportFlags_t to OCTransportModifiers_t.
336 * @param caConType CATransportFlags_t input.
337 * @return OCTransportFlags
339 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
342 * Handle response from presence request.
344 * @param endPoint CA remote endpoint.
345 * @param responseInfo CA response info.
346 * @return ::OC_STACK_OK on success, some other value upon failure.
348 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
349 const CAResponseInfo_t *responseInfo);
352 * This function will be called back by CA layer when a response is received.
354 * @param endPoint CA remote endpoint.
355 * @param responseInfo CA response info.
357 static void HandleCAResponses(const CAEndpoint_t* endPoint,
358 const CAResponseInfo_t* responseInfo);
361 * This function will be called back by CA layer when a request is received.
363 * @param endPoint CA remote endpoint.
364 * @param requestInfo CA request info.
366 static void HandleCARequests(const CAEndpoint_t* endPoint,
367 const CARequestInfo_t* requestInfo);
370 * Extract query from a URI.
372 * @param uri Full URI with query.
373 * @param query Pointer to string that will contain query.
374 * @param newURI Pointer to string that will contain URI.
375 * @return ::OC_STACK_OK on success, some other value upon failure.
377 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
380 * Finds a resource type in an OCResourceType link-list.
382 * @param resourceTypeList The link-list to be searched through.
383 * @param resourceTypeName The key to search for.
385 * @return Resource type that matches the key (ie. resourceTypeName) or
386 * NULL if there is either an invalid parameter or this function was unable to find the key.
388 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
389 const char * resourceTypeName);
392 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
393 * TTL will be set to maxAge.
395 * @param cbNode Callback Node for which presence ttl is to be reset.
396 * @param maxAge New value of ttl in seconds.
398 * @return ::OC_STACK_OK on success, some other value upon failure.
400 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
403 * Ensure the accept header option is set appropriatly before sending the requests and routing
404 * header option is updated with destination.
406 * @param object CA remote endpoint.
407 * @param requestInfo CA request info.
409 * @return ::OC_STACK_OK on success, some other value upon failure.
411 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
413 //-----------------------------------------------------------------------------
414 // Internal functions
415 //-----------------------------------------------------------------------------
417 uint32_t GetTicks(uint32_t afterMilliSeconds)
422 // Guard against overflow of uint32_t
423 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
424 COAP_TICKS_PER_SECOND)
426 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
434 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
436 VERIFY_NON_NULL_NR(in, FATAL);
437 VERIFY_NON_NULL_NR(out, FATAL);
439 out->adapter = (OCTransportAdapter)in->adapter;
440 out->flags = CAToOCTransportFlags(in->flags);
441 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
442 out->port = in->port;
443 out->ifindex = in->ifindex;
444 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
445 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
449 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
451 VERIFY_NON_NULL_NR(in, FATAL);
452 VERIFY_NON_NULL_NR(out, FATAL);
454 out->adapter = (CATransportAdapter_t)in->adapter;
455 out->flags = OCToCATransportFlags(in->flags);
456 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
457 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
458 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
460 out->port = in->port;
461 out->ifindex = in->ifindex;
464 void FixUpClientResponse(OCClientResponse *cr)
466 VERIFY_NON_NULL_NR(cr, FATAL);
468 cr->addr = &cr->devAddr;
469 cr->connType = (OCConnectivityType)
470 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
473 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
475 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
476 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
478 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
479 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
480 if (OC_STACK_OK != rmResult)
482 OIC_LOG(ERROR, TAG, "Add destination option failed");
487 // OC stack prefer CBOR encoded payloads.
488 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
489 CAResult_t result = CASendRequest(object, requestInfo);
490 if(CA_STATUS_OK != result)
492 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
493 return CAResultToOCResult(result);
497 //-----------------------------------------------------------------------------
498 // Internal API function
499 //-----------------------------------------------------------------------------
501 // This internal function is called to update the stack with the status of
502 // observers and communication failures
503 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
505 OCStackResult result = OC_STACK_ERROR;
506 ResourceObserver * observer = NULL;
507 OCEntityHandlerRequest ehRequest = {0};
511 case OC_OBSERVER_NOT_INTERESTED:
512 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
513 observer = GetObserverUsingToken (token, tokenLength);
516 result = FormOCEntityHandlerRequest(&ehRequest,
517 (OCRequestHandle)NULL,
520 (OCResourceHandle)NULL,
521 NULL, PAYLOAD_TYPE_REPRESENTATION,
523 OC_OBSERVE_DEREGISTER,
526 if(result != OC_STACK_OK)
530 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
531 observer->resource->entityHandlerCallbackParam);
534 result = DeleteObserverUsingToken (token, tokenLength);
535 if(result == OC_STACK_OK)
537 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
541 result = OC_STACK_OK;
542 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
546 case OC_OBSERVER_STILL_INTERESTED:
547 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
548 observer = GetObserverUsingToken (token, tokenLength);
551 observer->forceHighQos = 0;
552 observer->failedCommCount = 0;
553 result = OC_STACK_OK;
557 result = OC_STACK_OBSERVER_NOT_FOUND;
561 case OC_OBSERVER_FAILED_COMM:
562 OIC_LOG(DEBUG, TAG, "observer is unreachable");
563 observer = GetObserverUsingToken (token, tokenLength);
566 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
568 result = FormOCEntityHandlerRequest(&ehRequest,
569 (OCRequestHandle)NULL,
572 (OCResourceHandle)NULL,
573 NULL, PAYLOAD_TYPE_REPRESENTATION,
575 OC_OBSERVE_DEREGISTER,
578 if(result != OC_STACK_OK)
580 return OC_STACK_ERROR;
582 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
583 observer->resource->entityHandlerCallbackParam);
585 result = DeleteObserverUsingToken (token, tokenLength);
586 if(result == OC_STACK_OK)
588 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
592 result = OC_STACK_OK;
593 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
598 observer->failedCommCount++;
599 result = OC_STACK_CONTINUE;
601 observer->forceHighQos = 1;
602 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
606 OIC_LOG(ERROR, TAG, "Unknown status");
607 result = OC_STACK_ERROR;
613 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
615 OCStackResult ret = OC_STACK_ERROR;
619 case CA_ADAPTER_NOT_ENABLED:
620 case CA_SERVER_NOT_STARTED:
621 ret = OC_STACK_ADAPTER_NOT_ENABLED;
623 case CA_MEMORY_ALLOC_FAILED:
624 ret = OC_STACK_NO_MEMORY;
626 case CA_STATUS_INVALID_PARAM:
627 ret = OC_STACK_INVALID_PARAM;
635 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
637 OCStackResult ret = OC_STACK_ERROR;
642 ret = OC_STACK_RESOURCE_CREATED;
645 ret = OC_STACK_RESOURCE_DELETED;
648 ret = OC_STACK_RESOURCE_CHANGED;
655 ret = OC_STACK_INVALID_QUERY;
657 case CA_UNAUTHORIZED_REQ:
658 ret = OC_STACK_UNAUTHORIZED_REQ;
661 ret = OC_STACK_INVALID_OPTION;
664 ret = OC_STACK_NO_RESOURCE;
666 case CA_RETRANSMIT_TIMEOUT:
667 ret = OC_STACK_COMM_ERROR;
669 case CA_REQUEST_ENTITY_TOO_LARGE:
670 ret = OC_STACK_TOO_LARGE_REQ;
678 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
680 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
689 // This Response Code is like HTTP 204 "No Content" but only used in
690 // response to POST and PUT requests.
694 // This Response Code is like HTTP 200 "OK" but only used in response to
699 // This should not happen but,
700 // give it a value just in case but output an error
702 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
705 case OC_STACK_RESOURCE_CREATED:
708 case OC_STACK_RESOURCE_DELETED:
711 case OC_STACK_INVALID_QUERY:
714 case OC_STACK_INVALID_OPTION:
717 case OC_STACK_NO_RESOURCE:
720 case OC_STACK_COMM_ERROR:
721 ret = CA_RETRANSMIT_TIMEOUT;
723 case OC_STACK_UNAUTHORIZED_REQ:
724 ret = CA_UNAUTHORIZED_REQ;
732 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
734 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
736 // supply default behavior.
737 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
739 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
741 if ((caFlags & OC_MASK_SCOPE) == 0)
743 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
748 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
750 return (OCTransportFlags)caFlags;
753 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
755 uint32_t lowerBound = 0;
756 uint32_t higherBound = 0;
758 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
760 return OC_STACK_INVALID_PARAM;
763 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
765 cbNode->presence->TTL = maxAgeSeconds;
767 for (int index = 0; index < PresenceTimeOutSize; index++)
769 // Guard against overflow
770 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
773 lowerBound = GetTicks((PresenceTimeOut[index] *
774 cbNode->presence->TTL *
775 MILLISECONDS_PER_SECOND)/100);
779 lowerBound = GetTicks(UINT32_MAX);
782 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
785 higherBound = GetTicks((PresenceTimeOut[index + 1] *
786 cbNode->presence->TTL *
787 MILLISECONDS_PER_SECOND)/100);
791 higherBound = GetTicks(UINT32_MAX);
794 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
796 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
797 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
798 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
801 cbNode->presence->TTLlevel = 0;
803 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
807 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
809 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
811 return OC_RSRVD_TRIGGER_CREATE;
813 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
815 return OC_RSRVD_TRIGGER_CHANGE;
819 return OC_RSRVD_TRIGGER_DELETE;
823 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
827 return OC_PRESENCE_TRIGGER_CREATE;
829 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
831 return OC_PRESENCE_TRIGGER_CREATE;
833 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
835 return OC_PRESENCE_TRIGGER_CHANGE;
839 return OC_PRESENCE_TRIGGER_DELETE;
844 * Encode an address string to match RFC6874.
846 * @param outputAddress a char array to be written with the encoded string.
848 * @param outputSize size of outputAddress buffer.
850 * @param inputAddress a char array of size <= CA_MAX_URI_LENGTH
851 * containing a valid IPv6 address string.
853 * @return OC_STACK_OK if encoding succeeded.
854 * Else an error occured.
856 OCStackResult encodeAddressForRFC6874(char *outputAddress,
858 const char *inputAddress)
860 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
861 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
863 /** @todo Use a max IPv6 string length instead of CA_MAX_URI_LENGTH. */
864 #define ENCODE_MAX_INPUT_LENGTH CA_MAX_URI_LENGTH
866 size_t inputLength = strnlen(inputAddress, ENCODE_MAX_INPUT_LENGTH);
868 if (inputLength >= ENCODE_MAX_INPUT_LENGTH)
870 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: too long/unterminated!");
871 return OC_STACK_INVALID_PARAM;
874 // inputSize includes the null terminator
875 size_t inputSize = inputLength + 1;
877 if (inputSize > outputSize)
879 OIC_LOG_V(ERROR, TAG,
880 "encodeAddressForRFC6874 failed: "
881 "outputSize (%d) < inputSize (%d)",
882 outputSize, inputSize);
884 return OC_STACK_ERROR;
887 char* percentChar = strchr(inputAddress, '%');
889 // If there is no '%' character, then no change is required to the string.
890 if (NULL == percentChar)
892 OICStrcpy(outputAddress, outputSize, inputAddress);
896 const char* addressPart = &inputAddress[0];
897 const char* scopeIdPart = percentChar + 1;
899 // Sanity check to make sure this string doesn't have more '%' characters
900 if (NULL != strchr(scopeIdPart, '%'))
902 return OC_STACK_ERROR;
905 // If no string follows the first '%', then the input was invalid.
906 if (scopeIdPart[0] == '\0')
908 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
909 return OC_STACK_ERROR;
912 // Check to see if the string is already encoded
913 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
915 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
916 return OC_STACK_ERROR;
919 // Fail if we don't have room for encoded string's two additional chars
920 if (outputSize < (inputSize + 2))
922 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
923 return OC_STACK_ERROR;
926 // Restore the null terminator with an escaped '%' character, per RFC6874
927 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
928 strcat(outputAddress, "%25");
929 strcat(outputAddress, scopeIdPart);
935 * The cononical presence allows constructed URIs to be string compared.
937 * requestUri must be a char array of size CA_MAX_URI_LENGTH
939 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
942 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
943 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
944 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
946 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
948 if (ep->adapter == CA_ADAPTER_IP)
950 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
952 if ('\0' == ep->addr[0]) // multicast
954 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
958 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
960 OCStackResult result = encodeAddressForRFC6874(addressEncoded,
961 sizeof(addressEncoded),
964 if (OC_STACK_OK != result)
969 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
970 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
975 if ('\0' == ep->addr[0]) // multicast
977 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
978 ep->port = OC_MULTICAST_PORT;
980 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
981 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
985 // might work for other adapters (untested, but better than nothing)
986 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
987 OC_RSRVD_PRESENCE_URI);
991 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
992 const CAResponseInfo_t *responseInfo)
994 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
995 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
997 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
998 ClientCB * cbNode = NULL;
999 char *resourceTypeName = NULL;
1000 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1001 OCStackResult result = OC_STACK_ERROR;
1002 uint32_t maxAge = 0;
1004 char presenceUri[CA_MAX_URI_LENGTH];
1006 int presenceSubscribe = 0;
1007 int multicastPresenceSubscribe = 0;
1009 if (responseInfo->result != CA_CONTENT)
1011 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1012 return OC_STACK_ERROR;
1015 // check for unicast presence
1016 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
1017 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1019 return OC_STACK_INVALID_URI;
1022 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1025 presenceSubscribe = 1;
1029 // check for multiicast presence
1030 CAEndpoint_t ep = { .adapter = endpoint->adapter,
1031 .flags = endpoint->flags };
1033 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
1035 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1038 multicastPresenceSubscribe = 1;
1042 if (!presenceSubscribe && !multicastPresenceSubscribe)
1044 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1048 response.payload = NULL;
1049 response.result = OC_STACK_OK;
1051 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1052 FixUpClientResponse(&response);
1054 if (responseInfo->info.payload)
1056 result = OCParsePayload(&response.payload,
1057 PAYLOAD_TYPE_PRESENCE,
1058 responseInfo->info.payload,
1059 responseInfo->info.payloadSize);
1061 if(result != OC_STACK_OK)
1063 OIC_LOG(ERROR, TAG, "Presence parse failed");
1066 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1068 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1069 result = OC_STACK_ERROR;
1072 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1073 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1074 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1077 if (presenceSubscribe)
1079 if(cbNode->sequenceNumber == response.sequenceNumber)
1081 OIC_LOG(INFO, TAG, "No presence change");
1082 ResetPresenceTTL(cbNode, maxAge);
1083 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1089 OIC_LOG(INFO, TAG, "Stopping presence");
1090 response.result = OC_STACK_PRESENCE_STOPPED;
1091 if(cbNode->presence)
1093 OICFree(cbNode->presence->timeOut);
1094 OICFree(cbNode->presence);
1095 cbNode->presence = NULL;
1100 if(!cbNode->presence)
1102 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1104 if(!(cbNode->presence))
1106 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1107 result = OC_STACK_NO_MEMORY;
1111 VERIFY_NON_NULL_V(cbNode->presence);
1112 cbNode->presence->timeOut = NULL;
1113 cbNode->presence->timeOut = (uint32_t *)
1114 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1115 if(!(cbNode->presence->timeOut)){
1117 "Could not allocate memory for cbNode->presence->timeOut");
1118 OICFree(cbNode->presence);
1119 result = OC_STACK_NO_MEMORY;
1124 ResetPresenceTTL(cbNode, maxAge);
1126 cbNode->sequenceNumber = response.sequenceNumber;
1128 // Ensure that a filter is actually applied.
1129 if( resourceTypeName && cbNode->filterResourceType)
1131 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1140 // This is the multicast case
1141 OCMulticastNode* mcNode = NULL;
1142 mcNode = GetMCPresenceNode(presenceUri);
1146 if(mcNode->nonce == response.sequenceNumber)
1148 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1151 mcNode->nonce = response.sequenceNumber;
1155 OIC_LOG(INFO, TAG, "Stopping presence");
1156 response.result = OC_STACK_PRESENCE_STOPPED;
1161 char* uri = OICStrdup(presenceUri);
1165 "No Memory for URI to store in the presence node");
1166 result = OC_STACK_NO_MEMORY;
1170 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1171 if(result == OC_STACK_NO_MEMORY)
1174 "No Memory for Multicast Presence Node");
1178 // presence node now owns uri
1181 // Ensure that a filter is actually applied.
1182 if(resourceTypeName && cbNode->filterResourceType)
1184 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1191 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1193 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1195 FindAndDeleteClientCB(cbNode);
1199 OCPayloadDestroy(response.payload);
1203 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1205 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1207 if(responseInfo->info.resourceUri &&
1208 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1210 HandlePresenceResponse(endPoint, responseInfo);
1214 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1215 responseInfo->info.tokenLength, NULL, NULL);
1217 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1218 responseInfo->info.tokenLength);
1222 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1223 if(responseInfo->result == CA_EMPTY)
1225 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1226 // We do not have a case for the client to receive a RESET
1227 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1229 //This is the case of receiving an ACK on a request to a slow resource!
1230 OIC_LOG(INFO, TAG, "This is a pure ACK");
1231 //TODO: should we inform the client
1232 // app that at least the request was received at the server?
1235 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1237 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1238 OIC_LOG(INFO, TAG, "Calling into application address space");
1240 OCClientResponse response =
1241 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1242 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1243 FixUpClientResponse(&response);
1244 response.resourceUri = responseInfo->info.resourceUri;
1245 memcpy(response.identity.id, responseInfo->info.identity.id,
1246 sizeof (response.identity.id));
1247 response.identity.id_length = responseInfo->info.identity.id_length;
1249 response.result = CAResponseToOCStackResult(responseInfo->result);
1250 cbNode->callBack(cbNode->context,
1251 cbNode->handle, &response);
1252 FindAndDeleteClientCB(cbNode);
1256 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1257 OIC_LOG(INFO, TAG, "Calling into application address space");
1259 OCClientResponse response =
1260 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1261 response.sequenceNumber = -1;
1262 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1263 FixUpClientResponse(&response);
1264 response.resourceUri = responseInfo->info.resourceUri;
1265 memcpy(response.identity.id, responseInfo->info.identity.id,
1266 sizeof (response.identity.id));
1267 response.identity.id_length = responseInfo->info.identity.id_length;
1269 response.result = CAResponseToOCStackResult(responseInfo->result);
1271 if(responseInfo->info.payload &&
1272 responseInfo->info.payloadSize)
1274 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1275 // check the security resource
1276 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1278 type = PAYLOAD_TYPE_SECURITY;
1280 else if (cbNode->method == OC_REST_DISCOVER)
1282 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1283 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1285 type = PAYLOAD_TYPE_DISCOVERY;
1287 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1289 type = PAYLOAD_TYPE_DEVICE;
1291 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1293 type = PAYLOAD_TYPE_PLATFORM;
1295 #ifdef ROUTING_GATEWAY
1296 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1298 type = PAYLOAD_TYPE_REPRESENTATION;
1301 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1303 type = PAYLOAD_TYPE_RD;
1306 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1308 type = PAYLOAD_TYPE_REPRESENTATION;
1313 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1314 cbNode->method, cbNode->requestUri);
1318 else if (cbNode->method == OC_REST_GET ||
1319 cbNode->method == OC_REST_PUT ||
1320 cbNode->method == OC_REST_POST ||
1321 cbNode->method == OC_REST_OBSERVE ||
1322 cbNode->method == OC_REST_OBSERVE_ALL ||
1323 cbNode->method == OC_REST_DELETE)
1325 char targetUri[MAX_URI_LENGTH];
1326 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1327 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1328 if (strcmp(targetUri, cbNode->requestUri) == 0)
1330 type = PAYLOAD_TYPE_RD;
1332 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1334 type = PAYLOAD_TYPE_PLATFORM;
1336 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1338 type = PAYLOAD_TYPE_DEVICE;
1340 if (type == PAYLOAD_TYPE_INVALID)
1342 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1343 cbNode->method, cbNode->requestUri);
1344 type = PAYLOAD_TYPE_REPRESENTATION;
1349 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1350 cbNode->method, cbNode->requestUri);
1354 if(OC_STACK_OK != OCParsePayload(&response.payload,
1356 responseInfo->info.payload,
1357 responseInfo->info.payloadSize))
1359 OIC_LOG(ERROR, TAG, "Error converting payload");
1360 OCPayloadDestroy(response.payload);
1365 response.numRcvdVendorSpecificHeaderOptions = 0;
1366 if(responseInfo->info.numOptions > 0)
1369 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1370 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1373 uint32_t observationOption;
1374 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1375 for (observationOption=0, i=0;
1376 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1380 (observationOption << 8) | optionData[i];
1382 response.sequenceNumber = observationOption;
1384 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1389 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1392 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1394 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1395 OCPayloadDestroy(response.payload);
1399 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1401 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1402 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1406 if (cbNode->method == OC_REST_OBSERVE &&
1407 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1408 response.sequenceNumber <= cbNode->sequenceNumber)
1410 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1411 response.sequenceNumber);
1415 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1418 cbNode->sequenceNumber = response.sequenceNumber;
1420 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1422 FindAndDeleteClientCB(cbNode);
1426 // To keep discovery callbacks active.
1427 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1428 MILLISECONDS_PER_SECOND);
1432 //Need to send ACK when the response is CON
1433 if(responseInfo->info.type == CA_MSG_CONFIRM)
1435 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1436 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1439 OCPayloadDestroy(response.payload);
1446 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1447 if(responseInfo->result == CA_EMPTY)
1449 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1450 if(responseInfo->info.type == CA_MSG_RESET)
1452 OIC_LOG(INFO, TAG, "This is a RESET");
1453 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1454 OC_OBSERVER_NOT_INTERESTED);
1456 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1458 OIC_LOG(INFO, TAG, "This is a pure ACK");
1459 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1460 OC_OBSERVER_STILL_INTERESTED);
1463 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1465 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1466 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1467 OC_OBSERVER_FAILED_COMM);
1472 if(!cbNode && !observer)
1474 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1475 || myStackMode == OC_GATEWAY)
1477 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1478 if(responseInfo->result == CA_EMPTY)
1480 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1484 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1485 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1486 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1490 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1491 || myStackMode == OC_GATEWAY)
1493 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1494 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1496 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1497 responseInfo->info.messageId);
1499 if (responseInfo->info.type == CA_MSG_RESET)
1501 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1502 responseInfo->info.messageId);
1509 OIC_LOG(INFO, TAG, "Exit OCHandleResponse");
1512 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1514 VERIFY_NON_NULL_NR(endPoint, FATAL);
1515 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1517 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1519 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1520 #ifdef ROUTING_GATEWAY
1521 bool needRIHandling = false;
1523 * Routing manager is going to update either of endpoint or response or both.
1524 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1525 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1528 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1530 if(ret != OC_STACK_OK || !needRIHandling)
1532 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1538 * Put source in sender endpoint so that the next packet from application can be routed to
1539 * proper destination and remove "RM" coap header option before passing request / response to
1540 * RI as this option will make no sense to either RI or application.
1542 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1543 (uint8_t *) &(responseInfo->info.numOptions),
1544 (CAEndpoint_t *) endPoint);
1547 OCHandleResponse(endPoint, responseInfo);
1549 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1553 * This function handles error response from CA
1554 * code shall be added to handle the errors
1556 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1558 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1560 if (NULL == endPoint)
1562 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1566 if (NULL == errorInfo)
1568 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1572 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1573 errorInfo->info.tokenLength, NULL, NULL);
1576 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1577 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1578 FixUpClientResponse(&response);
1579 response.resourceUri = errorInfo->info.resourceUri;
1580 memcpy(response.identity.id, errorInfo->info.identity.id,
1581 sizeof (response.identity.id));
1582 response.identity.id_length = errorInfo->info.identity.id_length;
1583 response.result = CAResultToOCStackResult(errorInfo->result);
1585 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1586 FindAndDeleteClientCB(cbNode);
1589 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1593 * This function sends out Direct Stack Responses. These are responses that are not coming
1594 * from the application entity handler. These responses have no payload and are usually ACKs,
1595 * RESETs or some error conditions that were caught by the stack.
1597 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1598 const CAResponseResult_t responseResult, const CAMessageType_t type,
1599 const uint8_t numOptions, const CAHeaderOption_t *options,
1600 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1602 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1603 CAResponseInfo_t respInfo = {
1604 .result = responseResult
1606 respInfo.info.messageId = coapID;
1607 respInfo.info.numOptions = numOptions;
1609 if (respInfo.info.numOptions)
1611 respInfo.info.options =
1612 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1613 memcpy (respInfo.info.options, options,
1614 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1618 respInfo.info.payload = NULL;
1619 respInfo.info.token = token;
1620 respInfo.info.tokenLength = tokenLength;
1621 respInfo.info.type = type;
1622 respInfo.info.resourceUri = OICStrdup (resourceUri);
1623 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1625 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1626 // Add the destination to route option from the endpoint->routeData.
1627 bool doPost = false;
1628 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1629 if(OC_STACK_OK != result)
1631 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1636 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1637 CARequestInfo_t reqInfo = {.method = CA_POST };
1638 /* The following initialization is not done in a single initializer block as in
1639 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1640 * does not have designated initalizers. This is a work-around for now.
1642 reqInfo.info.type = CA_MSG_NONCONFIRM;
1643 reqInfo.info.messageId = coapID;
1644 reqInfo.info.tokenLength = tokenLength;
1645 reqInfo.info.token = token;
1646 reqInfo.info.numOptions = respInfo.info.numOptions;
1647 reqInfo.info.payload = NULL;
1648 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1649 if (reqInfo.info.numOptions)
1651 reqInfo.info.options =
1652 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1653 if (NULL == reqInfo.info.options)
1655 OIC_LOG(ERROR, TAG, "Calloc failed");
1656 return OC_STACK_NO_MEMORY;
1658 memcpy (reqInfo.info.options, respInfo.info.options,
1659 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1662 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1663 OICFree (reqInfo.info.resourceUri);
1664 OICFree (reqInfo.info.options);
1665 OICFree (respInfo.info.resourceUri);
1666 OICFree (respInfo.info.options);
1667 if (CA_STATUS_OK != caResult)
1669 OIC_LOG(ERROR, TAG, "CASendRequest error");
1670 return CAResultToOCResult(caResult);
1676 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1678 // resourceUri in the info field is cloned in the CA layer and
1679 // thus ownership is still here.
1680 OICFree (respInfo.info.resourceUri);
1681 OICFree (respInfo.info.options);
1682 if(CA_STATUS_OK != caResult)
1684 OIC_LOG(ERROR, TAG, "CASendResponse error");
1685 return CAResultToOCResult(caResult);
1688 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1692 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1694 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1695 OCStackResult result = OC_STACK_ERROR;
1696 if(!protocolRequest)
1698 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1699 return OC_STACK_INVALID_PARAM;
1702 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1703 protocolRequest->tokenLength);
1706 OIC_LOG(INFO, TAG, "This is a new Server Request");
1707 result = AddServerRequest(&request, protocolRequest->coapID,
1708 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1709 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1710 protocolRequest->observationOption, protocolRequest->qos,
1711 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1712 protocolRequest->payload, protocolRequest->requestToken,
1713 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1714 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1715 &protocolRequest->devAddr);
1716 if (OC_STACK_OK != result)
1718 OIC_LOG(ERROR, TAG, "Error adding server request");
1724 OIC_LOG(ERROR, TAG, "Out of Memory");
1725 return OC_STACK_NO_MEMORY;
1728 if(!protocolRequest->reqMorePacket)
1730 request->requestComplete = 1;
1735 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1738 if(request->requestComplete)
1740 OIC_LOG(INFO, TAG, "This Server Request is complete");
1741 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1742 OCResource *resource = NULL;
1743 result = DetermineResourceHandling (request, &resHandling, &resource);
1744 if (result == OC_STACK_OK)
1746 result = ProcessRequest(resHandling, resource, request);
1751 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1752 result = OC_STACK_CONTINUE;
1757 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1759 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1762 if (requestInfo->info.resourceUri &&
1763 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1765 HandleKeepAliveRequest(endPoint, requestInfo);
1770 OCStackResult requestResult = OC_STACK_ERROR;
1772 if(myStackMode == OC_CLIENT)
1774 //TODO: should the client be responding to requests?
1778 OCServerProtocolRequest serverRequest = {0};
1780 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1782 char * uriWithoutQuery = NULL;
1783 char * query = NULL;
1785 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1787 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1789 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1792 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1793 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1795 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1797 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1798 OICFree(uriWithoutQuery);
1802 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1803 OICFree(uriWithoutQuery);
1810 if(strlen(query) < MAX_QUERY_LENGTH)
1812 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1817 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1823 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1825 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1826 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1827 if (!serverRequest.payload)
1829 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1832 memcpy (serverRequest.payload, requestInfo->info.payload,
1833 requestInfo->info.payloadSize);
1837 serverRequest.reqTotalSize = 0;
1840 switch (requestInfo->method)
1843 serverRequest.method = OC_REST_GET;
1846 serverRequest.method = OC_REST_PUT;
1849 serverRequest.method = OC_REST_POST;
1852 serverRequest.method = OC_REST_DELETE;
1855 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1856 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1857 requestInfo->info.type, requestInfo->info.numOptions,
1858 requestInfo->info.options, requestInfo->info.token,
1859 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1860 OICFree(serverRequest.payload);
1864 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1865 requestInfo->info.tokenLength);
1867 serverRequest.tokenLength = requestInfo->info.tokenLength;
1868 if (serverRequest.tokenLength) {
1870 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1872 if (!serverRequest.requestToken)
1874 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1875 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1876 requestInfo->info.type, requestInfo->info.numOptions,
1877 requestInfo->info.options, requestInfo->info.token,
1878 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1879 OICFree(serverRequest.payload);
1882 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1885 switch (requestInfo->info.acceptFormat)
1887 case CA_FORMAT_APPLICATION_CBOR:
1888 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1890 case CA_FORMAT_UNDEFINED:
1891 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1894 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1897 if (requestInfo->info.type == CA_MSG_CONFIRM)
1899 serverRequest.qos = OC_HIGH_QOS;
1903 serverRequest.qos = OC_LOW_QOS;
1905 // CA does not need the following field
1906 // Are we sure CA does not need them? how is it responding to multicast
1907 serverRequest.delayedResNeeded = 0;
1909 serverRequest.coapID = requestInfo->info.messageId;
1911 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1913 // copy vendor specific header options
1914 uint8_t tempNum = (requestInfo->info.numOptions);
1916 // Assume no observation requested and it is a pure GET.
1917 // If obs registration/de-registration requested it'll be fetched from the
1918 // options in GetObserveHeaderOption()
1919 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1921 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1922 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1925 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1926 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1927 requestInfo->info.type, requestInfo->info.numOptions,
1928 requestInfo->info.options, requestInfo->info.token,
1929 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1930 OICFree(serverRequest.payload);
1931 OICFree(serverRequest.requestToken);
1934 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1935 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1937 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1938 sizeof(CAHeaderOption_t)*tempNum);
1941 requestResult = HandleStackRequests (&serverRequest);
1943 // Send ACK to client as precursor to slow response
1944 if (requestResult == OC_STACK_SLOW_RESOURCE)
1946 if (requestInfo->info.type == CA_MSG_CONFIRM)
1948 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1949 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1952 else if(!OCResultToSuccess(requestResult))
1954 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1956 CAResponseResult_t stackResponse =
1957 OCToCAStackResult(requestResult, serverRequest.method);
1959 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1960 requestInfo->info.type, requestInfo->info.numOptions,
1961 requestInfo->info.options, requestInfo->info.token,
1962 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1964 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1965 // The token is copied in there, and is thus still owned by this function.
1966 OICFree(serverRequest.payload);
1967 OICFree(serverRequest.requestToken);
1968 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1971 //This function will be called back by CA layer when a request is received
1972 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1974 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1977 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1983 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
1987 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1988 #ifdef ROUTING_GATEWAY
1989 bool needRIHandling = false;
1990 bool isEmptyMsg = false;
1992 * Routing manager is going to update either of endpoint or request or both.
1993 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1994 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1995 * destination. It can also remove "RM" coap header option before passing request / response to
1996 * RI as this option will make no sense to either RI or application.
1998 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1999 &needRIHandling, &isEmptyMsg);
2000 if(OC_STACK_OK != ret || !needRIHandling)
2002 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2008 * Put source in sender endpoint so that the next packet from application can be routed to
2009 * proper destination and remove RM header option.
2011 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2012 (uint8_t *) &(requestInfo->info.numOptions),
2013 (CAEndpoint_t *) endPoint);
2015 #ifdef ROUTING_GATEWAY
2019 * In Gateways, the MSGType in route option is used to check if the actual
2020 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2021 * EMPTY response is sent in the form of POST request which need to be changed
2022 * to a EMPTY response by RM. This translation is done in this part of the code.
2024 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2025 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2026 .info.messageId = requestInfo->info.messageId,
2027 .info.type = CA_MSG_ACKNOWLEDGE};
2028 OCHandleResponse(endPoint, &respInfo);
2034 // Normal handling of the packet
2035 OCHandleRequests(endPoint, requestInfo);
2037 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2040 bool validatePlatformInfo(OCPlatformInfo info)
2043 if (!info.platformID)
2045 OIC_LOG(ERROR, TAG, "No platform ID found.");
2049 if (info.manufacturerName)
2051 size_t lenManufacturerName = strlen(info.manufacturerName);
2053 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2055 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2061 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2065 if (info.manufacturerUrl)
2067 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2069 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2076 //-----------------------------------------------------------------------------
2078 //-----------------------------------------------------------------------------
2080 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2083 !raInfo->username ||
2084 !raInfo->hostname ||
2085 !raInfo->xmpp_domain)
2088 return OC_STACK_INVALID_PARAM;
2090 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2091 gRASetInfo = (result == OC_STACK_OK)? true : false;
2097 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2101 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2104 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2106 if(stackState == OC_STACK_INITIALIZED)
2108 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2109 OCStop() between them are ignored.");
2113 #ifndef ROUTING_GATEWAY
2114 if (OC_GATEWAY == mode)
2116 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2117 return OC_STACK_INVALID_PARAM;
2124 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2125 return OC_STACK_ERROR;
2129 OCStackResult result = OC_STACK_ERROR;
2130 OIC_LOG(INFO, TAG, "Entering OCInit");
2133 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2134 || (mode == OC_GATEWAY)))
2136 OIC_LOG(ERROR, TAG, "Invalid mode");
2137 return OC_STACK_ERROR;
2141 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2143 caglobals.client = true;
2145 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2147 caglobals.server = true;
2150 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2151 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2153 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2155 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2156 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2158 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2161 defaultDeviceHandler = NULL;
2162 defaultDeviceHandlerCallbackParameter = NULL;
2164 result = CAResultToOCResult(CAInitialize());
2165 VERIFY_SUCCESS(result, OC_STACK_OK);
2167 result = CAResultToOCResult(OCSelectNetwork());
2168 VERIFY_SUCCESS(result, OC_STACK_OK);
2170 switch (myStackMode)
2173 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2174 result = CAResultToOCResult(CAStartDiscoveryServer());
2175 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2178 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2179 result = CAResultToOCResult(CAStartListeningServer());
2180 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2182 case OC_CLIENT_SERVER:
2184 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2185 result = CAResultToOCResult(CAStartListeningServer());
2186 if(result == OC_STACK_OK)
2188 result = CAResultToOCResult(CAStartDiscoveryServer());
2192 VERIFY_SUCCESS(result, OC_STACK_OK);
2195 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2198 #ifdef WITH_PRESENCE
2199 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2200 #endif // WITH_PRESENCE
2202 //Update Stack state to initialized
2203 stackState = OC_STACK_INITIALIZED;
2205 // Initialize resource
2206 if(myStackMode != OC_CLIENT)
2208 result = initResources();
2211 // Initialize the SRM Policy Engine
2212 if(result == OC_STACK_OK)
2214 result = SRMInitPolicyEngine();
2215 // TODO after BeachHead delivery: consolidate into single SRMInit()
2217 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2218 RMSetStackMode(mode);
2219 #ifdef ROUTING_GATEWAY
2220 if (OC_GATEWAY == myStackMode)
2222 result = RMInitialize();
2228 if (result == OC_STACK_OK)
2230 result = InitializeKeepAlive(myStackMode);
2235 if(result != OC_STACK_OK)
2237 OIC_LOG(ERROR, TAG, "Stack initialization error");
2238 deleteAllResources();
2240 stackState = OC_STACK_UNINITIALIZED;
2245 OCStackResult OCStop()
2247 OIC_LOG(INFO, TAG, "Entering OCStop");
2249 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2251 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2254 else if (stackState != OC_STACK_INITIALIZED)
2256 OIC_LOG(ERROR, TAG, "Stack not initialized");
2257 return OC_STACK_ERROR;
2260 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2262 #ifdef WITH_PRESENCE
2263 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2264 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2265 presenceResource.presenceTTL = 0;
2266 #endif // WITH_PRESENCE
2268 #ifdef ROUTING_GATEWAY
2269 if (OC_GATEWAY == myStackMode)
2276 TerminateKeepAlive(myStackMode);
2279 // Free memory dynamically allocated for resources
2280 deleteAllResources();
2282 DeletePlatformInfo();
2284 // Remove all observers
2285 DeleteObserverList();
2286 // Remove all the client callbacks
2287 DeleteClientCBList();
2289 // De-init the SRM Policy Engine
2290 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2291 SRMDeInitPolicyEngine();
2294 stackState = OC_STACK_UNINITIALIZED;
2298 OCStackResult OCStartMulticastServer()
2300 if(stackState != OC_STACK_INITIALIZED)
2302 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2303 return OC_STACK_ERROR;
2305 CAResult_t ret = CAStartListeningServer();
2306 if (CA_STATUS_OK != ret)
2308 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2309 return OC_STACK_ERROR;
2314 OCStackResult OCStopMulticastServer()
2316 CAResult_t ret = CAStopListeningServer();
2317 if (CA_STATUS_OK != ret)
2319 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2320 return OC_STACK_ERROR;
2325 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2330 return CA_MSG_CONFIRM;
2335 return CA_MSG_NONCONFIRM;
2340 * A request uri consists of the following components in order:
2343 * CoAP over UDP prefix "coap://"
2344 * CoAP over TCP prefix "coap+tcp://"
2346 * IPv6 address "[1234::5678]"
2347 * IPv4 address "192.168.1.1"
2348 * optional port ":5683"
2349 * resource uri "/oc/core..."
2351 * for PRESENCE requests, extract resource type.
2353 static OCStackResult ParseRequestUri(const char *fullUri,
2354 OCTransportAdapter adapter,
2355 OCTransportFlags flags,
2356 OCDevAddr **devAddr,
2358 char **resourceType)
2360 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2362 OCStackResult result = OC_STACK_OK;
2363 OCDevAddr *da = NULL;
2367 // provide defaults for all returned values
2374 *resourceUri = NULL;
2378 *resourceType = NULL;
2381 // delimit url prefix, if any
2382 const char *start = fullUri;
2383 char *slash2 = strstr(start, "//");
2388 char *slash = strchr(start, '/');
2391 return OC_STACK_INVALID_URI;
2394 // process url scheme
2395 size_t prefixLen = slash2 - fullUri;
2399 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2405 // TODO: this logic should come in with unit tests exercising the various strings
2406 // processs url prefix, if any
2407 size_t urlLen = slash - start;
2411 if (urlLen && devAddr)
2412 { // construct OCDevAddr
2413 if (start[0] == '[')
2415 char *close = strchr(++start, ']');
2416 if (!close || close > slash)
2418 return OC_STACK_INVALID_URI;
2421 if (close[1] == ':')
2428 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2432 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2434 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2438 char *dot = strchr(start, '.');
2439 if (dot && dot < slash)
2441 colon = strchr(start, ':');
2442 end = (colon && colon < slash) ? colon : slash;
2447 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2451 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2453 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2461 if (len >= sizeof(da->addr))
2463 return OC_STACK_INVALID_URI;
2465 // collect port, if any
2466 if (colon && colon < slash)
2468 for (colon++; colon < slash; colon++)
2471 if (c < '0' || c > '9')
2473 return OC_STACK_INVALID_URI;
2475 port = 10 * port + c - '0';
2480 if (len >= sizeof(da->addr))
2482 return OC_STACK_INVALID_URI;
2485 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2488 return OC_STACK_NO_MEMORY;
2490 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2492 da->adapter = adapter;
2494 if (!strncmp(fullUri, "coaps:", 6))
2496 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2501 // process resource uri, if any
2503 { // request uri and query
2504 size_t ulen = strlen(slash); // resource uri length
2505 size_t tlen = 0; // resource type length
2508 static const char strPresence[] = "/oic/ad?rt=";
2509 static const size_t lenPresence = sizeof(strPresence) - 1;
2510 if (!strncmp(slash, strPresence, lenPresence))
2512 type = slash + lenPresence;
2513 tlen = ulen - lenPresence;
2518 *resourceUri = (char *)OICMalloc(ulen + 1);
2521 result = OC_STACK_NO_MEMORY;
2524 strcpy(*resourceUri, slash);
2527 if (type && resourceType)
2529 *resourceType = (char *)OICMalloc(tlen + 1);
2532 result = OC_STACK_NO_MEMORY;
2536 OICStrcpy(*resourceType, (tlen+1), type);
2543 // free all returned values
2550 OICFree(*resourceUri);
2554 OICFree(*resourceType);
2559 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2560 char *resourceUri, char **requestUri)
2562 char uri[CA_MAX_URI_LENGTH];
2564 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2566 *requestUri = OICStrdup(uri);
2569 return OC_STACK_NO_MEMORY;
2576 * Discover or Perform requests on a specified resource
2578 OCStackResult OCDoResource(OCDoHandle *handle,
2580 const char *requestUri,
2581 const OCDevAddr *destination,
2583 OCConnectivityType connectivityType,
2584 OCQualityOfService qos,
2585 OCCallbackData *cbData,
2586 OCHeaderOption *options,
2589 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2591 // Validate input parameters
2592 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2593 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2594 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2596 OCStackResult result = OC_STACK_ERROR;
2597 CAResult_t caResult;
2598 CAToken_t token = NULL;
2599 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2600 ClientCB *clientCB = NULL;
2601 OCDoHandle resHandle = NULL;
2602 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2603 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2605 OCTransportAdapter adapter;
2606 OCTransportFlags flags;
2607 // the request contents are put here
2608 CARequestInfo_t requestInfo = {.method = CA_GET};
2609 // requestUri will be parsed into the following three variables
2610 OCDevAddr *devAddr = NULL;
2611 char *resourceUri = NULL;
2612 char *resourceType = NULL;
2615 * Support original behavior with address on resourceUri argument.
2617 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2618 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2620 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2622 if (result != OC_STACK_OK)
2624 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2631 case OC_REST_OBSERVE:
2632 case OC_REST_OBSERVE_ALL:
2633 case OC_REST_CANCEL_OBSERVE:
2634 requestInfo.method = CA_GET;
2637 requestInfo.method = CA_PUT;
2640 requestInfo.method = CA_POST;
2642 case OC_REST_DELETE:
2643 requestInfo.method = CA_DELETE;
2645 case OC_REST_DISCOVER:
2647 if (destination || devAddr)
2649 requestInfo.isMulticast = false;
2653 tmpDevAddr.adapter = adapter;
2654 tmpDevAddr.flags = flags;
2655 destination = &tmpDevAddr;
2656 requestInfo.isMulticast = true;
2658 // CA_DISCOVER will become GET and isMulticast
2659 requestInfo.method = CA_GET;
2661 #ifdef WITH_PRESENCE
2662 case OC_REST_PRESENCE:
2663 // Replacing method type with GET because "presence"
2664 // is a stack layer only implementation.
2665 requestInfo.method = CA_GET;
2669 result = OC_STACK_INVALID_METHOD;
2673 if (!devAddr && !destination)
2675 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2676 result = OC_STACK_INVALID_PARAM;
2680 /* If not original behavior, use destination argument */
2681 if (destination && !devAddr)
2683 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2686 result = OC_STACK_NO_MEMORY;
2689 *devAddr = *destination;
2692 resHandle = GenerateInvocationHandle();
2695 result = OC_STACK_NO_MEMORY;
2699 caResult = CAGenerateToken(&token, tokenLength);
2700 if (caResult != CA_STATUS_OK)
2702 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2703 result= OC_STACK_ERROR;
2707 // fill in request data
2708 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2709 requestInfo.info.token = token;
2710 requestInfo.info.tokenLength = tokenLength;
2711 requestInfo.info.resourceUri = resourceUri;
2713 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2715 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2716 options, numOptions, OC_OBSERVE_REGISTER);
2717 if (result != OC_STACK_OK)
2721 requestInfo.info.numOptions = numOptions + 1;
2725 requestInfo.info.numOptions = numOptions;
2726 requestInfo.info.options =
2727 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2728 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2729 numOptions * sizeof(CAHeaderOption_t));
2732 CopyDevAddrToEndpoint(devAddr, &endpoint);
2737 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2740 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2743 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2747 requestInfo.info.payload = NULL;
2748 requestInfo.info.payloadSize = 0;
2749 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2752 // prepare for response
2753 #ifdef WITH_PRESENCE
2754 if (method == OC_REST_PRESENCE)
2756 char *presenceUri = NULL;
2757 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2758 if (OC_STACK_OK != result)
2763 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2764 // Presence notification will form a canonical uri to
2765 // look for callbacks into the application.
2766 resourceUri = presenceUri;
2770 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2771 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2772 method, devAddr, resourceUri, resourceType, ttl);
2773 if (OC_STACK_OK != result)
2778 devAddr = NULL; // Client CB list entry now owns it
2779 resourceUri = NULL; // Client CB list entry now owns it
2780 resourceType = NULL; // Client CB list entry now owns it
2783 result = OCSendRequest(&endpoint, &requestInfo);
2784 if (OC_STACK_OK != result)
2791 *handle = resHandle;
2795 if (result != OC_STACK_OK)
2797 OIC_LOG(ERROR, TAG, "OCDoResource error");
2798 FindAndDeleteClientCB(clientCB);
2799 CADestroyToken(token);
2807 // This is the owner of the payload object, so we free it
2808 OCPayloadDestroy(payload);
2809 OICFree(requestInfo.info.payload);
2811 OICFree(resourceUri);
2812 OICFree(resourceType);
2813 OICFree(requestInfo.info.options);
2817 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2821 * This ftn is implemented one of two ways in the case of observation:
2823 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2824 * Remove the callback associated on client side.
2825 * When the next notification comes in from server,
2826 * reply with RESET message to server.
2827 * Keep in mind that the server will react to RESET only
2828 * if the last notification was sent as CON
2830 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2831 * and it is associated with an observe request
2832 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2833 * Send CON Observe request to server with
2834 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2835 * Remove the callback associated on client side.
2837 OCStackResult ret = OC_STACK_OK;
2838 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2839 CARequestInfo_t requestInfo = {.method = CA_GET};
2843 return OC_STACK_INVALID_PARAM;
2846 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2849 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2850 return OC_STACK_ERROR;
2853 switch (clientCB->method)
2855 case OC_REST_OBSERVE:
2856 case OC_REST_OBSERVE_ALL:
2858 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2860 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2862 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2864 FindAndDeleteClientCB(clientCB);
2868 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2870 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2871 requestInfo.info.token = clientCB->token;
2872 requestInfo.info.tokenLength = clientCB->tokenLength;
2874 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2875 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2877 return OC_STACK_ERROR;
2879 requestInfo.info.numOptions = numOptions + 1;
2880 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2883 ret = OCSendRequest(&endpoint, &requestInfo);
2885 if (requestInfo.info.options)
2887 OICFree (requestInfo.info.options);
2889 if (requestInfo.info.resourceUri)
2891 OICFree (requestInfo.info.resourceUri);
2896 case OC_REST_DISCOVER:
2897 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2898 clientCB->requestUri);
2899 FindAndDeleteClientCB(clientCB);
2902 #ifdef WITH_PRESENCE
2903 case OC_REST_PRESENCE:
2904 FindAndDeleteClientCB(clientCB);
2909 ret = OC_STACK_INVALID_METHOD;
2917 * @brief Register Persistent storage callback.
2918 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2920 * OC_STACK_OK - No errors; Success
2921 * OC_STACK_INVALID_PARAM - Invalid parameter
2923 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2925 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2926 if(!persistentStorageHandler)
2928 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2929 return OC_STACK_INVALID_PARAM;
2933 if( !persistentStorageHandler->open ||
2934 !persistentStorageHandler->close ||
2935 !persistentStorageHandler->read ||
2936 !persistentStorageHandler->unlink ||
2937 !persistentStorageHandler->write)
2939 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2940 return OC_STACK_INVALID_PARAM;
2943 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2946 #ifdef WITH_PRESENCE
2948 OCStackResult OCProcessPresence()
2950 OCStackResult result = OC_STACK_OK;
2952 // the following line floods the log with messages that are irrelevant
2953 // to most purposes. Uncomment as needed.
2954 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2955 ClientCB* cbNode = NULL;
2956 OCClientResponse clientResponse;
2957 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2959 LL_FOREACH(cbList, cbNode)
2961 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2966 uint32_t now = GetTicks(0);
2967 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2968 cbNode->presence->TTLlevel);
2969 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2971 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2976 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2978 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2979 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2981 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2983 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2985 clientResponse.sequenceNumber = 0;
2986 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2987 clientResponse.devAddr = *cbNode->devAddr;
2988 FixUpClientResponse(&clientResponse);
2989 clientResponse.payload = NULL;
2991 // Increment the TTLLevel (going to a next state), so we don't keep
2992 // sending presence notification to client.
2993 cbNode->presence->TTLlevel++;
2994 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2995 cbNode->presence->TTLlevel);
2997 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2998 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3000 FindAndDeleteClientCB(cbNode);
3004 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3009 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3010 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3011 CARequestInfo_t requestInfo = {.method = CA_GET};
3013 OIC_LOG(DEBUG, TAG, "time to test server presence");
3015 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3017 requestData.type = CA_MSG_NONCONFIRM;
3018 requestData.token = cbNode->token;
3019 requestData.tokenLength = cbNode->tokenLength;
3020 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3021 requestInfo.method = CA_GET;
3022 requestInfo.info = requestData;
3024 result = OCSendRequest(&endpoint, &requestInfo);
3025 if (OC_STACK_OK != result)
3030 cbNode->presence->TTLlevel++;
3031 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3034 if (result != OC_STACK_OK)
3036 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3041 #endif // WITH_PRESENCE
3043 OCStackResult OCProcess()
3045 #ifdef WITH_PRESENCE
3046 OCProcessPresence();
3048 CAHandleRequestResponse();
3050 #ifdef ROUTING_GATEWAY
3060 #ifdef WITH_PRESENCE
3061 OCStackResult OCStartPresence(const uint32_t ttl)
3063 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3064 OCChangeResourceProperty(
3065 &(((OCResource *)presenceResource.handle)->resourceProperties),
3068 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3070 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3071 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3075 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3076 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3080 presenceResource.presenceTTL = ttl;
3082 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3084 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3086 presenceState = OC_PRESENCE_INITIALIZED;
3088 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3090 CAToken_t caToken = NULL;
3091 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3092 if (caResult != CA_STATUS_OK)
3094 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3095 CADestroyToken(caToken);
3096 return OC_STACK_ERROR;
3099 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3100 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3101 CADestroyToken(caToken);
3104 // Each time OCStartPresence is called
3105 // a different random 32-bit integer number is used
3106 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3108 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3109 OC_PRESENCE_TRIGGER_CREATE);
3112 OCStackResult OCStopPresence()
3114 OCStackResult result = OC_STACK_ERROR;
3116 if(presenceResource.handle)
3118 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3120 // make resource inactive
3121 result = OCChangeResourceProperty(
3122 &(((OCResource *) presenceResource.handle)->resourceProperties),
3126 if(result != OC_STACK_OK)
3129 "Changing the presence resource properties to ACTIVE not successful");
3133 return SendStopNotification();
3137 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3138 void* callbackParameter)
3140 defaultDeviceHandler = entityHandler;
3141 defaultDeviceHandlerCallbackParameter = callbackParameter;
3146 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3148 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3150 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3152 if (validatePlatformInfo(platformInfo))
3154 return SavePlatformInfo(platformInfo);
3158 return OC_STACK_INVALID_PARAM;
3163 return OC_STACK_ERROR;
3167 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3169 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3171 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3173 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3174 return OC_STACK_INVALID_PARAM;
3177 if (deviceInfo.types)
3179 OCStringLL *type = deviceInfo.types;
3180 OCResource *resource = findResource((OCResource *) deviceResource);
3183 return OC_STACK_INVALID_PARAM;
3188 OCBindResourceTypeToResource(deviceResource, type->value);
3192 return SaveDeviceInfo(deviceInfo);
3195 OCStackResult OCCreateResource(OCResourceHandle *handle,
3196 const char *resourceTypeName,
3197 const char *resourceInterfaceName,
3198 const char *uri, OCEntityHandler entityHandler,
3199 void* callbackParam,
3200 uint8_t resourceProperties)
3203 OCResource *pointer = NULL;
3204 OCStackResult result = OC_STACK_ERROR;
3206 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3208 if(myStackMode == OC_CLIENT)
3210 return OC_STACK_INVALID_PARAM;
3212 // Validate parameters
3213 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3215 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3216 return OC_STACK_INVALID_URI;
3218 // Is it presented during resource discovery?
3219 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3221 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3222 return OC_STACK_INVALID_PARAM;
3225 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3227 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3231 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3233 // Make sure resourceProperties bitmask has allowed properties specified
3234 if (resourceProperties
3235 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3236 OC_EXPLICIT_DISCOVERABLE
3245 OIC_LOG(ERROR, TAG, "Invalid property");
3246 return OC_STACK_INVALID_PARAM;
3249 // If the headResource is NULL, then no resources have been created...
3250 pointer = headResource;
3253 // At least one resources is in the resource list, so we need to search for
3254 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3257 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3259 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3260 return OC_STACK_INVALID_PARAM;
3262 pointer = pointer->next;
3265 // Create the pointer and insert it into the resource list
3266 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3269 result = OC_STACK_NO_MEMORY;
3272 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3274 insertResource(pointer);
3277 pointer->uri = OICStrdup(uri);
3280 result = OC_STACK_NO_MEMORY;
3284 // Set properties. Set OC_ACTIVE
3285 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3288 // Add the resourcetype to the resource
3289 result = BindResourceTypeToResource(pointer, resourceTypeName);
3290 if (result != OC_STACK_OK)
3292 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3296 // Add the resourceinterface to the resource
3297 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3298 if (result != OC_STACK_OK)
3300 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3304 // If an entity handler has been passed, attach it to the newly created
3305 // resource. Otherwise, set the default entity handler.
3308 pointer->entityHandler = entityHandler;
3309 pointer->entityHandlerCallbackParam = callbackParam;
3313 pointer->entityHandler = defaultResourceEHandler;
3314 pointer->entityHandlerCallbackParam = NULL;
3317 // Initialize a pointer indicating child resources in case of collection
3318 pointer->rsrcChildResourcesHead = NULL;
3321 result = OC_STACK_OK;
3323 #ifdef WITH_PRESENCE
3324 if (presenceResource.handle)
3326 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3327 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3331 if (result != OC_STACK_OK)
3333 // Deep delete of resource and other dynamic elements that it contains
3334 deleteResource(pointer);
3339 OCStackResult OCBindResource(
3340 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3342 OCResource *resource = NULL;
3343 OCChildResource *tempChildResource = NULL;
3344 OCChildResource *newChildResource = NULL;
3346 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3348 // Validate parameters
3349 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3350 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3351 // Container cannot contain itself
3352 if (collectionHandle == resourceHandle)
3354 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3355 return OC_STACK_INVALID_PARAM;
3358 // Use the handle to find the resource in the resource linked list
3359 resource = findResource((OCResource *) collectionHandle);
3362 OIC_LOG(ERROR, TAG, "Collection handle not found");
3363 return OC_STACK_INVALID_PARAM;
3366 // Look for an open slot to add add the child resource.
3367 // If found, add it and return success
3369 tempChildResource = resource->rsrcChildResourcesHead;
3371 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3373 // TODO: what if one of child resource was deregistered without unbinding?
3374 tempChildResource = tempChildResource->next;
3377 // Do memory allocation for child resource
3378 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3379 if(!newChildResource)
3381 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3382 return OC_STACK_ERROR;
3385 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3386 newChildResource->next = NULL;
3388 if(!resource->rsrcChildResourcesHead)
3390 resource->rsrcChildResourcesHead = newChildResource;
3393 tempChildResource->next = newChildResource;
3396 OIC_LOG(INFO, TAG, "resource bound");
3398 #ifdef WITH_PRESENCE
3399 if (presenceResource.handle)
3401 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3402 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3403 OC_PRESENCE_TRIGGER_CHANGE);
3410 OCStackResult OCUnBindResource(
3411 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3413 OCResource *resource = NULL;
3414 OCChildResource *tempChildResource = NULL;
3415 OCChildResource *tempLastChildResource = NULL;
3417 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3419 // Validate parameters
3420 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3421 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3422 // Container cannot contain itself
3423 if (collectionHandle == resourceHandle)
3425 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3426 return OC_STACK_INVALID_PARAM;
3429 // Use the handle to find the resource in the resource linked list
3430 resource = findResource((OCResource *) collectionHandle);
3433 OIC_LOG(ERROR, TAG, "Collection handle not found");
3434 return OC_STACK_INVALID_PARAM;
3437 // Look for an open slot to add add the child resource.
3438 // If found, add it and return success
3439 if(!resource->rsrcChildResourcesHead)
3441 OIC_LOG(INFO, TAG, "resource not found in collection");
3443 // Unable to add resourceHandle, so return error
3444 return OC_STACK_ERROR;
3448 tempChildResource = resource->rsrcChildResourcesHead;
3450 while (tempChildResource)
3452 if(tempChildResource->rsrcResource == resourceHandle)
3454 // if resource going to be unbinded is the head one.
3455 if( tempChildResource == resource->rsrcChildResourcesHead )
3457 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3458 OICFree(resource->rsrcChildResourcesHead);
3459 resource->rsrcChildResourcesHead = temp;
3464 OCChildResource *temp = tempChildResource->next;
3465 OICFree(tempChildResource);
3466 tempLastChildResource->next = temp;
3470 OIC_LOG(INFO, TAG, "resource unbound");
3472 // Send notification when resource is unbounded successfully.
3473 #ifdef WITH_PRESENCE
3474 if (presenceResource.handle)
3476 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3477 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3478 OC_PRESENCE_TRIGGER_CHANGE);
3481 tempChildResource = NULL;
3482 tempLastChildResource = NULL;
3488 tempLastChildResource = tempChildResource;
3489 tempChildResource = tempChildResource->next;
3492 OIC_LOG(INFO, TAG, "resource not found in collection");
3494 tempChildResource = NULL;
3495 tempLastChildResource = NULL;
3497 // Unable to add resourceHandle, so return error
3498 return OC_STACK_ERROR;
3501 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3503 if (!resourceItemName)
3507 // Per RFC 6690 only registered values must follow the first rule below.
3508 // At this point in time the only values registered begin with "core", and
3509 // all other values are specified as opaque strings where multiple values
3510 // are separated by a space.
3511 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3513 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3515 if (resourceItemName[index] != '.'
3516 && resourceItemName[index] != '-'
3517 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3518 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3526 for (size_t index = 0; resourceItemName[index]; ++index)
3528 if (resourceItemName[index] == ' '
3529 || resourceItemName[index] == '\t'
3530 || resourceItemName[index] == '\r'
3531 || resourceItemName[index] == '\n')
3541 OCStackResult BindResourceTypeToResource(OCResource* resource,
3542 const char *resourceTypeName)
3544 OCResourceType *pointer = NULL;
3546 OCStackResult result = OC_STACK_ERROR;
3548 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3550 if (!ValidateResourceTypeInterface(resourceTypeName))
3552 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3553 return OC_STACK_INVALID_PARAM;
3556 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3559 result = OC_STACK_NO_MEMORY;
3563 str = OICStrdup(resourceTypeName);
3566 result = OC_STACK_NO_MEMORY;
3569 pointer->resourcetypename = str;
3570 pointer->next = NULL;
3572 insertResourceType(resource, pointer);
3573 result = OC_STACK_OK;
3576 if (result != OC_STACK_OK)
3585 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3586 const char *resourceInterfaceName)
3588 OCResourceInterface *pointer = NULL;
3590 OCStackResult result = OC_STACK_ERROR;
3592 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3594 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3596 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3597 return OC_STACK_INVALID_PARAM;
3600 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3602 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3605 result = OC_STACK_NO_MEMORY;
3609 str = OICStrdup(resourceInterfaceName);
3612 result = OC_STACK_NO_MEMORY;
3615 pointer->name = str;
3617 // Bind the resourceinterface to the resource
3618 insertResourceInterface(resource, pointer);
3620 result = OC_STACK_OK;
3623 if (result != OC_STACK_OK)
3632 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3633 const char *resourceTypeName)
3636 OCStackResult result = OC_STACK_ERROR;
3637 OCResource *resource = NULL;
3639 resource = findResource((OCResource *) handle);
3642 OIC_LOG(ERROR, TAG, "Resource not found");
3643 return OC_STACK_ERROR;
3646 result = BindResourceTypeToResource(resource, resourceTypeName);
3648 #ifdef WITH_PRESENCE
3649 if(presenceResource.handle)
3651 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3652 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3659 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3660 const char *resourceInterfaceName)
3663 OCStackResult result = OC_STACK_ERROR;
3664 OCResource *resource = NULL;
3666 resource = findResource((OCResource *) handle);
3669 OIC_LOG(ERROR, TAG, "Resource not found");
3670 return OC_STACK_ERROR;
3673 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3675 #ifdef WITH_PRESENCE
3676 if (presenceResource.handle)
3678 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3679 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3686 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3688 OCResource *pointer = headResource;
3690 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3694 *numResources = *numResources + 1;
3695 pointer = pointer->next;
3700 OCResourceHandle OCGetResourceHandle(uint8_t index)
3702 OCResource *pointer = headResource;
3704 for( uint8_t i = 0; i < index && pointer; ++i)
3706 pointer = pointer->next;
3708 return (OCResourceHandle) pointer;
3711 OCStackResult OCDeleteResource(OCResourceHandle handle)
3715 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3716 return OC_STACK_INVALID_PARAM;
3719 OCResource *resource = findResource((OCResource *) handle);
3720 if (resource == NULL)
3722 OIC_LOG(ERROR, TAG, "Resource not found");
3723 return OC_STACK_NO_RESOURCE;
3726 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3728 OIC_LOG(ERROR, TAG, "Error deleting resource");
3729 return OC_STACK_ERROR;
3735 const char *OCGetResourceUri(OCResourceHandle handle)
3737 OCResource *resource = NULL;
3739 resource = findResource((OCResource *) handle);
3742 return resource->uri;
3744 return (const char *) NULL;
3747 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3749 OCResource *resource = NULL;
3751 resource = findResource((OCResource *) handle);
3754 return resource->resourceProperties;
3756 return (OCResourceProperty)-1;
3759 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3760 uint8_t *numResourceTypes)
3762 OCResource *resource = NULL;
3763 OCResourceType *pointer = NULL;
3765 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3766 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3768 *numResourceTypes = 0;
3770 resource = findResource((OCResource *) handle);
3773 pointer = resource->rsrcType;
3776 *numResourceTypes = *numResourceTypes + 1;
3777 pointer = pointer->next;
3783 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3785 OCResourceType *resourceType = NULL;
3787 resourceType = findResourceTypeAtIndex(handle, index);
3790 return resourceType->resourcetypename;
3792 return (const char *) NULL;
3795 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3796 uint8_t *numResourceInterfaces)
3798 OCResourceInterface *pointer = NULL;
3799 OCResource *resource = NULL;
3801 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3802 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3804 *numResourceInterfaces = 0;
3805 resource = findResource((OCResource *) handle);
3808 pointer = resource->rsrcInterface;
3811 *numResourceInterfaces = *numResourceInterfaces + 1;
3812 pointer = pointer->next;
3818 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3820 OCResourceInterface *resourceInterface = NULL;
3822 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3823 if (resourceInterface)
3825 return resourceInterface->name;
3827 return (const char *) NULL;
3830 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3833 OCResource *resource = NULL;
3834 OCChildResource *tempChildResource = NULL;
3837 resource = findResource((OCResource *) collectionHandle);
3843 tempChildResource = resource->rsrcChildResourcesHead;
3845 while(tempChildResource)
3849 return tempChildResource->rsrcResource;
3852 tempChildResource = tempChildResource->next;
3855 // In this case, the number of resource handles in the collection exceeds the index
3856 tempChildResource = NULL;
3860 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3861 OCEntityHandler entityHandler,
3862 void* callbackParam)
3864 OCResource *resource = NULL;
3866 // Validate parameters
3867 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3869 // Use the handle to find the resource in the resource linked list
3870 resource = findResource((OCResource *)handle);
3873 OIC_LOG(ERROR, TAG, "Resource not found");
3874 return OC_STACK_ERROR;
3878 resource->entityHandler = entityHandler;
3879 resource->entityHandlerCallbackParam = callbackParam;
3881 #ifdef WITH_PRESENCE
3882 if (presenceResource.handle)
3884 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3885 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3892 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3894 OCResource *resource = NULL;
3896 resource = findResource((OCResource *)handle);
3899 OIC_LOG(ERROR, TAG, "Resource not found");
3904 return resource->entityHandler;
3907 void incrementSequenceNumber(OCResource * resPtr)
3909 // Increment the sequence number
3910 resPtr->sequenceNum += 1;
3911 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3913 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3918 #ifdef WITH_PRESENCE
3919 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3920 OCPresenceTrigger trigger)
3922 OCResource *resPtr = NULL;
3923 OCStackResult result = OC_STACK_ERROR;
3924 OCMethod method = OC_REST_PRESENCE;
3925 uint32_t maxAge = 0;
3926 resPtr = findResource((OCResource *) presenceResource.handle);
3929 return OC_STACK_NO_RESOURCE;
3932 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3934 maxAge = presenceResource.presenceTTL;
3936 result = SendAllObserverNotification(method, resPtr, maxAge,
3937 trigger, resourceType, OC_LOW_QOS);
3943 OCStackResult SendStopNotification()
3945 OCResource *resPtr = NULL;
3946 OCStackResult result = OC_STACK_ERROR;
3947 OCMethod method = OC_REST_PRESENCE;
3948 resPtr = findResource((OCResource *) presenceResource.handle);
3951 return OC_STACK_NO_RESOURCE;
3954 // maxAge is 0. ResourceType is NULL.
3955 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3961 #endif // WITH_PRESENCE
3962 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3964 OCResource *resPtr = NULL;
3965 OCStackResult result = OC_STACK_ERROR;
3966 OCMethod method = OC_REST_NOMETHOD;
3967 uint32_t maxAge = 0;
3969 OIC_LOG(INFO, TAG, "Notifying all observers");
3970 #ifdef WITH_PRESENCE
3971 if(handle == presenceResource.handle)
3975 #endif // WITH_PRESENCE
3976 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3978 // Verify that the resource exists
3979 resPtr = findResource ((OCResource *) handle);
3982 return OC_STACK_NO_RESOURCE;
3986 //only increment in the case of regular observing (not presence)
3987 incrementSequenceNumber(resPtr);
3988 method = OC_REST_OBSERVE;
3989 maxAge = MAX_OBSERVE_AGE;
3990 #ifdef WITH_PRESENCE
3991 result = SendAllObserverNotification (method, resPtr, maxAge,
3992 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3994 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4001 OCNotifyListOfObservers (OCResourceHandle handle,
4002 OCObservationId *obsIdList,
4003 uint8_t numberOfIds,
4004 const OCRepPayload *payload,
4005 OCQualityOfService qos)
4007 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4009 OCResource *resPtr = NULL;
4010 //TODO: we should allow the server to define this
4011 uint32_t maxAge = MAX_OBSERVE_AGE;
4013 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4014 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4015 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4017 resPtr = findResource ((OCResource *) handle);
4018 if (NULL == resPtr || myStackMode == OC_CLIENT)
4020 return OC_STACK_NO_RESOURCE;
4024 incrementSequenceNumber(resPtr);
4026 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4027 payload, maxAge, qos));
4030 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4032 OCStackResult result = OC_STACK_ERROR;
4033 OCServerRequest *serverRequest = NULL;
4035 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4037 // Validate input parameters
4038 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4039 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4042 // Get pointer to request info
4043 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4046 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4047 result = serverRequest->ehResponseHandler(ehResponse);
4053 //#ifdef DIRECT_PAIRING
4054 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4056 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4057 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4059 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4063 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4066 const OCDPDev_t* OCGetDirectPairedDevices()
4068 return (const OCDPDev_t*)DPGetPairedDevices();
4071 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4072 OCDirectPairingCB resultCallback)
4074 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4075 if(NULL == peer || NULL == pinNumber)
4077 OIC_LOG(ERROR, TAG, "Invalid parameters");
4078 return OC_STACK_INVALID_PARAM;
4080 if (NULL == resultCallback)
4082 OIC_LOG(ERROR, TAG, "Invalid callback");
4083 return OC_STACK_INVALID_CALLBACK;
4086 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4087 pinNumber, (OCDirectPairingResultCB)resultCallback);
4089 //#endif // DIRECT_PAIRING
4091 //-----------------------------------------------------------------------------
4092 // Private internal function definitions
4093 //-----------------------------------------------------------------------------
4094 static OCDoHandle GenerateInvocationHandle()
4096 OCDoHandle handle = NULL;
4097 // Generate token here, it will be deleted when the transaction is deleted
4098 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4101 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4107 #ifdef WITH_PRESENCE
4108 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4109 OCResourceProperty resourceProperties, uint8_t enable)
4113 return OC_STACK_INVALID_PARAM;
4115 if (resourceProperties
4116 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4118 OIC_LOG(ERROR, TAG, "Invalid property");
4119 return OC_STACK_INVALID_PARAM;
4123 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4127 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4133 OCStackResult initResources()
4135 OCStackResult result = OC_STACK_OK;
4137 headResource = NULL;
4138 tailResource = NULL;
4139 // Init Virtual Resources
4140 #ifdef WITH_PRESENCE
4141 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4143 result = OCCreateResource(&presenceResource.handle,
4144 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4146 OC_RSRVD_PRESENCE_URI,
4150 //make resource inactive
4151 result = OCChangeResourceProperty(
4152 &(((OCResource *) presenceResource.handle)->resourceProperties),
4155 #ifndef WITH_ARDUINO
4156 if (result == OC_STACK_OK)
4158 result = SRMInitSecureResources();
4162 if(result == OC_STACK_OK)
4164 CreateResetProfile();
4165 result = OCCreateResource(&deviceResource,
4166 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4167 OC_RSRVD_INTERFACE_DEFAULT,
4168 OC_RSRVD_DEVICE_URI,
4172 if(result == OC_STACK_OK)
4174 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4175 OC_RSRVD_INTERFACE_READ);
4179 if(result == OC_STACK_OK)
4181 result = OCCreateResource(&platformResource,
4182 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4183 OC_RSRVD_INTERFACE_DEFAULT,
4184 OC_RSRVD_PLATFORM_URI,
4188 if(result == OC_STACK_OK)
4190 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4191 OC_RSRVD_INTERFACE_READ);
4198 void insertResource(OCResource *resource)
4202 headResource = resource;
4203 tailResource = resource;
4207 tailResource->next = resource;
4208 tailResource = resource;
4210 resource->next = NULL;
4213 OCResource *findResource(OCResource *resource)
4215 OCResource *pointer = headResource;
4219 if (pointer == resource)
4223 pointer = pointer->next;
4228 void deleteAllResources()
4230 OCResource *pointer = headResource;
4231 OCResource *temp = NULL;
4235 temp = pointer->next;
4236 #ifdef WITH_PRESENCE
4237 if (pointer != (OCResource *) presenceResource.handle)
4239 #endif // WITH_PRESENCE
4240 deleteResource(pointer);
4241 #ifdef WITH_PRESENCE
4243 #endif // WITH_PRESENCE
4246 memset(&platformResource, 0, sizeof(platformResource));
4247 memset(&deviceResource, 0, sizeof(deviceResource));
4249 SRMDeInitSecureResources();
4251 #ifdef WITH_PRESENCE
4252 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4253 // presence notification attributed to their deletion to be processed.
4254 deleteResource((OCResource *) presenceResource.handle);
4255 memset(&presenceResource, 0, sizeof(presenceResource));
4256 #endif // WITH_PRESENCE
4259 OCStackResult deleteResource(OCResource *resource)
4261 OCResource *prev = NULL;
4262 OCResource *temp = NULL;
4265 OIC_LOG(DEBUG,TAG,"resource is NULL");
4266 return OC_STACK_INVALID_PARAM;
4269 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4271 temp = headResource;
4274 if (temp == resource)
4276 // Invalidate all Resource Properties.
4277 resource->resourceProperties = (OCResourceProperty) 0;
4278 #ifdef WITH_PRESENCE
4279 if(resource != (OCResource *) presenceResource.handle)
4281 #endif // WITH_PRESENCE
4282 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4283 #ifdef WITH_PRESENCE
4286 if(presenceResource.handle)
4288 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4289 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4292 // Only resource in list.
4293 if (temp == headResource && temp == tailResource)
4295 headResource = NULL;
4296 tailResource = NULL;
4299 else if (temp == headResource)
4301 headResource = temp->next;
4304 else if (temp == tailResource)
4306 tailResource = prev;
4307 tailResource->next = NULL;
4311 prev->next = temp->next;
4314 deleteResourceElements(temp);
4325 return OC_STACK_ERROR;
4328 void deleteResourceElements(OCResource *resource)
4335 OICFree(resource->uri);
4336 deleteResourceType(resource->rsrcType);
4337 deleteResourceInterface(resource->rsrcInterface);
4340 void deleteResourceType(OCResourceType *resourceType)
4342 OCResourceType *pointer = resourceType;
4343 OCResourceType *next = NULL;
4347 next = pointer->next;
4348 OICFree(pointer->resourcetypename);
4354 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4356 OCResourceInterface *pointer = resourceInterface;
4357 OCResourceInterface *next = NULL;
4361 next = pointer->next;
4362 OICFree(pointer->name);
4368 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4370 OCResourceType *pointer = NULL;
4371 OCResourceType *previous = NULL;
4372 if (!resource || !resourceType)
4376 // resource type list is empty.
4377 else if (!resource->rsrcType)
4379 resource->rsrcType = resourceType;
4383 pointer = resource->rsrcType;
4387 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4389 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4390 OICFree(resourceType->resourcetypename);
4391 OICFree(resourceType);
4395 pointer = pointer->next;
4400 previous->next = resourceType;
4403 resourceType->next = NULL;
4405 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4408 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4410 OCResource *resource = NULL;
4411 OCResourceType *pointer = NULL;
4413 // Find the specified resource
4414 resource = findResource((OCResource *) handle);
4420 // Make sure a resource has a resourcetype
4421 if (!resource->rsrcType)
4426 // Iterate through the list
4427 pointer = resource->rsrcType;
4428 for(uint8_t i = 0; i< index && pointer; ++i)
4430 pointer = pointer->next;
4435 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4437 if(resourceTypeList && resourceTypeName)
4439 OCResourceType * rtPointer = resourceTypeList;
4440 while(resourceTypeName && rtPointer)
4442 if(rtPointer->resourcetypename &&
4443 strcmp(resourceTypeName, (const char *)
4444 (rtPointer->resourcetypename)) == 0)
4448 rtPointer = rtPointer->next;
4456 * Insert a new interface into interface linked list only if not already present.
4457 * If alredy present, 2nd arg is free'd.
4458 * Default interface will always be first if present.
4460 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4462 OCResourceInterface *pointer = NULL;
4463 OCResourceInterface *previous = NULL;
4465 newInterface->next = NULL;
4467 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4469 if (!*firstInterface)
4471 // If first interface is not oic.if.baseline, by default add it as first interface type.
4472 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4474 *firstInterface = newInterface;
4478 OCStackResult result = BindResourceInterfaceToResource(resource, OC_RSRVD_INTERFACE_DEFAULT);
4479 if (result != OC_STACK_OK)
4481 OICFree(newInterface->name);
4482 OICFree(newInterface);
4485 if (*firstInterface)
4487 (*firstInterface)->next = newInterface;
4491 // If once add oic.if.baseline, later too below code take care of freeing memory.
4492 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4494 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4496 OICFree(newInterface->name);
4497 OICFree(newInterface);
4500 // This code will not hit anymore, keeping
4503 newInterface->next = *firstInterface;
4504 *firstInterface = newInterface;
4509 pointer = *firstInterface;
4512 if (strcmp(newInterface->name, pointer->name) == 0)
4514 OICFree(newInterface->name);
4515 OICFree(newInterface);
4519 pointer = pointer->next;
4524 previous->next = newInterface;
4529 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4532 OCResource *resource = NULL;
4533 OCResourceInterface *pointer = NULL;
4535 // Find the specified resource
4536 resource = findResource((OCResource *) handle);
4542 // Make sure a resource has a resourceinterface
4543 if (!resource->rsrcInterface)
4548 // Iterate through the list
4549 pointer = resource->rsrcInterface;
4551 for (uint8_t i = 0; i < index && pointer; ++i)
4553 pointer = pointer->next;
4559 * This function splits the uri using the '?' delimiter.
4560 * "uriWithoutQuery" is the block of characters between the beginning
4561 * till the delimiter or '\0' which ever comes first.
4562 * "query" is whatever is to the right of the delimiter if present.
4563 * No delimiter sets the query to NULL.
4564 * If either are present, they will be malloc'ed into the params 2, 3.
4565 * The first param, *uri is left untouched.
4567 * NOTE: This function does not account for whitespace at the end of the uri NOR
4568 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4569 * part of the query.
4571 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4575 return OC_STACK_INVALID_URI;
4577 if(!query || !uriWithoutQuery)
4579 return OC_STACK_INVALID_PARAM;
4583 *uriWithoutQuery = NULL;
4585 size_t uriWithoutQueryLen = 0;
4586 size_t queryLen = 0;
4587 size_t uriLen = strlen(uri);
4589 char *pointerToDelimiter = strstr(uri, "?");
4591 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4592 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4594 if (uriWithoutQueryLen)
4596 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4597 if (!*uriWithoutQuery)
4601 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4605 *query = (char *) OICCalloc(queryLen + 1, 1);
4608 OICFree(*uriWithoutQuery);
4609 *uriWithoutQuery = NULL;
4612 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4618 return OC_STACK_NO_MEMORY;
4621 static const OicUuid_t* OCGetServerInstanceID(void)
4623 static bool generated = false;
4624 static OicUuid_t sid;
4630 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4632 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4639 const char* OCGetServerInstanceIDString(void)
4641 static bool generated = false;
4642 static char sidStr[UUID_STRING_SIZE];
4649 const OicUuid_t *sid = OCGetServerInstanceID();
4650 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4652 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4660 CAResult_t OCSelectNetwork()
4662 CAResult_t retResult = CA_STATUS_FAILED;
4663 CAResult_t caResult = CA_STATUS_OK;
4665 CATransportAdapter_t connTypes[] = {
4667 CA_ADAPTER_RFCOMM_BTEDR,
4668 CA_ADAPTER_GATT_BTLE,
4671 ,CA_ADAPTER_REMOTE_ACCESS
4678 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4680 for(int i = 0; i<numConnTypes; i++)
4682 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4683 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4685 caResult = CASelectNetwork(connTypes[i]);
4686 if(caResult == CA_STATUS_OK)
4688 retResult = CA_STATUS_OK;
4693 if(retResult != CA_STATUS_OK)
4695 return caResult; // Returns error of appropriate transport that failed fatally.
4701 OCStackResult CAResultToOCResult(CAResult_t caResult)
4707 case CA_STATUS_INVALID_PARAM:
4708 return OC_STACK_INVALID_PARAM;
4709 case CA_ADAPTER_NOT_ENABLED:
4710 return OC_STACK_ADAPTER_NOT_ENABLED;
4711 case CA_SERVER_STARTED_ALREADY:
4713 case CA_SERVER_NOT_STARTED:
4714 return OC_STACK_ERROR;
4715 case CA_DESTINATION_NOT_REACHABLE:
4716 return OC_STACK_COMM_ERROR;
4717 case CA_SOCKET_OPERATION_FAILED:
4718 return OC_STACK_COMM_ERROR;
4719 case CA_SEND_FAILED:
4720 return OC_STACK_COMM_ERROR;
4721 case CA_RECEIVE_FAILED:
4722 return OC_STACK_COMM_ERROR;
4723 case CA_MEMORY_ALLOC_FAILED:
4724 return OC_STACK_NO_MEMORY;
4725 case CA_REQUEST_TIMEOUT:
4726 return OC_STACK_TIMEOUT;
4727 case CA_DESTINATION_DISCONNECTED:
4728 return OC_STACK_COMM_ERROR;
4729 case CA_STATUS_FAILED:
4730 return OC_STACK_ERROR;
4731 case CA_NOT_SUPPORTED:
4732 return OC_STACK_NOTIMPL;
4734 return OC_STACK_ERROR;
4738 bool OCResultToSuccess(OCStackResult ocResult)
4743 case OC_STACK_RESOURCE_CREATED:
4744 case OC_STACK_RESOURCE_DELETED:
4745 case OC_STACK_CONTINUE:
4746 case OC_STACK_RESOURCE_CHANGED: