1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //-----------------------------------------------------------------------------
24 //-----------------------------------------------------------------------------
26 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
27 // causes header files to expose definitions
28 // corresponding to the POSIX.1-2001 base
29 // specification (excluding the XSI extension).
30 // For POSIX.1-2001 base specification,
31 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
32 #define _POSIX_C_SOURCE 200112L
33 #ifndef __STDC_FORMAT_MACROS
34 #define __STDC_FORMAT_MACROS
36 #ifndef __STDC_LIMIT_MACROS
37 #define __STDC_LIMIT_MACROS
44 #include "ocstackinternal.h"
45 #include "ocresourcehandler.h"
46 #include "occlientcb.h"
47 #include "ocobserve.h"
49 #include "oic_malloc.h"
50 #include "oic_string.h"
52 #include "ocserverrequest.h"
53 #include "secureresourcemanager.h"
54 #include "psinterface.h"
55 #include "doxmresource.h"
57 #include "cainterface.h"
58 #include "ocpayload.h"
59 #include "ocpayloadcbor.h"
60 #include "platform_features.h"
62 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
63 #include "routingutility.h"
64 #ifdef ROUTING_GATEWAY
65 #include "routingmanager.h"
70 #include "oickeepalive.h"
73 //#ifdef DIRECT_PAIRING
74 #include "directpairing.h"
77 #ifdef HAVE_ARDUINO_TIME_H
80 #ifdef HAVE_SYS_TIME_H
83 #include "coap_time.h"
87 #ifdef HAVE_ARPA_INET_H
88 #include <arpa/inet.h>
92 #define UINT32_MAX (0xFFFFFFFFUL)
95 //-----------------------------------------------------------------------------
97 //-----------------------------------------------------------------------------
100 OC_STACK_UNINITIALIZED = 0,
101 OC_STACK_INITIALIZED,
102 OC_STACK_UNINIT_IN_PROGRESS
108 OC_PRESENCE_UNINITIALIZED = 0,
109 OC_PRESENCE_INITIALIZED
113 //-----------------------------------------------------------------------------
115 //-----------------------------------------------------------------------------
116 static OCStackState stackState = OC_STACK_UNINITIALIZED;
118 OCResource *headResource = NULL;
119 static OCResource *tailResource = NULL;
120 static OCResourceHandle platformResource = {0};
121 static OCResourceHandle deviceResource = {0};
123 static OCResourceHandle brokerResource = {0};
127 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
128 static PresenceResource presenceResource = {0};
129 static uint8_t PresenceTimeOutSize = 0;
130 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
133 static OCMode myStackMode;
135 //TODO: revisit this design
136 static bool gRASetInfo = false;
138 OCDeviceEntityHandler defaultDeviceHandler;
139 void* defaultDeviceHandlerCallbackParameter = NULL;
140 static const char COAP_TCP[] = "coap+tcp:";
141 static const char CORESPEC[] = "core";
143 //-----------------------------------------------------------------------------
145 //-----------------------------------------------------------------------------
146 #define TAG "OIC_RI_STACK"
147 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
148 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
149 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
150 TAG, #arg " is NULL"); return (retVal); } }
151 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
152 TAG, #arg " is NULL"); return; } }
153 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
156 //TODO: we should allow the server to define this
157 #define MAX_OBSERVE_AGE (0x2FFFFUL)
159 #define MILLISECONDS_PER_SECOND (1000)
161 //-----------------------------------------------------------------------------
162 // Private internal function prototypes
163 //-----------------------------------------------------------------------------
166 * Generate handle of OCDoResource invocation for callback management.
168 * @return Generated OCDoResource handle.
170 static OCDoHandle GenerateInvocationHandle();
173 * Initialize resource data structures, variables, etc.
175 * @return ::OC_STACK_OK on success, some other value upon failure.
177 static OCStackResult initResources();
180 * Add a resource to the end of the linked list of resources.
182 * @param resource Resource to be added
184 static void insertResource(OCResource *resource);
187 * Find a resource in the linked list of resources.
189 * @param resource Resource to be found.
190 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
193 static OCResource *findResource(OCResource *resource);
196 * Insert a resource type into a resource's resource type linked list.
197 * If resource type already exists, it will not be inserted and the
198 * resourceType will be free'd.
199 * resourceType->next should be null to avoid memory leaks.
200 * Function returns silently for null args.
202 * @param resource Resource where resource type is to be inserted.
203 * @param resourceType Resource type to be inserted.
205 static void insertResourceType(OCResource *resource,
206 OCResourceType *resourceType);
209 * Get a resource type at the specified index within a resource.
211 * @param handle Handle of resource.
212 * @param index Index of resource type.
214 * @return Pointer to resource type if found, NULL otherwise.
216 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
220 * Insert a resource interface into a resource's resource interface linked list.
221 * If resource interface already exists, it will not be inserted and the
222 * resourceInterface will be free'd.
223 * resourceInterface->next should be null to avoid memory leaks.
225 * @param resource Resource where resource interface is to be inserted.
226 * @param resourceInterface Resource interface to be inserted.
228 static void insertResourceInterface(OCResource *resource,
229 OCResourceInterface *resourceInterface);
232 * Get a resource interface at the specified index within a resource.
234 * @param handle Handle of resource.
235 * @param index Index of resource interface.
237 * @return Pointer to resource interface if found, NULL otherwise.
239 static OCResourceInterface *findResourceInterfaceAtIndex(
240 OCResourceHandle handle, uint8_t index);
243 * Delete all of the dynamically allocated elements that were created for the resource type.
245 * @param resourceType Specified resource type.
247 static void deleteResourceType(OCResourceType *resourceType);
250 * Delete all of the dynamically allocated elements that were created for the resource interface.
252 * @param resourceInterface Specified resource interface.
254 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
257 * Delete all of the dynamically allocated elements that were created for the resource.
259 * @param resource Specified resource.
261 static void deleteResourceElements(OCResource *resource);
264 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
267 * @param handle Handle of resource to be deleted.
269 * @return ::OC_STACK_OK on success, some other value upon failure.
271 static OCStackResult deleteResource(OCResource *resource);
274 * Delete all of the resources in the resource list.
276 static void deleteAllResources();
279 * Increment resource sequence number. Handles rollover.
281 * @param resPtr Pointer to resource.
283 static void incrementSequenceNumber(OCResource * resPtr);
286 * Attempts to initialize every network interface that the CA Layer might have compiled in.
288 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
289 * return something other than @ref CA_STATUS_OK, then this function fails.
291 * @return ::CA_STATUS_OK on success, some other value upon failure.
293 static CAResult_t OCSelectNetwork();
296 * Get the CoAP ticks after the specified number of milli-seconds.
298 * @param afterMilliSeconds Milli-seconds.
302 static uint32_t GetTicks(uint32_t afterMilliSeconds);
305 * Convert CAResult_t to OCStackResult.
307 * @param caResult CAResult_t code.
308 * @return ::OC_STACK_OK on success, some other value upon failure.
310 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
313 * Convert CAResponseResult_t to OCStackResult.
315 * @param caCode CAResponseResult_t code.
316 * @return ::OC_STACK_OK on success, some other value upon failure.
318 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
321 * Convert OCStackResult to CAResponseResult_t.
323 * @param caCode OCStackResult code.
324 * @param method OCMethod method the return code replies to.
325 * @return ::CA_CONTENT on OK, some other value upon failure.
327 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
330 * Convert OCTransportFlags_t to CATransportModifiers_t.
332 * @param ocConType OCTransportFlags_t input.
333 * @return CATransportFlags
335 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
338 * Convert CATransportFlags_t to OCTransportModifiers_t.
340 * @param caConType CATransportFlags_t input.
341 * @return OCTransportFlags
343 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
346 * Handle response from presence request.
348 * @param endPoint CA remote endpoint.
349 * @param responseInfo CA response info.
350 * @return ::OC_STACK_OK on success, some other value upon failure.
352 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
353 const CAResponseInfo_t *responseInfo);
356 * This function will be called back by CA layer when a response is received.
358 * @param endPoint CA remote endpoint.
359 * @param responseInfo CA response info.
361 static void HandleCAResponses(const CAEndpoint_t* endPoint,
362 const CAResponseInfo_t* responseInfo);
365 * This function will be called back by CA layer when a request is received.
367 * @param endPoint CA remote endpoint.
368 * @param requestInfo CA request info.
370 static void HandleCARequests(const CAEndpoint_t* endPoint,
371 const CARequestInfo_t* requestInfo);
374 * Extract query from a URI.
376 * @param uri Full URI with query.
377 * @param query Pointer to string that will contain query.
378 * @param newURI Pointer to string that will contain URI.
379 * @return ::OC_STACK_OK on success, some other value upon failure.
381 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
384 * Finds a resource type in an OCResourceType link-list.
386 * @param resourceTypeList The link-list to be searched through.
387 * @param resourceTypeName The key to search for.
389 * @return Resource type that matches the key (ie. resourceTypeName) or
390 * NULL if there is either an invalid parameter or this function was unable to find the key.
392 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
393 const char * resourceTypeName);
396 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
397 * TTL will be set to maxAge.
399 * @param cbNode Callback Node for which presence ttl is to be reset.
400 * @param maxAge New value of ttl in seconds.
402 * @return ::OC_STACK_OK on success, some other value upon failure.
404 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
407 * Ensure the accept header option is set appropriatly before sending the requests and routing
408 * header option is updated with destination.
410 * @param object CA remote endpoint.
411 * @param requestInfo CA request info.
413 * @return ::OC_STACK_OK on success, some other value upon failure.
415 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
417 //-----------------------------------------------------------------------------
418 // Internal functions
419 //-----------------------------------------------------------------------------
421 uint32_t GetTicks(uint32_t afterMilliSeconds)
426 // Guard against overflow of uint32_t
427 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
428 COAP_TICKS_PER_SECOND)
430 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
438 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
440 VERIFY_NON_NULL_NR(in, FATAL);
441 VERIFY_NON_NULL_NR(out, FATAL);
443 out->adapter = (OCTransportAdapter)in->adapter;
444 out->flags = CAToOCTransportFlags(in->flags);
445 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
446 out->port = in->port;
447 out->ifindex = in->ifindex;
448 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
449 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
453 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
455 VERIFY_NON_NULL_NR(in, FATAL);
456 VERIFY_NON_NULL_NR(out, FATAL);
458 out->adapter = (CATransportAdapter_t)in->adapter;
459 out->flags = OCToCATransportFlags(in->flags);
460 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
461 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
462 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
464 out->port = in->port;
465 out->ifindex = in->ifindex;
468 void FixUpClientResponse(OCClientResponse *cr)
470 VERIFY_NON_NULL_NR(cr, FATAL);
472 cr->addr = &cr->devAddr;
473 cr->connType = (OCConnectivityType)
474 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
477 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
479 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
480 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
482 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
483 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
484 if (OC_STACK_OK != rmResult)
486 OIC_LOG(ERROR, TAG, "Add destination option failed");
491 // OC stack prefer CBOR encoded payloads.
492 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
493 CAResult_t result = CASendRequest(object, requestInfo);
494 if(CA_STATUS_OK != result)
496 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
497 return CAResultToOCResult(result);
501 //-----------------------------------------------------------------------------
502 // Internal API function
503 //-----------------------------------------------------------------------------
505 // This internal function is called to update the stack with the status of
506 // observers and communication failures
507 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
509 OCStackResult result = OC_STACK_ERROR;
510 ResourceObserver * observer = NULL;
511 OCEntityHandlerRequest ehRequest = {0};
515 case OC_OBSERVER_NOT_INTERESTED:
516 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
517 observer = GetObserverUsingToken (token, tokenLength);
520 result = FormOCEntityHandlerRequest(&ehRequest,
521 (OCRequestHandle)NULL,
524 (OCResourceHandle)NULL,
525 NULL, PAYLOAD_TYPE_REPRESENTATION,
527 OC_OBSERVE_DEREGISTER,
530 if(result != OC_STACK_OK)
534 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
535 observer->resource->entityHandlerCallbackParam);
538 result = DeleteObserverUsingToken (token, tokenLength);
539 if(result == OC_STACK_OK)
541 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
545 result = OC_STACK_OK;
546 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
550 case OC_OBSERVER_STILL_INTERESTED:
551 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
552 observer = GetObserverUsingToken (token, tokenLength);
555 observer->forceHighQos = 0;
556 observer->failedCommCount = 0;
557 result = OC_STACK_OK;
561 result = OC_STACK_OBSERVER_NOT_FOUND;
565 case OC_OBSERVER_FAILED_COMM:
566 OIC_LOG(DEBUG, TAG, "observer is unreachable");
567 observer = GetObserverUsingToken (token, tokenLength);
570 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
572 result = FormOCEntityHandlerRequest(&ehRequest,
573 (OCRequestHandle)NULL,
576 (OCResourceHandle)NULL,
577 NULL, PAYLOAD_TYPE_REPRESENTATION,
579 OC_OBSERVE_DEREGISTER,
582 if(result != OC_STACK_OK)
584 return OC_STACK_ERROR;
586 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
587 observer->resource->entityHandlerCallbackParam);
589 result = DeleteObserverUsingToken (token, tokenLength);
590 if(result == OC_STACK_OK)
592 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
596 result = OC_STACK_OK;
597 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
602 observer->failedCommCount++;
603 result = OC_STACK_CONTINUE;
605 observer->forceHighQos = 1;
606 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
610 OIC_LOG(ERROR, TAG, "Unknown status");
611 result = OC_STACK_ERROR;
617 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
619 OCStackResult ret = OC_STACK_ERROR;
623 case CA_ADAPTER_NOT_ENABLED:
624 case CA_SERVER_NOT_STARTED:
625 ret = OC_STACK_ADAPTER_NOT_ENABLED;
627 case CA_MEMORY_ALLOC_FAILED:
628 ret = OC_STACK_NO_MEMORY;
630 case CA_STATUS_INVALID_PARAM:
631 ret = OC_STACK_INVALID_PARAM;
639 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
641 OCStackResult ret = OC_STACK_ERROR;
645 ret = OC_STACK_RESOURCE_CREATED;
648 ret = OC_STACK_RESOURCE_DELETED;
651 ret = OC_STACK_RESOURCE_CHANGED;
658 ret = OC_STACK_INVALID_QUERY;
660 case CA_UNAUTHORIZED_REQ:
661 ret = OC_STACK_UNAUTHORIZED_REQ;
664 ret = OC_STACK_INVALID_OPTION;
667 ret = OC_STACK_NO_RESOURCE;
669 case CA_RETRANSMIT_TIMEOUT:
670 ret = OC_STACK_COMM_ERROR;
672 case CA_REQUEST_ENTITY_TOO_LARGE:
673 ret = OC_STACK_TOO_LARGE_REQ;
681 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
683 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
692 // This Response Code is like HTTP 204 "No Content" but only used in
693 // response to POST and PUT requests.
697 // This Response Code is like HTTP 200 "OK" but only used in response to
702 // This should not happen but,
703 // give it a value just in case but output an error
705 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
709 case OC_STACK_RESOURCE_CREATED:
712 case OC_STACK_RESOURCE_DELETED:
715 case OC_STACK_RESOURCE_CHANGED:
718 case OC_STACK_INVALID_QUERY:
721 case OC_STACK_INVALID_OPTION:
724 case OC_STACK_NO_RESOURCE:
727 case OC_STACK_COMM_ERROR:
728 ret = CA_RETRANSMIT_TIMEOUT;
730 case OC_STACK_UNAUTHORIZED_REQ:
731 ret = CA_UNAUTHORIZED_REQ;
739 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
741 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
743 // supply default behavior.
744 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
746 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
748 if ((caFlags & OC_MASK_SCOPE) == 0)
750 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
755 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
757 return (OCTransportFlags)caFlags;
760 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
762 uint32_t lowerBound = 0;
763 uint32_t higherBound = 0;
765 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
767 return OC_STACK_INVALID_PARAM;
770 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
772 cbNode->presence->TTL = maxAgeSeconds;
774 for (int index = 0; index < PresenceTimeOutSize; index++)
776 // Guard against overflow
777 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
780 lowerBound = GetTicks((PresenceTimeOut[index] *
781 cbNode->presence->TTL *
782 MILLISECONDS_PER_SECOND)/100);
786 lowerBound = GetTicks(UINT32_MAX);
789 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
792 higherBound = GetTicks((PresenceTimeOut[index + 1] *
793 cbNode->presence->TTL *
794 MILLISECONDS_PER_SECOND)/100);
798 higherBound = GetTicks(UINT32_MAX);
801 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
803 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
804 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
805 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
808 cbNode->presence->TTLlevel = 0;
810 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
814 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
816 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
818 return OC_RSRVD_TRIGGER_CREATE;
820 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
822 return OC_RSRVD_TRIGGER_CHANGE;
826 return OC_RSRVD_TRIGGER_DELETE;
830 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
834 return OC_PRESENCE_TRIGGER_CREATE;
836 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
838 return OC_PRESENCE_TRIGGER_CREATE;
840 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
842 return OC_PRESENCE_TRIGGER_CHANGE;
846 return OC_PRESENCE_TRIGGER_DELETE;
851 * Encode an address string to match RFC6874.
853 * @param outputAddress a char array to be written with the encoded string.
855 * @param outputSize size of outputAddress buffer.
857 * @param inputAddress a char array of size <= CA_MAX_URI_LENGTH
858 * containing a valid IPv6 address string.
860 * @return OC_STACK_OK if encoding succeeded.
861 * Else an error occured.
863 OCStackResult encodeAddressForRFC6874(char *outputAddress,
865 const char *inputAddress)
867 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
868 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
870 /** @todo Use a max IPv6 string length instead of CA_MAX_URI_LENGTH. */
871 #define ENCODE_MAX_INPUT_LENGTH CA_MAX_URI_LENGTH
873 size_t inputLength = strnlen(inputAddress, ENCODE_MAX_INPUT_LENGTH);
875 if (inputLength >= ENCODE_MAX_INPUT_LENGTH)
878 "encodeAddressForRFC6874 failed: Invalid input string: too long/unterminated!");
879 return OC_STACK_INVALID_PARAM;
882 // inputSize includes the null terminator
883 size_t inputSize = inputLength + 1;
885 if (inputSize > outputSize)
887 OIC_LOG_V(ERROR, TAG,
888 "encodeAddressForRFC6874 failed: "
889 "outputSize (%d) < inputSize (%d)",
890 outputSize, inputSize);
892 return OC_STACK_ERROR;
895 char* percentChar = strchr(inputAddress, '%');
897 // If there is no '%' character, then no change is required to the string.
898 if (NULL == percentChar)
900 OICStrcpy(outputAddress, outputSize, inputAddress);
904 const char* addressPart = &inputAddress[0];
905 const char* scopeIdPart = percentChar + 1;
907 // Sanity check to make sure this string doesn't have more '%' characters
908 if (NULL != strchr(scopeIdPart, '%'))
910 return OC_STACK_ERROR;
913 // If no string follows the first '%', then the input was invalid.
914 if (scopeIdPart[0] == '\0')
916 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
917 return OC_STACK_ERROR;
920 // Check to see if the string is already encoded
921 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
923 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
924 return OC_STACK_ERROR;
927 // Fail if we don't have room for encoded string's two additional chars
928 if (outputSize < (inputSize + 2))
930 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
931 return OC_STACK_ERROR;
934 // Restore the null terminator with an escaped '%' character, per RFC6874
935 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
936 strcat(outputAddress, "%25");
937 strcat(outputAddress, scopeIdPart);
943 * The cononical presence allows constructed URIs to be string compared.
945 * requestUri must be a char array of size CA_MAX_URI_LENGTH
947 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
950 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
951 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
952 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
954 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
956 if (ep->adapter == CA_ADAPTER_IP)
958 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
960 if ('\0' == ep->addr[0]) // multicast
962 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
966 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
968 OCStackResult result = encodeAddressForRFC6874(addressEncoded,
969 sizeof(addressEncoded),
972 if (OC_STACK_OK != result)
977 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
978 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
983 if ('\0' == ep->addr[0]) // multicast
985 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
986 ep->port = OC_MULTICAST_PORT;
988 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
989 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
993 // might work for other adapters (untested, but better than nothing)
994 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
995 OC_RSRVD_PRESENCE_URI);
999 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1000 const CAResponseInfo_t *responseInfo)
1002 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1003 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1005 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1006 ClientCB * cbNode = NULL;
1007 char *resourceTypeName = NULL;
1008 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1009 OCStackResult result = OC_STACK_ERROR;
1010 uint32_t maxAge = 0;
1012 char presenceUri[CA_MAX_URI_LENGTH];
1014 int presenceSubscribe = 0;
1015 int multicastPresenceSubscribe = 0;
1017 if (responseInfo->result != CA_CONTENT)
1019 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1020 return OC_STACK_ERROR;
1023 // check for unicast presence
1024 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
1025 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1027 return OC_STACK_INVALID_URI;
1030 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1033 presenceSubscribe = 1;
1037 // check for multiicast presence
1038 CAEndpoint_t ep = { .adapter = endpoint->adapter,
1039 .flags = endpoint->flags };
1041 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
1043 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1046 multicastPresenceSubscribe = 1;
1050 if (!presenceSubscribe && !multicastPresenceSubscribe)
1052 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1056 response.payload = NULL;
1057 response.result = OC_STACK_OK;
1059 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1060 FixUpClientResponse(&response);
1062 if (responseInfo->info.payload)
1064 result = OCParsePayload(&response.payload,
1065 PAYLOAD_TYPE_PRESENCE,
1066 responseInfo->info.payload,
1067 responseInfo->info.payloadSize);
1069 if(result != OC_STACK_OK)
1071 OIC_LOG(ERROR, TAG, "Presence parse failed");
1074 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1076 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1077 result = OC_STACK_ERROR;
1080 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1081 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1082 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1085 if (presenceSubscribe)
1087 if(cbNode->sequenceNumber == response.sequenceNumber)
1089 OIC_LOG(INFO, TAG, "No presence change");
1090 ResetPresenceTTL(cbNode, maxAge);
1091 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1097 OIC_LOG(INFO, TAG, "Stopping presence");
1098 response.result = OC_STACK_PRESENCE_STOPPED;
1099 if(cbNode->presence)
1101 OICFree(cbNode->presence->timeOut);
1102 OICFree(cbNode->presence);
1103 cbNode->presence = NULL;
1108 if(!cbNode->presence)
1110 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1112 if(!(cbNode->presence))
1114 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1115 result = OC_STACK_NO_MEMORY;
1119 VERIFY_NON_NULL_V(cbNode->presence);
1120 cbNode->presence->timeOut = NULL;
1121 cbNode->presence->timeOut = (uint32_t *)
1122 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1123 if(!(cbNode->presence->timeOut)){
1125 "Could not allocate memory for cbNode->presence->timeOut");
1126 OICFree(cbNode->presence);
1127 result = OC_STACK_NO_MEMORY;
1132 ResetPresenceTTL(cbNode, maxAge);
1134 cbNode->sequenceNumber = response.sequenceNumber;
1136 // Ensure that a filter is actually applied.
1137 if( resourceTypeName && cbNode->filterResourceType)
1139 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1148 // This is the multicast case
1149 OCMulticastNode* mcNode = NULL;
1150 mcNode = GetMCPresenceNode(presenceUri);
1154 if(mcNode->nonce == response.sequenceNumber)
1156 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1159 mcNode->nonce = response.sequenceNumber;
1163 OIC_LOG(INFO, TAG, "Stopping presence");
1164 response.result = OC_STACK_PRESENCE_STOPPED;
1169 char* uri = OICStrdup(presenceUri);
1173 "No Memory for URI to store in the presence node");
1174 result = OC_STACK_NO_MEMORY;
1178 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1179 if(result == OC_STACK_NO_MEMORY)
1182 "No Memory for Multicast Presence Node");
1186 // presence node now owns uri
1189 // Ensure that a filter is actually applied.
1190 if(resourceTypeName && cbNode->filterResourceType)
1192 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1199 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1201 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1203 FindAndDeleteClientCB(cbNode);
1207 OCPayloadDestroy(response.payload);
1211 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1213 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1215 if(responseInfo->info.resourceUri &&
1216 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1218 HandlePresenceResponse(endPoint, responseInfo);
1222 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1223 responseInfo->info.tokenLength, NULL, NULL);
1225 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1226 responseInfo->info.tokenLength);
1230 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1231 if(responseInfo->result == CA_EMPTY)
1233 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1234 // We do not have a case for the client to receive a RESET
1235 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1237 //This is the case of receiving an ACK on a request to a slow resource!
1238 OIC_LOG(INFO, TAG, "This is a pure ACK");
1239 //TODO: should we inform the client
1240 // app that at least the request was received at the server?
1243 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1245 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1246 OIC_LOG(INFO, TAG, "Calling into application address space");
1248 OCClientResponse response =
1249 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1250 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1251 FixUpClientResponse(&response);
1252 response.resourceUri = responseInfo->info.resourceUri;
1253 memcpy(response.identity.id, responseInfo->info.identity.id,
1254 sizeof (response.identity.id));
1255 response.identity.id_length = responseInfo->info.identity.id_length;
1257 response.result = CAResponseToOCStackResult(responseInfo->result);
1258 cbNode->callBack(cbNode->context,
1259 cbNode->handle, &response);
1260 FindAndDeleteClientCB(cbNode);
1264 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1265 OIC_LOG(INFO, TAG, "Calling into application address space");
1267 OCClientResponse response =
1268 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1269 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1270 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1271 FixUpClientResponse(&response);
1272 response.resourceUri = responseInfo->info.resourceUri;
1273 memcpy(response.identity.id, responseInfo->info.identity.id,
1274 sizeof (response.identity.id));
1275 response.identity.id_length = responseInfo->info.identity.id_length;
1277 response.result = CAResponseToOCStackResult(responseInfo->result);
1279 if(responseInfo->info.payload &&
1280 responseInfo->info.payloadSize)
1282 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1283 // check the security resource
1284 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1286 type = PAYLOAD_TYPE_SECURITY;
1288 else if (cbNode->method == OC_REST_DISCOVER)
1290 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1291 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1293 type = PAYLOAD_TYPE_DISCOVERY;
1296 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1298 type = PAYLOAD_TYPE_DISCOVERY;
1301 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1303 type = PAYLOAD_TYPE_DEVICE;
1305 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1307 type = PAYLOAD_TYPE_PLATFORM;
1309 #ifdef ROUTING_GATEWAY
1310 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1312 type = PAYLOAD_TYPE_REPRESENTATION;
1315 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1317 type = PAYLOAD_TYPE_RD;
1320 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1322 type = PAYLOAD_TYPE_REPRESENTATION;
1327 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1328 cbNode->method, cbNode->requestUri);
1332 else if (cbNode->method == OC_REST_GET ||
1333 cbNode->method == OC_REST_PUT ||
1334 cbNode->method == OC_REST_POST ||
1335 cbNode->method == OC_REST_OBSERVE ||
1336 cbNode->method == OC_REST_OBSERVE_ALL ||
1337 cbNode->method == OC_REST_DELETE)
1339 char targetUri[MAX_URI_LENGTH];
1340 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1341 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1342 if (strcmp(targetUri, cbNode->requestUri) == 0)
1344 type = PAYLOAD_TYPE_RD;
1346 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1348 type = PAYLOAD_TYPE_PLATFORM;
1350 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1352 type = PAYLOAD_TYPE_DEVICE;
1354 if (type == PAYLOAD_TYPE_INVALID)
1356 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1357 cbNode->method, cbNode->requestUri);
1358 type = PAYLOAD_TYPE_REPRESENTATION;
1363 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1364 cbNode->method, cbNode->requestUri);
1368 if(OC_STACK_OK != OCParsePayload(&response.payload,
1370 responseInfo->info.payload,
1371 responseInfo->info.payloadSize))
1373 OIC_LOG(ERROR, TAG, "Error converting payload");
1374 OCPayloadDestroy(response.payload);
1379 response.numRcvdVendorSpecificHeaderOptions = 0;
1380 if(responseInfo->info.numOptions > 0)
1383 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1384 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1387 uint32_t observationOption;
1388 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1389 for (observationOption=0, i=0;
1390 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1394 (observationOption << 8) | optionData[i];
1396 response.sequenceNumber = observationOption;
1397 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1402 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1405 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1407 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1408 OCPayloadDestroy(response.payload);
1412 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1414 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1415 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1419 if (cbNode->method == OC_REST_OBSERVE &&
1420 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1421 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1422 response.sequenceNumber <= cbNode->sequenceNumber)
1424 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1425 response.sequenceNumber);
1429 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1432 cbNode->sequenceNumber = response.sequenceNumber;
1434 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1436 FindAndDeleteClientCB(cbNode);
1440 // To keep discovery callbacks active.
1441 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1442 MILLISECONDS_PER_SECOND);
1446 //Need to send ACK when the response is CON
1447 if(responseInfo->info.type == CA_MSG_CONFIRM)
1449 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1450 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1453 OCPayloadDestroy(response.payload);
1460 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1461 if(responseInfo->result == CA_EMPTY)
1463 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1464 if(responseInfo->info.type == CA_MSG_RESET)
1466 OIC_LOG(INFO, TAG, "This is a RESET");
1467 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1468 OC_OBSERVER_NOT_INTERESTED);
1470 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1472 OIC_LOG(INFO, TAG, "This is a pure ACK");
1473 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1474 OC_OBSERVER_STILL_INTERESTED);
1477 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1479 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1480 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1481 OC_OBSERVER_FAILED_COMM);
1486 if(!cbNode && !observer)
1488 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1489 || myStackMode == OC_GATEWAY)
1491 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1492 if(responseInfo->result == CA_EMPTY)
1494 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1498 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1499 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1500 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1504 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1505 || myStackMode == OC_GATEWAY)
1507 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1508 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1510 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1511 responseInfo->info.messageId);
1513 if (responseInfo->info.type == CA_MSG_RESET)
1515 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1516 responseInfo->info.messageId);
1523 OIC_LOG(INFO, TAG, "Exit OCHandleResponse");
1526 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1528 VERIFY_NON_NULL_NR(endPoint, FATAL);
1529 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1531 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1533 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1534 #ifdef ROUTING_GATEWAY
1535 bool needRIHandling = false;
1537 * Routing manager is going to update either of endpoint or response or both.
1538 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1539 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1542 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1544 if(ret != OC_STACK_OK || !needRIHandling)
1546 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1552 * Put source in sender endpoint so that the next packet from application can be routed to
1553 * proper destination and remove "RM" coap header option before passing request / response to
1554 * RI as this option will make no sense to either RI or application.
1556 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1557 (uint8_t *) &(responseInfo->info.numOptions),
1558 (CAEndpoint_t *) endPoint);
1561 OCHandleResponse(endPoint, responseInfo);
1563 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1567 * This function handles error response from CA
1568 * code shall be added to handle the errors
1570 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1572 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1574 if (NULL == endPoint)
1576 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1580 if (NULL == errorInfo)
1582 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1586 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1587 errorInfo->info.tokenLength, NULL, NULL);
1590 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1591 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1592 FixUpClientResponse(&response);
1593 response.resourceUri = errorInfo->info.resourceUri;
1594 memcpy(response.identity.id, errorInfo->info.identity.id,
1595 sizeof (response.identity.id));
1596 response.identity.id_length = errorInfo->info.identity.id_length;
1597 response.result = CAResultToOCStackResult(errorInfo->result);
1599 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1600 FindAndDeleteClientCB(cbNode);
1603 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1607 * This function sends out Direct Stack Responses. These are responses that are not coming
1608 * from the application entity handler. These responses have no payload and are usually ACKs,
1609 * RESETs or some error conditions that were caught by the stack.
1611 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1612 const CAResponseResult_t responseResult, const CAMessageType_t type,
1613 const uint8_t numOptions, const CAHeaderOption_t *options,
1614 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1616 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1617 CAResponseInfo_t respInfo = {
1618 .result = responseResult
1620 respInfo.info.messageId = coapID;
1621 respInfo.info.numOptions = numOptions;
1623 if (respInfo.info.numOptions)
1625 respInfo.info.options =
1626 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1627 memcpy (respInfo.info.options, options,
1628 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1632 respInfo.info.payload = NULL;
1633 respInfo.info.token = token;
1634 respInfo.info.tokenLength = tokenLength;
1635 respInfo.info.type = type;
1636 respInfo.info.resourceUri = OICStrdup (resourceUri);
1637 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1639 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1640 // Add the destination to route option from the endpoint->routeData.
1641 bool doPost = false;
1642 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1643 if(OC_STACK_OK != result)
1645 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1650 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1651 CARequestInfo_t reqInfo = {.method = CA_POST };
1652 /* The following initialization is not done in a single initializer block as in
1653 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1654 * does not have designated initalizers. This is a work-around for now.
1656 reqInfo.info.type = CA_MSG_NONCONFIRM;
1657 reqInfo.info.messageId = coapID;
1658 reqInfo.info.tokenLength = tokenLength;
1659 reqInfo.info.token = token;
1660 reqInfo.info.numOptions = respInfo.info.numOptions;
1661 reqInfo.info.payload = NULL;
1662 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1663 if (reqInfo.info.numOptions)
1665 reqInfo.info.options =
1666 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1667 if (NULL == reqInfo.info.options)
1669 OIC_LOG(ERROR, TAG, "Calloc failed");
1670 return OC_STACK_NO_MEMORY;
1672 memcpy (reqInfo.info.options, respInfo.info.options,
1673 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1676 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1677 OICFree (reqInfo.info.resourceUri);
1678 OICFree (reqInfo.info.options);
1679 OICFree (respInfo.info.resourceUri);
1680 OICFree (respInfo.info.options);
1681 if (CA_STATUS_OK != caResult)
1683 OIC_LOG(ERROR, TAG, "CASendRequest error");
1684 return CAResultToOCResult(caResult);
1690 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1692 // resourceUri in the info field is cloned in the CA layer and
1693 // thus ownership is still here.
1694 OICFree (respInfo.info.resourceUri);
1695 OICFree (respInfo.info.options);
1696 if(CA_STATUS_OK != caResult)
1698 OIC_LOG(ERROR, TAG, "CASendResponse error");
1699 return CAResultToOCResult(caResult);
1702 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1706 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1708 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1709 OCStackResult result = OC_STACK_ERROR;
1710 if(!protocolRequest)
1712 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1713 return OC_STACK_INVALID_PARAM;
1716 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1717 protocolRequest->tokenLength);
1720 OIC_LOG(INFO, TAG, "This is a new Server Request");
1721 result = AddServerRequest(&request, protocolRequest->coapID,
1722 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1723 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1724 protocolRequest->observationOption, protocolRequest->qos,
1725 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1726 protocolRequest->payload, protocolRequest->requestToken,
1727 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1728 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1729 &protocolRequest->devAddr);
1730 if (OC_STACK_OK != result)
1732 OIC_LOG(ERROR, TAG, "Error adding server request");
1738 OIC_LOG(ERROR, TAG, "Out of Memory");
1739 return OC_STACK_NO_MEMORY;
1742 if(!protocolRequest->reqMorePacket)
1744 request->requestComplete = 1;
1749 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1752 if(request->requestComplete)
1754 OIC_LOG(INFO, TAG, "This Server Request is complete");
1755 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1756 OCResource *resource = NULL;
1757 result = DetermineResourceHandling (request, &resHandling, &resource);
1758 if (result == OC_STACK_OK)
1760 result = ProcessRequest(resHandling, resource, request);
1765 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1766 result = OC_STACK_CONTINUE;
1771 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1773 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1776 if (requestInfo->info.resourceUri &&
1777 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1779 HandleKeepAliveRequest(endPoint, requestInfo);
1784 OCStackResult requestResult = OC_STACK_ERROR;
1786 if(myStackMode == OC_CLIENT)
1788 //TODO: should the client be responding to requests?
1792 OCServerProtocolRequest serverRequest = {0};
1794 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1796 char * uriWithoutQuery = NULL;
1797 char * query = NULL;
1799 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1801 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1803 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1806 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1807 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1809 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1811 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1812 OICFree(uriWithoutQuery);
1816 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1817 OICFree(uriWithoutQuery);
1824 if(strlen(query) < MAX_QUERY_LENGTH)
1826 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1831 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1837 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1839 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1840 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1841 if (!serverRequest.payload)
1843 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1846 memcpy (serverRequest.payload, requestInfo->info.payload,
1847 requestInfo->info.payloadSize);
1851 serverRequest.reqTotalSize = 0;
1854 switch (requestInfo->method)
1857 serverRequest.method = OC_REST_GET;
1860 serverRequest.method = OC_REST_PUT;
1863 serverRequest.method = OC_REST_POST;
1866 serverRequest.method = OC_REST_DELETE;
1869 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1870 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1871 requestInfo->info.type, requestInfo->info.numOptions,
1872 requestInfo->info.options, requestInfo->info.token,
1873 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1874 OICFree(serverRequest.payload);
1878 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1879 requestInfo->info.tokenLength);
1881 serverRequest.tokenLength = requestInfo->info.tokenLength;
1882 if (serverRequest.tokenLength) {
1884 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1886 if (!serverRequest.requestToken)
1888 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1889 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1890 requestInfo->info.type, requestInfo->info.numOptions,
1891 requestInfo->info.options, requestInfo->info.token,
1892 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1893 OICFree(serverRequest.payload);
1896 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1899 switch (requestInfo->info.acceptFormat)
1901 case CA_FORMAT_APPLICATION_CBOR:
1902 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1904 case CA_FORMAT_UNDEFINED:
1905 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1908 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1911 if (requestInfo->info.type == CA_MSG_CONFIRM)
1913 serverRequest.qos = OC_HIGH_QOS;
1917 serverRequest.qos = OC_LOW_QOS;
1919 // CA does not need the following field
1920 // Are we sure CA does not need them? how is it responding to multicast
1921 serverRequest.delayedResNeeded = 0;
1923 serverRequest.coapID = requestInfo->info.messageId;
1925 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1927 // copy vendor specific header options
1928 uint8_t tempNum = (requestInfo->info.numOptions);
1930 // Assume no observation requested and it is a pure GET.
1931 // If obs registration/de-registration requested it'll be fetched from the
1932 // options in GetObserveHeaderOption()
1933 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1935 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1936 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1939 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1940 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1941 requestInfo->info.type, requestInfo->info.numOptions,
1942 requestInfo->info.options, requestInfo->info.token,
1943 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1944 OICFree(serverRequest.payload);
1945 OICFree(serverRequest.requestToken);
1948 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1949 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1951 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1952 sizeof(CAHeaderOption_t)*tempNum);
1955 requestResult = HandleStackRequests (&serverRequest);
1957 // Send ACK to client as precursor to slow response
1958 if (requestResult == OC_STACK_SLOW_RESOURCE)
1960 if (requestInfo->info.type == CA_MSG_CONFIRM)
1962 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1963 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1966 else if(!OCResultToSuccess(requestResult))
1968 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1970 CAResponseResult_t stackResponse =
1971 OCToCAStackResult(requestResult, serverRequest.method);
1973 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1974 requestInfo->info.type, requestInfo->info.numOptions,
1975 requestInfo->info.options, requestInfo->info.token,
1976 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1978 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1979 // The token is copied in there, and is thus still owned by this function.
1980 OICFree(serverRequest.payload);
1981 OICFree(serverRequest.requestToken);
1982 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1985 //This function will be called back by CA layer when a request is received
1986 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1988 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1991 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1997 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2001 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2002 #ifdef ROUTING_GATEWAY
2003 bool needRIHandling = false;
2004 bool isEmptyMsg = false;
2006 * Routing manager is going to update either of endpoint or request or both.
2007 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2008 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2009 * destination. It can also remove "RM" coap header option before passing request / response to
2010 * RI as this option will make no sense to either RI or application.
2012 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2013 &needRIHandling, &isEmptyMsg);
2014 if(OC_STACK_OK != ret || !needRIHandling)
2016 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2022 * Put source in sender endpoint so that the next packet from application can be routed to
2023 * proper destination and remove RM header option.
2025 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2026 (uint8_t *) &(requestInfo->info.numOptions),
2027 (CAEndpoint_t *) endPoint);
2029 #ifdef ROUTING_GATEWAY
2033 * In Gateways, the MSGType in route option is used to check if the actual
2034 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2035 * EMPTY response is sent in the form of POST request which need to be changed
2036 * to a EMPTY response by RM. This translation is done in this part of the code.
2038 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2039 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2040 .info.messageId = requestInfo->info.messageId,
2041 .info.type = CA_MSG_ACKNOWLEDGE};
2042 OCHandleResponse(endPoint, &respInfo);
2048 // Normal handling of the packet
2049 OCHandleRequests(endPoint, requestInfo);
2051 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2054 bool validatePlatformInfo(OCPlatformInfo info)
2057 if (!info.platformID)
2059 OIC_LOG(ERROR, TAG, "No platform ID found.");
2063 if (info.manufacturerName)
2065 size_t lenManufacturerName = strlen(info.manufacturerName);
2067 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2069 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2075 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2079 if (info.manufacturerUrl)
2081 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2083 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2090 //-----------------------------------------------------------------------------
2092 //-----------------------------------------------------------------------------
2094 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2097 !raInfo->username ||
2098 !raInfo->hostname ||
2099 !raInfo->xmpp_domain)
2102 return OC_STACK_INVALID_PARAM;
2104 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2105 gRASetInfo = (result == OC_STACK_OK)? true : false;
2111 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2115 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2118 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2120 if(stackState == OC_STACK_INITIALIZED)
2122 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2123 OCStop() between them are ignored.");
2127 #ifndef ROUTING_GATEWAY
2128 if (OC_GATEWAY == mode)
2130 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2131 return OC_STACK_INVALID_PARAM;
2138 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2139 return OC_STACK_ERROR;
2143 OCStackResult result = OC_STACK_ERROR;
2144 OIC_LOG(INFO, TAG, "Entering OCInit");
2147 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2148 || (mode == OC_GATEWAY)))
2150 OIC_LOG(ERROR, TAG, "Invalid mode");
2151 return OC_STACK_ERROR;
2155 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2157 caglobals.client = true;
2159 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2161 caglobals.server = true;
2164 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2165 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2167 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2169 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2170 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2172 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2175 defaultDeviceHandler = NULL;
2176 defaultDeviceHandlerCallbackParameter = NULL;
2178 result = CAResultToOCResult(CAInitialize());
2179 VERIFY_SUCCESS(result, OC_STACK_OK);
2181 result = CAResultToOCResult(OCSelectNetwork());
2182 VERIFY_SUCCESS(result, OC_STACK_OK);
2184 switch (myStackMode)
2187 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2188 result = CAResultToOCResult(CAStartDiscoveryServer());
2189 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2192 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2193 result = CAResultToOCResult(CAStartListeningServer());
2194 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2196 case OC_CLIENT_SERVER:
2198 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2199 result = CAResultToOCResult(CAStartListeningServer());
2200 if(result == OC_STACK_OK)
2202 result = CAResultToOCResult(CAStartDiscoveryServer());
2206 VERIFY_SUCCESS(result, OC_STACK_OK);
2209 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2212 #ifdef WITH_PRESENCE
2213 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2214 #endif // WITH_PRESENCE
2216 //Update Stack state to initialized
2217 stackState = OC_STACK_INITIALIZED;
2219 // Initialize resource
2220 if(myStackMode != OC_CLIENT)
2222 result = initResources();
2225 // Initialize the SRM Policy Engine
2226 if(result == OC_STACK_OK)
2228 result = SRMInitPolicyEngine();
2229 // TODO after BeachHead delivery: consolidate into single SRMInit()
2231 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2232 RMSetStackMode(mode);
2233 #ifdef ROUTING_GATEWAY
2234 if (OC_GATEWAY == myStackMode)
2236 result = RMInitialize();
2242 if (result == OC_STACK_OK)
2244 result = InitializeKeepAlive(myStackMode);
2249 if(result != OC_STACK_OK)
2251 OIC_LOG(ERROR, TAG, "Stack initialization error");
2252 deleteAllResources();
2254 stackState = OC_STACK_UNINITIALIZED;
2259 OCStackResult OCStop()
2261 OIC_LOG(INFO, TAG, "Entering OCStop");
2263 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2265 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2268 else if (stackState != OC_STACK_INITIALIZED)
2270 OIC_LOG(ERROR, TAG, "Stack not initialized");
2271 return OC_STACK_ERROR;
2274 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2276 #ifdef WITH_PRESENCE
2277 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2278 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2279 presenceResource.presenceTTL = 0;
2280 #endif // WITH_PRESENCE
2282 #ifdef ROUTING_GATEWAY
2283 if (OC_GATEWAY == myStackMode)
2290 TerminateKeepAlive(myStackMode);
2293 // Free memory dynamically allocated for resources
2294 deleteAllResources();
2296 DeletePlatformInfo();
2298 // Remove all observers
2299 DeleteObserverList();
2300 // Remove all the client callbacks
2301 DeleteClientCBList();
2303 // De-init the SRM Policy Engine
2304 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2305 SRMDeInitPolicyEngine();
2308 stackState = OC_STACK_UNINITIALIZED;
2312 OCStackResult OCStartMulticastServer()
2314 if(stackState != OC_STACK_INITIALIZED)
2316 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2317 return OC_STACK_ERROR;
2319 CAResult_t ret = CAStartListeningServer();
2320 if (CA_STATUS_OK != ret)
2322 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2323 return OC_STACK_ERROR;
2328 OCStackResult OCStopMulticastServer()
2330 CAResult_t ret = CAStopListeningServer();
2331 if (CA_STATUS_OK != ret)
2333 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2334 return OC_STACK_ERROR;
2339 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2344 return CA_MSG_CONFIRM;
2349 return CA_MSG_NONCONFIRM;
2354 * A request uri consists of the following components in order:
2357 * CoAP over UDP prefix "coap://"
2358 * CoAP over TCP prefix "coap+tcp://"
2360 * IPv6 address "[1234::5678]"
2361 * IPv4 address "192.168.1.1"
2362 * optional port ":5683"
2363 * resource uri "/oc/core..."
2365 * for PRESENCE requests, extract resource type.
2367 static OCStackResult ParseRequestUri(const char *fullUri,
2368 OCTransportAdapter adapter,
2369 OCTransportFlags flags,
2370 OCDevAddr **devAddr,
2372 char **resourceType)
2374 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2376 OCStackResult result = OC_STACK_OK;
2377 OCDevAddr *da = NULL;
2381 // provide defaults for all returned values
2388 *resourceUri = NULL;
2392 *resourceType = NULL;
2395 // delimit url prefix, if any
2396 const char *start = fullUri;
2397 char *slash2 = strstr(start, "//");
2402 char *slash = strchr(start, '/');
2405 return OC_STACK_INVALID_URI;
2408 // process url scheme
2409 size_t prefixLen = slash2 - fullUri;
2413 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2419 // TODO: this logic should come in with unit tests exercising the various strings
2420 // processs url prefix, if any
2421 size_t urlLen = slash - start;
2425 if (urlLen && devAddr)
2426 { // construct OCDevAddr
2427 if (start[0] == '[')
2429 char *close = strchr(++start, ']');
2430 if (!close || close > slash)
2432 return OC_STACK_INVALID_URI;
2435 if (close[1] == ':')
2442 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2446 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2448 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2452 char *dot = strchr(start, '.');
2453 if (dot && dot < slash)
2455 colon = strchr(start, ':');
2456 end = (colon && colon < slash) ? colon : slash;
2461 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2465 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2467 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2475 if (len >= sizeof(da->addr))
2477 return OC_STACK_INVALID_URI;
2479 // collect port, if any
2480 if (colon && colon < slash)
2482 for (colon++; colon < slash; colon++)
2485 if (c < '0' || c > '9')
2487 return OC_STACK_INVALID_URI;
2489 port = 10 * port + c - '0';
2494 if (len >= sizeof(da->addr))
2496 return OC_STACK_INVALID_URI;
2499 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2502 return OC_STACK_NO_MEMORY;
2504 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2506 da->adapter = adapter;
2508 if (!strncmp(fullUri, "coaps:", 6))
2510 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2515 // process resource uri, if any
2517 { // request uri and query
2518 size_t ulen = strlen(slash); // resource uri length
2519 size_t tlen = 0; // resource type length
2522 static const char strPresence[] = "/oic/ad?rt=";
2523 static const size_t lenPresence = sizeof(strPresence) - 1;
2524 if (!strncmp(slash, strPresence, lenPresence))
2526 type = slash + lenPresence;
2527 tlen = ulen - lenPresence;
2532 *resourceUri = (char *)OICMalloc(ulen + 1);
2535 result = OC_STACK_NO_MEMORY;
2538 strcpy(*resourceUri, slash);
2541 if (type && resourceType)
2543 *resourceType = (char *)OICMalloc(tlen + 1);
2546 result = OC_STACK_NO_MEMORY;
2550 OICStrcpy(*resourceType, (tlen+1), type);
2557 // free all returned values
2564 OICFree(*resourceUri);
2568 OICFree(*resourceType);
2573 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2574 char *resourceUri, char **requestUri)
2576 char uri[CA_MAX_URI_LENGTH];
2578 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2580 *requestUri = OICStrdup(uri);
2583 return OC_STACK_NO_MEMORY;
2590 * Discover or Perform requests on a specified resource
2592 OCStackResult OCDoResource(OCDoHandle *handle,
2594 const char *requestUri,
2595 const OCDevAddr *destination,
2597 OCConnectivityType connectivityType,
2598 OCQualityOfService qos,
2599 OCCallbackData *cbData,
2600 OCHeaderOption *options,
2603 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2605 // Validate input parameters
2606 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2607 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2608 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2610 OCStackResult result = OC_STACK_ERROR;
2611 CAResult_t caResult;
2612 CAToken_t token = NULL;
2613 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2614 ClientCB *clientCB = NULL;
2615 OCDoHandle resHandle = NULL;
2616 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2617 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2619 OCTransportAdapter adapter;
2620 OCTransportFlags flags;
2621 // the request contents are put here
2622 CARequestInfo_t requestInfo = {.method = CA_GET};
2623 // requestUri will be parsed into the following three variables
2624 OCDevAddr *devAddr = NULL;
2625 char *resourceUri = NULL;
2626 char *resourceType = NULL;
2629 * Support original behavior with address on resourceUri argument.
2631 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2632 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2634 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2636 if (result != OC_STACK_OK)
2638 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2645 case OC_REST_OBSERVE:
2646 case OC_REST_OBSERVE_ALL:
2647 case OC_REST_CANCEL_OBSERVE:
2648 requestInfo.method = CA_GET;
2651 requestInfo.method = CA_PUT;
2654 requestInfo.method = CA_POST;
2656 case OC_REST_DELETE:
2657 requestInfo.method = CA_DELETE;
2659 case OC_REST_DISCOVER:
2661 if (destination || devAddr)
2663 requestInfo.isMulticast = false;
2667 tmpDevAddr.adapter = adapter;
2668 tmpDevAddr.flags = flags;
2669 destination = &tmpDevAddr;
2670 requestInfo.isMulticast = true;
2672 // CA_DISCOVER will become GET and isMulticast
2673 requestInfo.method = CA_GET;
2675 #ifdef WITH_PRESENCE
2676 case OC_REST_PRESENCE:
2677 // Replacing method type with GET because "presence"
2678 // is a stack layer only implementation.
2679 requestInfo.method = CA_GET;
2683 result = OC_STACK_INVALID_METHOD;
2687 if (!devAddr && !destination)
2689 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2690 result = OC_STACK_INVALID_PARAM;
2694 /* If not original behavior, use destination argument */
2695 if (destination && !devAddr)
2697 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2700 result = OC_STACK_NO_MEMORY;
2703 *devAddr = *destination;
2706 resHandle = GenerateInvocationHandle();
2709 result = OC_STACK_NO_MEMORY;
2713 caResult = CAGenerateToken(&token, tokenLength);
2714 if (caResult != CA_STATUS_OK)
2716 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2717 result= OC_STACK_ERROR;
2721 // fill in request data
2722 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2723 requestInfo.info.token = token;
2724 requestInfo.info.tokenLength = tokenLength;
2725 requestInfo.info.resourceUri = resourceUri;
2727 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2729 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2730 options, numOptions, OC_OBSERVE_REGISTER);
2731 if (result != OC_STACK_OK)
2735 requestInfo.info.numOptions = numOptions + 1;
2739 requestInfo.info.numOptions = numOptions;
2740 requestInfo.info.options =
2741 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2742 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2743 numOptions * sizeof(CAHeaderOption_t));
2746 CopyDevAddrToEndpoint(devAddr, &endpoint);
2751 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2754 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2757 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2761 requestInfo.info.payload = NULL;
2762 requestInfo.info.payloadSize = 0;
2763 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2766 // prepare for response
2767 #ifdef WITH_PRESENCE
2768 if (method == OC_REST_PRESENCE)
2770 char *presenceUri = NULL;
2771 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2772 if (OC_STACK_OK != result)
2777 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2778 // Presence notification will form a canonical uri to
2779 // look for callbacks into the application.
2780 resourceUri = presenceUri;
2784 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2785 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2786 method, devAddr, resourceUri, resourceType, ttl);
2787 if (OC_STACK_OK != result)
2792 devAddr = NULL; // Client CB list entry now owns it
2793 resourceUri = NULL; // Client CB list entry now owns it
2794 resourceType = NULL; // Client CB list entry now owns it
2797 result = OCSendRequest(&endpoint, &requestInfo);
2798 if (OC_STACK_OK != result)
2805 *handle = resHandle;
2809 if (result != OC_STACK_OK)
2811 OIC_LOG(ERROR, TAG, "OCDoResource error");
2812 FindAndDeleteClientCB(clientCB);
2813 CADestroyToken(token);
2821 // This is the owner of the payload object, so we free it
2822 OCPayloadDestroy(payload);
2823 OICFree(requestInfo.info.payload);
2825 OICFree(resourceUri);
2826 OICFree(resourceType);
2827 OICFree(requestInfo.info.options);
2831 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2835 * This ftn is implemented one of two ways in the case of observation:
2837 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2838 * Remove the callback associated on client side.
2839 * When the next notification comes in from server,
2840 * reply with RESET message to server.
2841 * Keep in mind that the server will react to RESET only
2842 * if the last notification was sent as CON
2844 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2845 * and it is associated with an observe request
2846 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2847 * Send CON Observe request to server with
2848 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2849 * Remove the callback associated on client side.
2851 OCStackResult ret = OC_STACK_OK;
2852 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2853 CARequestInfo_t requestInfo = {.method = CA_GET};
2857 return OC_STACK_INVALID_PARAM;
2860 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2863 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2864 return OC_STACK_ERROR;
2867 switch (clientCB->method)
2869 case OC_REST_OBSERVE:
2870 case OC_REST_OBSERVE_ALL:
2872 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2874 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2876 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2878 FindAndDeleteClientCB(clientCB);
2882 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2884 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2885 requestInfo.info.token = clientCB->token;
2886 requestInfo.info.tokenLength = clientCB->tokenLength;
2888 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2889 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2891 return OC_STACK_ERROR;
2893 requestInfo.info.numOptions = numOptions + 1;
2894 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2897 ret = OCSendRequest(&endpoint, &requestInfo);
2899 if (requestInfo.info.options)
2901 OICFree (requestInfo.info.options);
2903 if (requestInfo.info.resourceUri)
2905 OICFree (requestInfo.info.resourceUri);
2910 case OC_REST_DISCOVER:
2911 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2912 clientCB->requestUri);
2913 FindAndDeleteClientCB(clientCB);
2916 #ifdef WITH_PRESENCE
2917 case OC_REST_PRESENCE:
2918 FindAndDeleteClientCB(clientCB);
2923 ret = OC_STACK_INVALID_METHOD;
2931 * @brief Register Persistent storage callback.
2932 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2934 * OC_STACK_OK - No errors; Success
2935 * OC_STACK_INVALID_PARAM - Invalid parameter
2937 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2939 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2940 if(!persistentStorageHandler)
2942 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2943 return OC_STACK_INVALID_PARAM;
2947 if( !persistentStorageHandler->open ||
2948 !persistentStorageHandler->close ||
2949 !persistentStorageHandler->read ||
2950 !persistentStorageHandler->unlink ||
2951 !persistentStorageHandler->write)
2953 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2954 return OC_STACK_INVALID_PARAM;
2957 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2960 #ifdef WITH_PRESENCE
2962 OCStackResult OCProcessPresence()
2964 OCStackResult result = OC_STACK_OK;
2966 // the following line floods the log with messages that are irrelevant
2967 // to most purposes. Uncomment as needed.
2968 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2969 ClientCB* cbNode = NULL;
2970 OCClientResponse clientResponse;
2971 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2973 LL_FOREACH(cbList, cbNode)
2975 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2980 uint32_t now = GetTicks(0);
2981 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2982 cbNode->presence->TTLlevel);
2983 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2985 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2990 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2992 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2993 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2995 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2997 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2999 clientResponse.sequenceNumber = 0;
3000 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3001 clientResponse.devAddr = *cbNode->devAddr;
3002 FixUpClientResponse(&clientResponse);
3003 clientResponse.payload = NULL;
3005 // Increment the TTLLevel (going to a next state), so we don't keep
3006 // sending presence notification to client.
3007 cbNode->presence->TTLlevel++;
3008 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3009 cbNode->presence->TTLlevel);
3011 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3012 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3014 FindAndDeleteClientCB(cbNode);
3018 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3023 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3024 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3025 CARequestInfo_t requestInfo = {.method = CA_GET};
3027 OIC_LOG(DEBUG, TAG, "time to test server presence");
3029 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3031 requestData.type = CA_MSG_NONCONFIRM;
3032 requestData.token = cbNode->token;
3033 requestData.tokenLength = cbNode->tokenLength;
3034 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3035 requestInfo.method = CA_GET;
3036 requestInfo.info = requestData;
3038 result = OCSendRequest(&endpoint, &requestInfo);
3039 if (OC_STACK_OK != result)
3044 cbNode->presence->TTLlevel++;
3045 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3048 if (result != OC_STACK_OK)
3050 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3055 #endif // WITH_PRESENCE
3057 OCStackResult OCProcess()
3059 #ifdef WITH_PRESENCE
3060 OCProcessPresence();
3062 CAHandleRequestResponse();
3064 #ifdef ROUTING_GATEWAY
3074 #ifdef WITH_PRESENCE
3075 OCStackResult OCStartPresence(const uint32_t ttl)
3077 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3078 OCChangeResourceProperty(
3079 &(((OCResource *)presenceResource.handle)->resourceProperties),
3082 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3084 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3085 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3089 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3090 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3094 presenceResource.presenceTTL = ttl;
3096 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3098 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3100 presenceState = OC_PRESENCE_INITIALIZED;
3102 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3104 CAToken_t caToken = NULL;
3105 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3106 if (caResult != CA_STATUS_OK)
3108 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3109 CADestroyToken(caToken);
3110 return OC_STACK_ERROR;
3113 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3114 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3115 CADestroyToken(caToken);
3118 // Each time OCStartPresence is called
3119 // a different random 32-bit integer number is used
3120 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3122 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3123 OC_PRESENCE_TRIGGER_CREATE);
3126 OCStackResult OCStopPresence()
3128 OCStackResult result = OC_STACK_ERROR;
3130 if(presenceResource.handle)
3132 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3134 // make resource inactive
3135 result = OCChangeResourceProperty(
3136 &(((OCResource *) presenceResource.handle)->resourceProperties),
3140 if(result != OC_STACK_OK)
3143 "Changing the presence resource properties to ACTIVE not successful");
3147 return SendStopNotification();
3151 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3152 void* callbackParameter)
3154 defaultDeviceHandler = entityHandler;
3155 defaultDeviceHandlerCallbackParameter = callbackParameter;
3160 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3162 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3164 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3166 if (validatePlatformInfo(platformInfo))
3168 return SavePlatformInfo(platformInfo);
3172 return OC_STACK_INVALID_PARAM;
3177 return OC_STACK_ERROR;
3181 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3183 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3185 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3187 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3188 return OC_STACK_INVALID_PARAM;
3191 if (deviceInfo.types)
3193 OCStringLL *type = deviceInfo.types;
3194 OCResource *resource = findResource((OCResource *) deviceResource);
3197 return OC_STACK_INVALID_PARAM;
3202 OCBindResourceTypeToResource(deviceResource, type->value);
3206 return SaveDeviceInfo(deviceInfo);
3209 OCStackResult OCCreateResource(OCResourceHandle *handle,
3210 const char *resourceTypeName,
3211 const char *resourceInterfaceName,
3212 const char *uri, OCEntityHandler entityHandler,
3213 void* callbackParam,
3214 uint8_t resourceProperties)
3217 OCResource *pointer = NULL;
3218 OCStackResult result = OC_STACK_ERROR;
3220 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3222 if(myStackMode == OC_CLIENT)
3224 return OC_STACK_INVALID_PARAM;
3226 // Validate parameters
3227 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3229 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3230 return OC_STACK_INVALID_URI;
3232 // Is it presented during resource discovery?
3233 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3235 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3236 return OC_STACK_INVALID_PARAM;
3239 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3241 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3245 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3247 // Make sure resourceProperties bitmask has allowed properties specified
3248 if (resourceProperties
3249 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3250 OC_EXPLICIT_DISCOVERABLE
3259 OIC_LOG(ERROR, TAG, "Invalid property");
3260 return OC_STACK_INVALID_PARAM;
3263 // If the headResource is NULL, then no resources have been created...
3264 pointer = headResource;
3267 // At least one resources is in the resource list, so we need to search for
3268 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3271 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3273 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3274 return OC_STACK_INVALID_PARAM;
3276 pointer = pointer->next;
3279 // Create the pointer and insert it into the resource list
3280 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3283 result = OC_STACK_NO_MEMORY;
3286 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3288 insertResource(pointer);
3291 pointer->uri = OICStrdup(uri);
3294 result = OC_STACK_NO_MEMORY;
3298 // Set properties. Set OC_ACTIVE
3299 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3302 // Add the resourcetype to the resource
3303 result = BindResourceTypeToResource(pointer, resourceTypeName);
3304 if (result != OC_STACK_OK)
3306 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3310 // Add the resourceinterface to the resource
3311 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3312 if (result != OC_STACK_OK)
3314 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3318 // If an entity handler has been passed, attach it to the newly created
3319 // resource. Otherwise, set the default entity handler.
3322 pointer->entityHandler = entityHandler;
3323 pointer->entityHandlerCallbackParam = callbackParam;
3327 pointer->entityHandler = defaultResourceEHandler;
3328 pointer->entityHandlerCallbackParam = NULL;
3331 // Initialize a pointer indicating child resources in case of collection
3332 pointer->rsrcChildResourcesHead = NULL;
3335 result = OC_STACK_OK;
3337 #ifdef WITH_PRESENCE
3338 if (presenceResource.handle)
3340 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3341 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3345 if (result != OC_STACK_OK)
3347 // Deep delete of resource and other dynamic elements that it contains
3348 deleteResource(pointer);
3353 OCStackResult OCBindResource(
3354 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3356 OCResource *resource = NULL;
3357 OCChildResource *tempChildResource = NULL;
3358 OCChildResource *newChildResource = NULL;
3360 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3362 // Validate parameters
3363 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3364 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3365 // Container cannot contain itself
3366 if (collectionHandle == resourceHandle)
3368 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3369 return OC_STACK_INVALID_PARAM;
3372 // Use the handle to find the resource in the resource linked list
3373 resource = findResource((OCResource *) collectionHandle);
3376 OIC_LOG(ERROR, TAG, "Collection handle not found");
3377 return OC_STACK_INVALID_PARAM;
3380 // Look for an open slot to add add the child resource.
3381 // If found, add it and return success
3383 tempChildResource = resource->rsrcChildResourcesHead;
3385 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3387 // TODO: what if one of child resource was deregistered without unbinding?
3388 tempChildResource = tempChildResource->next;
3391 // Do memory allocation for child resource
3392 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3393 if(!newChildResource)
3395 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3396 return OC_STACK_ERROR;
3399 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3400 newChildResource->next = NULL;
3402 if(!resource->rsrcChildResourcesHead)
3404 resource->rsrcChildResourcesHead = newChildResource;
3407 tempChildResource->next = newChildResource;
3410 OIC_LOG(INFO, TAG, "resource bound");
3412 #ifdef WITH_PRESENCE
3413 if (presenceResource.handle)
3415 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3416 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3417 OC_PRESENCE_TRIGGER_CHANGE);
3424 OCStackResult OCUnBindResource(
3425 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3427 OCResource *resource = NULL;
3428 OCChildResource *tempChildResource = NULL;
3429 OCChildResource *tempLastChildResource = NULL;
3431 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3433 // Validate parameters
3434 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3435 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3436 // Container cannot contain itself
3437 if (collectionHandle == resourceHandle)
3439 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3440 return OC_STACK_INVALID_PARAM;
3443 // Use the handle to find the resource in the resource linked list
3444 resource = findResource((OCResource *) collectionHandle);
3447 OIC_LOG(ERROR, TAG, "Collection handle not found");
3448 return OC_STACK_INVALID_PARAM;
3451 // Look for an open slot to add add the child resource.
3452 // If found, add it and return success
3453 if(!resource->rsrcChildResourcesHead)
3455 OIC_LOG(INFO, TAG, "resource not found in collection");
3457 // Unable to add resourceHandle, so return error
3458 return OC_STACK_ERROR;
3462 tempChildResource = resource->rsrcChildResourcesHead;
3464 while (tempChildResource)
3466 if(tempChildResource->rsrcResource == resourceHandle)
3468 // if resource going to be unbinded is the head one.
3469 if( tempChildResource == resource->rsrcChildResourcesHead )
3471 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3472 OICFree(resource->rsrcChildResourcesHead);
3473 resource->rsrcChildResourcesHead = temp;
3478 OCChildResource *temp = tempChildResource->next;
3479 OICFree(tempChildResource);
3480 tempLastChildResource->next = temp;
3484 OIC_LOG(INFO, TAG, "resource unbound");
3486 // Send notification when resource is unbounded successfully.
3487 #ifdef WITH_PRESENCE
3488 if (presenceResource.handle)
3490 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3491 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3492 OC_PRESENCE_TRIGGER_CHANGE);
3495 tempChildResource = NULL;
3496 tempLastChildResource = NULL;
3502 tempLastChildResource = tempChildResource;
3503 tempChildResource = tempChildResource->next;
3506 OIC_LOG(INFO, TAG, "resource not found in collection");
3508 tempChildResource = NULL;
3509 tempLastChildResource = NULL;
3511 // Unable to add resourceHandle, so return error
3512 return OC_STACK_ERROR;
3515 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3517 if (!resourceItemName)
3521 // Per RFC 6690 only registered values must follow the first rule below.
3522 // At this point in time the only values registered begin with "core", and
3523 // all other values are specified as opaque strings where multiple values
3524 // are separated by a space.
3525 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3527 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3529 if (resourceItemName[index] != '.'
3530 && resourceItemName[index] != '-'
3531 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3532 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3540 for (size_t index = 0; resourceItemName[index]; ++index)
3542 if (resourceItemName[index] == ' '
3543 || resourceItemName[index] == '\t'
3544 || resourceItemName[index] == '\r'
3545 || resourceItemName[index] == '\n')
3555 OCStackResult BindResourceTypeToResource(OCResource* resource,
3556 const char *resourceTypeName)
3558 OCResourceType *pointer = NULL;
3560 OCStackResult result = OC_STACK_ERROR;
3562 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3564 if (!ValidateResourceTypeInterface(resourceTypeName))
3566 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3567 return OC_STACK_INVALID_PARAM;
3570 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3573 result = OC_STACK_NO_MEMORY;
3577 str = OICStrdup(resourceTypeName);
3580 result = OC_STACK_NO_MEMORY;
3583 pointer->resourcetypename = str;
3584 pointer->next = NULL;
3586 insertResourceType(resource, pointer);
3587 result = OC_STACK_OK;
3590 if (result != OC_STACK_OK)
3599 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3600 const char *resourceInterfaceName)
3602 OCResourceInterface *pointer = NULL;
3604 OCStackResult result = OC_STACK_ERROR;
3606 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3608 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3610 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3611 return OC_STACK_INVALID_PARAM;
3614 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3616 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3619 result = OC_STACK_NO_MEMORY;
3623 str = OICStrdup(resourceInterfaceName);
3626 result = OC_STACK_NO_MEMORY;
3629 pointer->name = str;
3631 // Bind the resourceinterface to the resource
3632 insertResourceInterface(resource, pointer);
3634 result = OC_STACK_OK;
3637 if (result != OC_STACK_OK)
3646 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3647 const char *resourceTypeName)
3650 OCStackResult result = OC_STACK_ERROR;
3651 OCResource *resource = NULL;
3653 resource = findResource((OCResource *) handle);
3656 OIC_LOG(ERROR, TAG, "Resource not found");
3657 return OC_STACK_ERROR;
3660 result = BindResourceTypeToResource(resource, resourceTypeName);
3662 #ifdef WITH_PRESENCE
3663 if(presenceResource.handle)
3665 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3666 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3673 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3674 const char *resourceInterfaceName)
3677 OCStackResult result = OC_STACK_ERROR;
3678 OCResource *resource = NULL;
3680 resource = findResource((OCResource *) handle);
3683 OIC_LOG(ERROR, TAG, "Resource not found");
3684 return OC_STACK_ERROR;
3687 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3689 #ifdef WITH_PRESENCE
3690 if (presenceResource.handle)
3692 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3693 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3700 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3702 OCResource *pointer = headResource;
3704 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3708 *numResources = *numResources + 1;
3709 pointer = pointer->next;
3714 OCResourceHandle OCGetResourceHandle(uint8_t index)
3716 OCResource *pointer = headResource;
3718 for( uint8_t i = 0; i < index && pointer; ++i)
3720 pointer = pointer->next;
3722 return (OCResourceHandle) pointer;
3725 OCStackResult OCDeleteResource(OCResourceHandle handle)
3729 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3730 return OC_STACK_INVALID_PARAM;
3733 OCResource *resource = findResource((OCResource *) handle);
3734 if (resource == NULL)
3736 OIC_LOG(ERROR, TAG, "Resource not found");
3737 return OC_STACK_NO_RESOURCE;
3740 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3742 OIC_LOG(ERROR, TAG, "Error deleting resource");
3743 return OC_STACK_ERROR;
3749 const char *OCGetResourceUri(OCResourceHandle handle)
3751 OCResource *resource = NULL;
3753 resource = findResource((OCResource *) handle);
3756 return resource->uri;
3758 return (const char *) NULL;
3761 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3763 OCResource *resource = NULL;
3765 resource = findResource((OCResource *) handle);
3768 return resource->resourceProperties;
3770 return (OCResourceProperty)-1;
3773 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3774 uint8_t *numResourceTypes)
3776 OCResource *resource = NULL;
3777 OCResourceType *pointer = NULL;
3779 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3780 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3782 *numResourceTypes = 0;
3784 resource = findResource((OCResource *) handle);
3787 pointer = resource->rsrcType;
3790 *numResourceTypes = *numResourceTypes + 1;
3791 pointer = pointer->next;
3797 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3799 OCResourceType *resourceType = NULL;
3801 resourceType = findResourceTypeAtIndex(handle, index);
3804 return resourceType->resourcetypename;
3806 return (const char *) NULL;
3809 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3810 uint8_t *numResourceInterfaces)
3812 OCResourceInterface *pointer = NULL;
3813 OCResource *resource = NULL;
3815 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3816 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3818 *numResourceInterfaces = 0;
3819 resource = findResource((OCResource *) handle);
3822 pointer = resource->rsrcInterface;
3825 *numResourceInterfaces = *numResourceInterfaces + 1;
3826 pointer = pointer->next;
3832 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3834 OCResourceInterface *resourceInterface = NULL;
3836 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3837 if (resourceInterface)
3839 return resourceInterface->name;
3841 return (const char *) NULL;
3844 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3847 OCResource *resource = NULL;
3848 OCChildResource *tempChildResource = NULL;
3851 resource = findResource((OCResource *) collectionHandle);
3857 tempChildResource = resource->rsrcChildResourcesHead;
3859 while(tempChildResource)
3863 return tempChildResource->rsrcResource;
3866 tempChildResource = tempChildResource->next;
3869 // In this case, the number of resource handles in the collection exceeds the index
3870 tempChildResource = NULL;
3874 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3875 OCEntityHandler entityHandler,
3876 void* callbackParam)
3878 OCResource *resource = NULL;
3880 // Validate parameters
3881 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3883 // Use the handle to find the resource in the resource linked list
3884 resource = findResource((OCResource *)handle);
3887 OIC_LOG(ERROR, TAG, "Resource not found");
3888 return OC_STACK_ERROR;
3892 resource->entityHandler = entityHandler;
3893 resource->entityHandlerCallbackParam = callbackParam;
3895 #ifdef WITH_PRESENCE
3896 if (presenceResource.handle)
3898 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3899 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3906 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3908 OCResource *resource = NULL;
3910 resource = findResource((OCResource *)handle);
3913 OIC_LOG(ERROR, TAG, "Resource not found");
3918 return resource->entityHandler;
3921 void incrementSequenceNumber(OCResource * resPtr)
3923 // Increment the sequence number
3924 resPtr->sequenceNum += 1;
3925 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3927 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3932 #ifdef WITH_PRESENCE
3933 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3934 OCPresenceTrigger trigger)
3936 OCResource *resPtr = NULL;
3937 OCStackResult result = OC_STACK_ERROR;
3938 OCMethod method = OC_REST_PRESENCE;
3939 uint32_t maxAge = 0;
3940 resPtr = findResource((OCResource *) presenceResource.handle);
3943 return OC_STACK_NO_RESOURCE;
3946 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3948 maxAge = presenceResource.presenceTTL;
3950 result = SendAllObserverNotification(method, resPtr, maxAge,
3951 trigger, resourceType, OC_LOW_QOS);
3957 OCStackResult SendStopNotification()
3959 OCResource *resPtr = NULL;
3960 OCStackResult result = OC_STACK_ERROR;
3961 OCMethod method = OC_REST_PRESENCE;
3962 resPtr = findResource((OCResource *) presenceResource.handle);
3965 return OC_STACK_NO_RESOURCE;
3968 // maxAge is 0. ResourceType is NULL.
3969 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3975 #endif // WITH_PRESENCE
3976 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3978 OCResource *resPtr = NULL;
3979 OCStackResult result = OC_STACK_ERROR;
3980 OCMethod method = OC_REST_NOMETHOD;
3981 uint32_t maxAge = 0;
3983 OIC_LOG(INFO, TAG, "Notifying all observers");
3984 #ifdef WITH_PRESENCE
3985 if(handle == presenceResource.handle)
3989 #endif // WITH_PRESENCE
3990 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3992 // Verify that the resource exists
3993 resPtr = findResource ((OCResource *) handle);
3996 return OC_STACK_NO_RESOURCE;
4000 //only increment in the case of regular observing (not presence)
4001 incrementSequenceNumber(resPtr);
4002 method = OC_REST_OBSERVE;
4003 maxAge = MAX_OBSERVE_AGE;
4004 #ifdef WITH_PRESENCE
4005 result = SendAllObserverNotification (method, resPtr, maxAge,
4006 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4008 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4015 OCNotifyListOfObservers (OCResourceHandle handle,
4016 OCObservationId *obsIdList,
4017 uint8_t numberOfIds,
4018 const OCRepPayload *payload,
4019 OCQualityOfService qos)
4021 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4023 OCResource *resPtr = NULL;
4024 //TODO: we should allow the server to define this
4025 uint32_t maxAge = MAX_OBSERVE_AGE;
4027 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4028 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4029 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4031 resPtr = findResource ((OCResource *) handle);
4032 if (NULL == resPtr || myStackMode == OC_CLIENT)
4034 return OC_STACK_NO_RESOURCE;
4038 incrementSequenceNumber(resPtr);
4040 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4041 payload, maxAge, qos));
4044 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4046 OCStackResult result = OC_STACK_ERROR;
4047 OCServerRequest *serverRequest = NULL;
4049 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4051 // Validate input parameters
4052 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4053 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4056 // Get pointer to request info
4057 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4060 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4061 result = serverRequest->ehResponseHandler(ehResponse);
4067 //#ifdef DIRECT_PAIRING
4068 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4070 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4071 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4073 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4077 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4080 const OCDPDev_t* OCGetDirectPairedDevices()
4082 return (const OCDPDev_t*)DPGetPairedDevices();
4085 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4086 OCDirectPairingCB resultCallback)
4088 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4089 if(NULL == peer || NULL == pinNumber)
4091 OIC_LOG(ERROR, TAG, "Invalid parameters");
4092 return OC_STACK_INVALID_PARAM;
4094 if (NULL == resultCallback)
4096 OIC_LOG(ERROR, TAG, "Invalid callback");
4097 return OC_STACK_INVALID_CALLBACK;
4100 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4101 pinNumber, (OCDirectPairingResultCB)resultCallback);
4103 //#endif // DIRECT_PAIRING
4105 //-----------------------------------------------------------------------------
4106 // Private internal function definitions
4107 //-----------------------------------------------------------------------------
4108 static OCDoHandle GenerateInvocationHandle()
4110 OCDoHandle handle = NULL;
4111 // Generate token here, it will be deleted when the transaction is deleted
4112 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4115 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4121 #ifdef WITH_PRESENCE
4122 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4123 OCResourceProperty resourceProperties, uint8_t enable)
4127 return OC_STACK_INVALID_PARAM;
4129 if (resourceProperties
4130 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4132 OIC_LOG(ERROR, TAG, "Invalid property");
4133 return OC_STACK_INVALID_PARAM;
4137 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4141 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4147 OCStackResult initResources()
4149 OCStackResult result = OC_STACK_OK;
4151 headResource = NULL;
4152 tailResource = NULL;
4153 // Init Virtual Resources
4154 #ifdef WITH_PRESENCE
4155 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4157 result = OCCreateResource(&presenceResource.handle,
4158 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4160 OC_RSRVD_PRESENCE_URI,
4164 //make resource inactive
4165 result = OCChangeResourceProperty(
4166 &(((OCResource *) presenceResource.handle)->resourceProperties),
4169 #ifndef WITH_ARDUINO
4170 if (result == OC_STACK_OK)
4172 result = SRMInitSecureResources();
4176 if(result == OC_STACK_OK)
4178 CreateResetProfile();
4179 result = OCCreateResource(&deviceResource,
4180 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4181 OC_RSRVD_INTERFACE_DEFAULT,
4182 OC_RSRVD_DEVICE_URI,
4186 if(result == OC_STACK_OK)
4188 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4189 OC_RSRVD_INTERFACE_READ);
4193 if(result == OC_STACK_OK)
4195 result = OCCreateResource(&platformResource,
4196 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4197 OC_RSRVD_INTERFACE_DEFAULT,
4198 OC_RSRVD_PLATFORM_URI,
4202 if(result == OC_STACK_OK)
4204 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4205 OC_RSRVD_INTERFACE_READ);
4212 void insertResource(OCResource *resource)
4216 headResource = resource;
4217 tailResource = resource;
4221 tailResource->next = resource;
4222 tailResource = resource;
4224 resource->next = NULL;
4227 OCResource *findResource(OCResource *resource)
4229 OCResource *pointer = headResource;
4233 if (pointer == resource)
4237 pointer = pointer->next;
4242 void deleteAllResources()
4244 OCResource *pointer = headResource;
4245 OCResource *temp = NULL;
4249 temp = pointer->next;
4250 #ifdef WITH_PRESENCE
4251 if (pointer != (OCResource *) presenceResource.handle)
4253 #endif // WITH_PRESENCE
4254 deleteResource(pointer);
4255 #ifdef WITH_PRESENCE
4257 #endif // WITH_PRESENCE
4260 memset(&platformResource, 0, sizeof(platformResource));
4261 memset(&deviceResource, 0, sizeof(deviceResource));
4263 memset(&brokerResource, 0, sizeof(brokerResource));
4266 SRMDeInitSecureResources();
4268 #ifdef WITH_PRESENCE
4269 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4270 // presence notification attributed to their deletion to be processed.
4271 deleteResource((OCResource *) presenceResource.handle);
4272 memset(&presenceResource, 0, sizeof(presenceResource));
4273 #endif // WITH_PRESENCE
4276 OCStackResult deleteResource(OCResource *resource)
4278 OCResource *prev = NULL;
4279 OCResource *temp = NULL;
4282 OIC_LOG(DEBUG,TAG,"resource is NULL");
4283 return OC_STACK_INVALID_PARAM;
4286 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4288 temp = headResource;
4291 if (temp == resource)
4293 // Invalidate all Resource Properties.
4294 resource->resourceProperties = (OCResourceProperty) 0;
4295 #ifdef WITH_PRESENCE
4296 if(resource != (OCResource *) presenceResource.handle)
4298 #endif // WITH_PRESENCE
4299 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4300 #ifdef WITH_PRESENCE
4303 if(presenceResource.handle)
4305 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4306 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4309 // Only resource in list.
4310 if (temp == headResource && temp == tailResource)
4312 headResource = NULL;
4313 tailResource = NULL;
4316 else if (temp == headResource)
4318 headResource = temp->next;
4321 else if (temp == tailResource)
4323 tailResource = prev;
4324 tailResource->next = NULL;
4328 prev->next = temp->next;
4331 deleteResourceElements(temp);
4342 return OC_STACK_ERROR;
4345 void deleteResourceElements(OCResource *resource)
4352 OICFree(resource->uri);
4353 deleteResourceType(resource->rsrcType);
4354 deleteResourceInterface(resource->rsrcInterface);
4357 void deleteResourceType(OCResourceType *resourceType)
4359 OCResourceType *pointer = resourceType;
4360 OCResourceType *next = NULL;
4364 next = pointer->next;
4365 OICFree(pointer->resourcetypename);
4371 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4373 OCResourceInterface *pointer = resourceInterface;
4374 OCResourceInterface *next = NULL;
4378 next = pointer->next;
4379 OICFree(pointer->name);
4385 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4387 OCResourceType *pointer = NULL;
4388 OCResourceType *previous = NULL;
4389 if (!resource || !resourceType)
4393 // resource type list is empty.
4394 else if (!resource->rsrcType)
4396 resource->rsrcType = resourceType;
4400 pointer = resource->rsrcType;
4404 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4406 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4407 OICFree(resourceType->resourcetypename);
4408 OICFree(resourceType);
4412 pointer = pointer->next;
4417 previous->next = resourceType;
4420 resourceType->next = NULL;
4422 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4425 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4427 OCResource *resource = NULL;
4428 OCResourceType *pointer = NULL;
4430 // Find the specified resource
4431 resource = findResource((OCResource *) handle);
4437 // Make sure a resource has a resourcetype
4438 if (!resource->rsrcType)
4443 // Iterate through the list
4444 pointer = resource->rsrcType;
4445 for(uint8_t i = 0; i< index && pointer; ++i)
4447 pointer = pointer->next;
4452 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4454 if(resourceTypeList && resourceTypeName)
4456 OCResourceType * rtPointer = resourceTypeList;
4457 while(resourceTypeName && rtPointer)
4459 if(rtPointer->resourcetypename &&
4460 strcmp(resourceTypeName, (const char *)
4461 (rtPointer->resourcetypename)) == 0)
4465 rtPointer = rtPointer->next;
4473 * Insert a new interface into interface linked list only if not already present.
4474 * If alredy present, 2nd arg is free'd.
4475 * Default interface will always be first if present.
4477 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4479 OCResourceInterface *pointer = NULL;
4480 OCResourceInterface *previous = NULL;
4482 newInterface->next = NULL;
4484 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4486 if (!*firstInterface)
4488 // If first interface is not oic.if.baseline, by default add it as first interface type.
4489 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4491 *firstInterface = newInterface;
4495 OCStackResult result = BindResourceInterfaceToResource(resource,
4496 OC_RSRVD_INTERFACE_DEFAULT);
4497 if (result != OC_STACK_OK)
4499 OICFree(newInterface->name);
4500 OICFree(newInterface);
4503 if (*firstInterface)
4505 (*firstInterface)->next = newInterface;
4509 // If once add oic.if.baseline, later too below code take care of freeing memory.
4510 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4512 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4514 OICFree(newInterface->name);
4515 OICFree(newInterface);
4518 // This code will not hit anymore, keeping
4521 newInterface->next = *firstInterface;
4522 *firstInterface = newInterface;
4527 pointer = *firstInterface;
4530 if (strcmp(newInterface->name, pointer->name) == 0)
4532 OICFree(newInterface->name);
4533 OICFree(newInterface);
4537 pointer = pointer->next;
4542 previous->next = newInterface;
4547 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4550 OCResource *resource = NULL;
4551 OCResourceInterface *pointer = NULL;
4553 // Find the specified resource
4554 resource = findResource((OCResource *) handle);
4560 // Make sure a resource has a resourceinterface
4561 if (!resource->rsrcInterface)
4566 // Iterate through the list
4567 pointer = resource->rsrcInterface;
4569 for (uint8_t i = 0; i < index && pointer; ++i)
4571 pointer = pointer->next;
4577 * This function splits the uri using the '?' delimiter.
4578 * "uriWithoutQuery" is the block of characters between the beginning
4579 * till the delimiter or '\0' which ever comes first.
4580 * "query" is whatever is to the right of the delimiter if present.
4581 * No delimiter sets the query to NULL.
4582 * If either are present, they will be malloc'ed into the params 2, 3.
4583 * The first param, *uri is left untouched.
4585 * NOTE: This function does not account for whitespace at the end of the uri NOR
4586 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4587 * part of the query.
4589 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4593 return OC_STACK_INVALID_URI;
4595 if(!query || !uriWithoutQuery)
4597 return OC_STACK_INVALID_PARAM;
4601 *uriWithoutQuery = NULL;
4603 size_t uriWithoutQueryLen = 0;
4604 size_t queryLen = 0;
4605 size_t uriLen = strlen(uri);
4607 char *pointerToDelimiter = strstr(uri, "?");
4609 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4610 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4612 if (uriWithoutQueryLen)
4614 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4615 if (!*uriWithoutQuery)
4619 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4623 *query = (char *) OICCalloc(queryLen + 1, 1);
4626 OICFree(*uriWithoutQuery);
4627 *uriWithoutQuery = NULL;
4630 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4636 return OC_STACK_NO_MEMORY;
4639 static const OicUuid_t* OCGetServerInstanceID(void)
4641 static bool generated = false;
4642 static OicUuid_t sid;
4648 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4650 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4657 const char* OCGetServerInstanceIDString(void)
4659 static bool generated = false;
4660 static char sidStr[UUID_STRING_SIZE];
4667 const OicUuid_t *sid = OCGetServerInstanceID();
4668 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4670 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4678 CAResult_t OCSelectNetwork()
4680 CAResult_t retResult = CA_STATUS_FAILED;
4681 CAResult_t caResult = CA_STATUS_OK;
4683 CATransportAdapter_t connTypes[] = {
4685 CA_ADAPTER_RFCOMM_BTEDR,
4686 CA_ADAPTER_GATT_BTLE,
4689 ,CA_ADAPTER_REMOTE_ACCESS
4696 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4698 for(int i = 0; i<numConnTypes; i++)
4700 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4701 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4703 caResult = CASelectNetwork(connTypes[i]);
4704 if(caResult == CA_STATUS_OK)
4706 retResult = CA_STATUS_OK;
4711 if(retResult != CA_STATUS_OK)
4713 return caResult; // Returns error of appropriate transport that failed fatally.
4719 OCStackResult CAResultToOCResult(CAResult_t caResult)
4725 case CA_STATUS_INVALID_PARAM:
4726 return OC_STACK_INVALID_PARAM;
4727 case CA_ADAPTER_NOT_ENABLED:
4728 return OC_STACK_ADAPTER_NOT_ENABLED;
4729 case CA_SERVER_STARTED_ALREADY:
4731 case CA_SERVER_NOT_STARTED:
4732 return OC_STACK_ERROR;
4733 case CA_DESTINATION_NOT_REACHABLE:
4734 return OC_STACK_COMM_ERROR;
4735 case CA_SOCKET_OPERATION_FAILED:
4736 return OC_STACK_COMM_ERROR;
4737 case CA_SEND_FAILED:
4738 return OC_STACK_COMM_ERROR;
4739 case CA_RECEIVE_FAILED:
4740 return OC_STACK_COMM_ERROR;
4741 case CA_MEMORY_ALLOC_FAILED:
4742 return OC_STACK_NO_MEMORY;
4743 case CA_REQUEST_TIMEOUT:
4744 return OC_STACK_TIMEOUT;
4745 case CA_DESTINATION_DISCONNECTED:
4746 return OC_STACK_COMM_ERROR;
4747 case CA_STATUS_FAILED:
4748 return OC_STACK_ERROR;
4749 case CA_NOT_SUPPORTED:
4750 return OC_STACK_NOTIMPL;
4752 return OC_STACK_ERROR;
4756 bool OCResultToSuccess(OCStackResult ocResult)
4761 case OC_STACK_RESOURCE_CREATED:
4762 case OC_STACK_RESOURCE_DELETED:
4763 case OC_STACK_CONTINUE:
4764 case OC_STACK_RESOURCE_CHANGED:
4771 #if defined(RD_CLIENT) || defined(RD_SERVER)
4772 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
4774 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4776 OCResource *resource = NULL;
4778 resource = findResource((OCResource *) handle);
4781 OIC_LOG(ERROR, TAG, "Resource not found");
4782 return OC_STACK_ERROR;
4785 resource->ins = ins;
4790 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
4794 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
4798 OCResource *pointer = headResource;
4802 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
4804 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
4807 pointer = pointer->next;
4812 OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
4814 OCResource *resource = NULL;
4816 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4817 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
4819 resource = findResource((OCResource *) handle);
4822 *ins = resource->ins;
4825 return OC_STACK_ERROR;