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 = -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 response.sequenceNumber <= cbNode->sequenceNumber)
1423 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1424 response.sequenceNumber);
1428 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1431 cbNode->sequenceNumber = response.sequenceNumber;
1433 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1435 FindAndDeleteClientCB(cbNode);
1439 // To keep discovery callbacks active.
1440 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1441 MILLISECONDS_PER_SECOND);
1445 //Need to send ACK when the response is CON
1446 if(responseInfo->info.type == CA_MSG_CONFIRM)
1448 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1449 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1452 OCPayloadDestroy(response.payload);
1459 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1460 if(responseInfo->result == CA_EMPTY)
1462 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1463 if(responseInfo->info.type == CA_MSG_RESET)
1465 OIC_LOG(INFO, TAG, "This is a RESET");
1466 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1467 OC_OBSERVER_NOT_INTERESTED);
1469 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1471 OIC_LOG(INFO, TAG, "This is a pure ACK");
1472 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1473 OC_OBSERVER_STILL_INTERESTED);
1476 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1478 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1479 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1480 OC_OBSERVER_FAILED_COMM);
1485 if(!cbNode && !observer)
1487 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1488 || myStackMode == OC_GATEWAY)
1490 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1491 if(responseInfo->result == CA_EMPTY)
1493 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1497 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1498 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1499 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1503 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1504 || myStackMode == OC_GATEWAY)
1506 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1507 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1509 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1510 responseInfo->info.messageId);
1512 if (responseInfo->info.type == CA_MSG_RESET)
1514 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1515 responseInfo->info.messageId);
1522 OIC_LOG(INFO, TAG, "Exit OCHandleResponse");
1525 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1527 VERIFY_NON_NULL_NR(endPoint, FATAL);
1528 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1530 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1532 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1533 #ifdef ROUTING_GATEWAY
1534 bool needRIHandling = false;
1536 * Routing manager is going to update either of endpoint or response or both.
1537 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1538 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1541 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1543 if(ret != OC_STACK_OK || !needRIHandling)
1545 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1551 * Put source in sender endpoint so that the next packet from application can be routed to
1552 * proper destination and remove "RM" coap header option before passing request / response to
1553 * RI as this option will make no sense to either RI or application.
1555 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1556 (uint8_t *) &(responseInfo->info.numOptions),
1557 (CAEndpoint_t *) endPoint);
1560 OCHandleResponse(endPoint, responseInfo);
1562 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1566 * This function handles error response from CA
1567 * code shall be added to handle the errors
1569 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1571 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1573 if (NULL == endPoint)
1575 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1579 if (NULL == errorInfo)
1581 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1585 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1586 errorInfo->info.tokenLength, NULL, NULL);
1589 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1590 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1591 FixUpClientResponse(&response);
1592 response.resourceUri = errorInfo->info.resourceUri;
1593 memcpy(response.identity.id, errorInfo->info.identity.id,
1594 sizeof (response.identity.id));
1595 response.identity.id_length = errorInfo->info.identity.id_length;
1596 response.result = CAResultToOCStackResult(errorInfo->result);
1598 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1599 FindAndDeleteClientCB(cbNode);
1602 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1606 * This function sends out Direct Stack Responses. These are responses that are not coming
1607 * from the application entity handler. These responses have no payload and are usually ACKs,
1608 * RESETs or some error conditions that were caught by the stack.
1610 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1611 const CAResponseResult_t responseResult, const CAMessageType_t type,
1612 const uint8_t numOptions, const CAHeaderOption_t *options,
1613 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1615 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1616 CAResponseInfo_t respInfo = {
1617 .result = responseResult
1619 respInfo.info.messageId = coapID;
1620 respInfo.info.numOptions = numOptions;
1622 if (respInfo.info.numOptions)
1624 respInfo.info.options =
1625 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1626 memcpy (respInfo.info.options, options,
1627 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1631 respInfo.info.payload = NULL;
1632 respInfo.info.token = token;
1633 respInfo.info.tokenLength = tokenLength;
1634 respInfo.info.type = type;
1635 respInfo.info.resourceUri = OICStrdup (resourceUri);
1636 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1638 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1639 // Add the destination to route option from the endpoint->routeData.
1640 bool doPost = false;
1641 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1642 if(OC_STACK_OK != result)
1644 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1649 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1650 CARequestInfo_t reqInfo = {.method = CA_POST };
1651 /* The following initialization is not done in a single initializer block as in
1652 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1653 * does not have designated initalizers. This is a work-around for now.
1655 reqInfo.info.type = CA_MSG_NONCONFIRM;
1656 reqInfo.info.messageId = coapID;
1657 reqInfo.info.tokenLength = tokenLength;
1658 reqInfo.info.token = token;
1659 reqInfo.info.numOptions = respInfo.info.numOptions;
1660 reqInfo.info.payload = NULL;
1661 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1662 if (reqInfo.info.numOptions)
1664 reqInfo.info.options =
1665 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1666 if (NULL == reqInfo.info.options)
1668 OIC_LOG(ERROR, TAG, "Calloc failed");
1669 return OC_STACK_NO_MEMORY;
1671 memcpy (reqInfo.info.options, respInfo.info.options,
1672 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1675 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1676 OICFree (reqInfo.info.resourceUri);
1677 OICFree (reqInfo.info.options);
1678 OICFree (respInfo.info.resourceUri);
1679 OICFree (respInfo.info.options);
1680 if (CA_STATUS_OK != caResult)
1682 OIC_LOG(ERROR, TAG, "CASendRequest error");
1683 return CAResultToOCResult(caResult);
1689 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1691 // resourceUri in the info field is cloned in the CA layer and
1692 // thus ownership is still here.
1693 OICFree (respInfo.info.resourceUri);
1694 OICFree (respInfo.info.options);
1695 if(CA_STATUS_OK != caResult)
1697 OIC_LOG(ERROR, TAG, "CASendResponse error");
1698 return CAResultToOCResult(caResult);
1701 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1705 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1707 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1708 OCStackResult result = OC_STACK_ERROR;
1709 if(!protocolRequest)
1711 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1712 return OC_STACK_INVALID_PARAM;
1715 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1716 protocolRequest->tokenLength);
1719 OIC_LOG(INFO, TAG, "This is a new Server Request");
1720 result = AddServerRequest(&request, protocolRequest->coapID,
1721 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1722 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1723 protocolRequest->observationOption, protocolRequest->qos,
1724 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1725 protocolRequest->payload, protocolRequest->requestToken,
1726 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1727 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1728 &protocolRequest->devAddr);
1729 if (OC_STACK_OK != result)
1731 OIC_LOG(ERROR, TAG, "Error adding server request");
1737 OIC_LOG(ERROR, TAG, "Out of Memory");
1738 return OC_STACK_NO_MEMORY;
1741 if(!protocolRequest->reqMorePacket)
1743 request->requestComplete = 1;
1748 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1751 if(request->requestComplete)
1753 OIC_LOG(INFO, TAG, "This Server Request is complete");
1754 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1755 OCResource *resource = NULL;
1756 result = DetermineResourceHandling (request, &resHandling, &resource);
1757 if (result == OC_STACK_OK)
1759 result = ProcessRequest(resHandling, resource, request);
1764 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1765 result = OC_STACK_CONTINUE;
1770 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1772 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1775 if (requestInfo->info.resourceUri &&
1776 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1778 HandleKeepAliveRequest(endPoint, requestInfo);
1783 OCStackResult requestResult = OC_STACK_ERROR;
1785 if(myStackMode == OC_CLIENT)
1787 //TODO: should the client be responding to requests?
1791 OCServerProtocolRequest serverRequest = {0};
1793 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1795 char * uriWithoutQuery = NULL;
1796 char * query = NULL;
1798 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1800 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1802 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1805 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1806 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1808 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1810 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1811 OICFree(uriWithoutQuery);
1815 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1816 OICFree(uriWithoutQuery);
1823 if(strlen(query) < MAX_QUERY_LENGTH)
1825 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1830 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1836 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1838 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1839 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1840 if (!serverRequest.payload)
1842 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1845 memcpy (serverRequest.payload, requestInfo->info.payload,
1846 requestInfo->info.payloadSize);
1850 serverRequest.reqTotalSize = 0;
1853 switch (requestInfo->method)
1856 serverRequest.method = OC_REST_GET;
1859 serverRequest.method = OC_REST_PUT;
1862 serverRequest.method = OC_REST_POST;
1865 serverRequest.method = OC_REST_DELETE;
1868 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1869 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1870 requestInfo->info.type, requestInfo->info.numOptions,
1871 requestInfo->info.options, requestInfo->info.token,
1872 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1873 OICFree(serverRequest.payload);
1877 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1878 requestInfo->info.tokenLength);
1880 serverRequest.tokenLength = requestInfo->info.tokenLength;
1881 if (serverRequest.tokenLength) {
1883 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1885 if (!serverRequest.requestToken)
1887 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1888 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1889 requestInfo->info.type, requestInfo->info.numOptions,
1890 requestInfo->info.options, requestInfo->info.token,
1891 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1892 OICFree(serverRequest.payload);
1895 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1898 switch (requestInfo->info.acceptFormat)
1900 case CA_FORMAT_APPLICATION_CBOR:
1901 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1903 case CA_FORMAT_UNDEFINED:
1904 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1907 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1910 if (requestInfo->info.type == CA_MSG_CONFIRM)
1912 serverRequest.qos = OC_HIGH_QOS;
1916 serverRequest.qos = OC_LOW_QOS;
1918 // CA does not need the following field
1919 // Are we sure CA does not need them? how is it responding to multicast
1920 serverRequest.delayedResNeeded = 0;
1922 serverRequest.coapID = requestInfo->info.messageId;
1924 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1926 // copy vendor specific header options
1927 uint8_t tempNum = (requestInfo->info.numOptions);
1929 // Assume no observation requested and it is a pure GET.
1930 // If obs registration/de-registration requested it'll be fetched from the
1931 // options in GetObserveHeaderOption()
1932 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1934 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1935 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1938 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1939 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1940 requestInfo->info.type, requestInfo->info.numOptions,
1941 requestInfo->info.options, requestInfo->info.token,
1942 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1943 OICFree(serverRequest.payload);
1944 OICFree(serverRequest.requestToken);
1947 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1948 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1950 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1951 sizeof(CAHeaderOption_t)*tempNum);
1954 requestResult = HandleStackRequests (&serverRequest);
1956 // Send ACK to client as precursor to slow response
1957 if (requestResult == OC_STACK_SLOW_RESOURCE)
1959 if (requestInfo->info.type == CA_MSG_CONFIRM)
1961 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1962 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1965 else if(!OCResultToSuccess(requestResult))
1967 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1969 CAResponseResult_t stackResponse =
1970 OCToCAStackResult(requestResult, serverRequest.method);
1972 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1973 requestInfo->info.type, requestInfo->info.numOptions,
1974 requestInfo->info.options, requestInfo->info.token,
1975 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1977 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1978 // The token is copied in there, and is thus still owned by this function.
1979 OICFree(serverRequest.payload);
1980 OICFree(serverRequest.requestToken);
1981 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1984 //This function will be called back by CA layer when a request is received
1985 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1987 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1990 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1996 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2000 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2001 #ifdef ROUTING_GATEWAY
2002 bool needRIHandling = false;
2003 bool isEmptyMsg = false;
2005 * Routing manager is going to update either of endpoint or request or both.
2006 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2007 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2008 * destination. It can also remove "RM" coap header option before passing request / response to
2009 * RI as this option will make no sense to either RI or application.
2011 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2012 &needRIHandling, &isEmptyMsg);
2013 if(OC_STACK_OK != ret || !needRIHandling)
2015 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2021 * Put source in sender endpoint so that the next packet from application can be routed to
2022 * proper destination and remove RM header option.
2024 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2025 (uint8_t *) &(requestInfo->info.numOptions),
2026 (CAEndpoint_t *) endPoint);
2028 #ifdef ROUTING_GATEWAY
2032 * In Gateways, the MSGType in route option is used to check if the actual
2033 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2034 * EMPTY response is sent in the form of POST request which need to be changed
2035 * to a EMPTY response by RM. This translation is done in this part of the code.
2037 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2038 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2039 .info.messageId = requestInfo->info.messageId,
2040 .info.type = CA_MSG_ACKNOWLEDGE};
2041 OCHandleResponse(endPoint, &respInfo);
2047 // Normal handling of the packet
2048 OCHandleRequests(endPoint, requestInfo);
2050 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2053 bool validatePlatformInfo(OCPlatformInfo info)
2056 if (!info.platformID)
2058 OIC_LOG(ERROR, TAG, "No platform ID found.");
2062 if (info.manufacturerName)
2064 size_t lenManufacturerName = strlen(info.manufacturerName);
2066 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2068 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2074 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2078 if (info.manufacturerUrl)
2080 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2082 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2089 //-----------------------------------------------------------------------------
2091 //-----------------------------------------------------------------------------
2093 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2096 !raInfo->username ||
2097 !raInfo->hostname ||
2098 !raInfo->xmpp_domain)
2101 return OC_STACK_INVALID_PARAM;
2103 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2104 gRASetInfo = (result == OC_STACK_OK)? true : false;
2110 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2114 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2117 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2119 if(stackState == OC_STACK_INITIALIZED)
2121 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2122 OCStop() between them are ignored.");
2126 #ifndef ROUTING_GATEWAY
2127 if (OC_GATEWAY == mode)
2129 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2130 return OC_STACK_INVALID_PARAM;
2137 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2138 return OC_STACK_ERROR;
2142 OCStackResult result = OC_STACK_ERROR;
2143 OIC_LOG(INFO, TAG, "Entering OCInit");
2146 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2147 || (mode == OC_GATEWAY)))
2149 OIC_LOG(ERROR, TAG, "Invalid mode");
2150 return OC_STACK_ERROR;
2154 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2156 caglobals.client = true;
2158 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2160 caglobals.server = true;
2163 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2164 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2166 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2168 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2169 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2171 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2174 defaultDeviceHandler = NULL;
2175 defaultDeviceHandlerCallbackParameter = NULL;
2177 result = CAResultToOCResult(CAInitialize());
2178 VERIFY_SUCCESS(result, OC_STACK_OK);
2180 result = CAResultToOCResult(OCSelectNetwork());
2181 VERIFY_SUCCESS(result, OC_STACK_OK);
2183 switch (myStackMode)
2186 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2187 result = CAResultToOCResult(CAStartDiscoveryServer());
2188 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2191 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2192 result = CAResultToOCResult(CAStartListeningServer());
2193 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2195 case OC_CLIENT_SERVER:
2197 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2198 result = CAResultToOCResult(CAStartListeningServer());
2199 if(result == OC_STACK_OK)
2201 result = CAResultToOCResult(CAStartDiscoveryServer());
2205 VERIFY_SUCCESS(result, OC_STACK_OK);
2208 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2211 #ifdef WITH_PRESENCE
2212 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2213 #endif // WITH_PRESENCE
2215 //Update Stack state to initialized
2216 stackState = OC_STACK_INITIALIZED;
2218 // Initialize resource
2219 if(myStackMode != OC_CLIENT)
2221 result = initResources();
2224 // Initialize the SRM Policy Engine
2225 if(result == OC_STACK_OK)
2227 result = SRMInitPolicyEngine();
2228 // TODO after BeachHead delivery: consolidate into single SRMInit()
2230 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2231 RMSetStackMode(mode);
2232 #ifdef ROUTING_GATEWAY
2233 if (OC_GATEWAY == myStackMode)
2235 result = RMInitialize();
2241 if (result == OC_STACK_OK)
2243 result = InitializeKeepAlive(myStackMode);
2248 if(result != OC_STACK_OK)
2250 OIC_LOG(ERROR, TAG, "Stack initialization error");
2251 deleteAllResources();
2253 stackState = OC_STACK_UNINITIALIZED;
2258 OCStackResult OCStop()
2260 OIC_LOG(INFO, TAG, "Entering OCStop");
2262 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2264 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2267 else if (stackState != OC_STACK_INITIALIZED)
2269 OIC_LOG(ERROR, TAG, "Stack not initialized");
2270 return OC_STACK_ERROR;
2273 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2275 #ifdef WITH_PRESENCE
2276 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2277 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2278 presenceResource.presenceTTL = 0;
2279 #endif // WITH_PRESENCE
2281 #ifdef ROUTING_GATEWAY
2282 if (OC_GATEWAY == myStackMode)
2289 TerminateKeepAlive(myStackMode);
2292 // Free memory dynamically allocated for resources
2293 deleteAllResources();
2295 DeletePlatformInfo();
2297 // Remove all observers
2298 DeleteObserverList();
2299 // Remove all the client callbacks
2300 DeleteClientCBList();
2302 // De-init the SRM Policy Engine
2303 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2304 SRMDeInitPolicyEngine();
2307 stackState = OC_STACK_UNINITIALIZED;
2311 OCStackResult OCStartMulticastServer()
2313 if(stackState != OC_STACK_INITIALIZED)
2315 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2316 return OC_STACK_ERROR;
2318 CAResult_t ret = CAStartListeningServer();
2319 if (CA_STATUS_OK != ret)
2321 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2322 return OC_STACK_ERROR;
2327 OCStackResult OCStopMulticastServer()
2329 CAResult_t ret = CAStopListeningServer();
2330 if (CA_STATUS_OK != ret)
2332 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2333 return OC_STACK_ERROR;
2338 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2343 return CA_MSG_CONFIRM;
2348 return CA_MSG_NONCONFIRM;
2353 * A request uri consists of the following components in order:
2356 * CoAP over UDP prefix "coap://"
2357 * CoAP over TCP prefix "coap+tcp://"
2359 * IPv6 address "[1234::5678]"
2360 * IPv4 address "192.168.1.1"
2361 * optional port ":5683"
2362 * resource uri "/oc/core..."
2364 * for PRESENCE requests, extract resource type.
2366 static OCStackResult ParseRequestUri(const char *fullUri,
2367 OCTransportAdapter adapter,
2368 OCTransportFlags flags,
2369 OCDevAddr **devAddr,
2371 char **resourceType)
2373 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2375 OCStackResult result = OC_STACK_OK;
2376 OCDevAddr *da = NULL;
2380 // provide defaults for all returned values
2387 *resourceUri = NULL;
2391 *resourceType = NULL;
2394 // delimit url prefix, if any
2395 const char *start = fullUri;
2396 char *slash2 = strstr(start, "//");
2401 char *slash = strchr(start, '/');
2404 return OC_STACK_INVALID_URI;
2407 // process url scheme
2408 size_t prefixLen = slash2 - fullUri;
2412 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2418 // TODO: this logic should come in with unit tests exercising the various strings
2419 // processs url prefix, if any
2420 size_t urlLen = slash - start;
2424 if (urlLen && devAddr)
2425 { // construct OCDevAddr
2426 if (start[0] == '[')
2428 char *close = strchr(++start, ']');
2429 if (!close || close > slash)
2431 return OC_STACK_INVALID_URI;
2434 if (close[1] == ':')
2441 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2445 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2447 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2451 char *dot = strchr(start, '.');
2452 if (dot && dot < slash)
2454 colon = strchr(start, ':');
2455 end = (colon && colon < slash) ? colon : slash;
2460 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2464 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2466 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2474 if (len >= sizeof(da->addr))
2476 return OC_STACK_INVALID_URI;
2478 // collect port, if any
2479 if (colon && colon < slash)
2481 for (colon++; colon < slash; colon++)
2484 if (c < '0' || c > '9')
2486 return OC_STACK_INVALID_URI;
2488 port = 10 * port + c - '0';
2493 if (len >= sizeof(da->addr))
2495 return OC_STACK_INVALID_URI;
2498 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2501 return OC_STACK_NO_MEMORY;
2503 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2505 da->adapter = adapter;
2507 if (!strncmp(fullUri, "coaps:", 6))
2509 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2514 // process resource uri, if any
2516 { // request uri and query
2517 size_t ulen = strlen(slash); // resource uri length
2518 size_t tlen = 0; // resource type length
2521 static const char strPresence[] = "/oic/ad?rt=";
2522 static const size_t lenPresence = sizeof(strPresence) - 1;
2523 if (!strncmp(slash, strPresence, lenPresence))
2525 type = slash + lenPresence;
2526 tlen = ulen - lenPresence;
2531 *resourceUri = (char *)OICMalloc(ulen + 1);
2534 result = OC_STACK_NO_MEMORY;
2537 strcpy(*resourceUri, slash);
2540 if (type && resourceType)
2542 *resourceType = (char *)OICMalloc(tlen + 1);
2545 result = OC_STACK_NO_MEMORY;
2549 OICStrcpy(*resourceType, (tlen+1), type);
2556 // free all returned values
2563 OICFree(*resourceUri);
2567 OICFree(*resourceType);
2572 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2573 char *resourceUri, char **requestUri)
2575 char uri[CA_MAX_URI_LENGTH];
2577 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2579 *requestUri = OICStrdup(uri);
2582 return OC_STACK_NO_MEMORY;
2589 * Discover or Perform requests on a specified resource
2591 OCStackResult OCDoResource(OCDoHandle *handle,
2593 const char *requestUri,
2594 const OCDevAddr *destination,
2596 OCConnectivityType connectivityType,
2597 OCQualityOfService qos,
2598 OCCallbackData *cbData,
2599 OCHeaderOption *options,
2602 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2604 // Validate input parameters
2605 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2606 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2607 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2609 OCStackResult result = OC_STACK_ERROR;
2610 CAResult_t caResult;
2611 CAToken_t token = NULL;
2612 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2613 ClientCB *clientCB = NULL;
2614 OCDoHandle resHandle = NULL;
2615 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2616 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2618 OCTransportAdapter adapter;
2619 OCTransportFlags flags;
2620 // the request contents are put here
2621 CARequestInfo_t requestInfo = {.method = CA_GET};
2622 // requestUri will be parsed into the following three variables
2623 OCDevAddr *devAddr = NULL;
2624 char *resourceUri = NULL;
2625 char *resourceType = NULL;
2628 * Support original behavior with address on resourceUri argument.
2630 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2631 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2633 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2635 if (result != OC_STACK_OK)
2637 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2644 case OC_REST_OBSERVE:
2645 case OC_REST_OBSERVE_ALL:
2646 case OC_REST_CANCEL_OBSERVE:
2647 requestInfo.method = CA_GET;
2650 requestInfo.method = CA_PUT;
2653 requestInfo.method = CA_POST;
2655 case OC_REST_DELETE:
2656 requestInfo.method = CA_DELETE;
2658 case OC_REST_DISCOVER:
2660 if (destination || devAddr)
2662 requestInfo.isMulticast = false;
2666 tmpDevAddr.adapter = adapter;
2667 tmpDevAddr.flags = flags;
2668 destination = &tmpDevAddr;
2669 requestInfo.isMulticast = true;
2671 // CA_DISCOVER will become GET and isMulticast
2672 requestInfo.method = CA_GET;
2674 #ifdef WITH_PRESENCE
2675 case OC_REST_PRESENCE:
2676 // Replacing method type with GET because "presence"
2677 // is a stack layer only implementation.
2678 requestInfo.method = CA_GET;
2682 result = OC_STACK_INVALID_METHOD;
2686 if (!devAddr && !destination)
2688 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2689 result = OC_STACK_INVALID_PARAM;
2693 /* If not original behavior, use destination argument */
2694 if (destination && !devAddr)
2696 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2699 result = OC_STACK_NO_MEMORY;
2702 *devAddr = *destination;
2705 resHandle = GenerateInvocationHandle();
2708 result = OC_STACK_NO_MEMORY;
2712 caResult = CAGenerateToken(&token, tokenLength);
2713 if (caResult != CA_STATUS_OK)
2715 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2716 result= OC_STACK_ERROR;
2720 // fill in request data
2721 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2722 requestInfo.info.token = token;
2723 requestInfo.info.tokenLength = tokenLength;
2724 requestInfo.info.resourceUri = resourceUri;
2726 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2728 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2729 options, numOptions, OC_OBSERVE_REGISTER);
2730 if (result != OC_STACK_OK)
2734 requestInfo.info.numOptions = numOptions + 1;
2738 requestInfo.info.numOptions = numOptions;
2739 requestInfo.info.options =
2740 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2741 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2742 numOptions * sizeof(CAHeaderOption_t));
2745 CopyDevAddrToEndpoint(devAddr, &endpoint);
2750 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2753 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2756 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2760 requestInfo.info.payload = NULL;
2761 requestInfo.info.payloadSize = 0;
2762 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2765 // prepare for response
2766 #ifdef WITH_PRESENCE
2767 if (method == OC_REST_PRESENCE)
2769 char *presenceUri = NULL;
2770 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2771 if (OC_STACK_OK != result)
2776 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2777 // Presence notification will form a canonical uri to
2778 // look for callbacks into the application.
2779 resourceUri = presenceUri;
2783 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2784 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2785 method, devAddr, resourceUri, resourceType, ttl);
2786 if (OC_STACK_OK != result)
2791 devAddr = NULL; // Client CB list entry now owns it
2792 resourceUri = NULL; // Client CB list entry now owns it
2793 resourceType = NULL; // Client CB list entry now owns it
2796 result = OCSendRequest(&endpoint, &requestInfo);
2797 if (OC_STACK_OK != result)
2804 *handle = resHandle;
2808 if (result != OC_STACK_OK)
2810 OIC_LOG(ERROR, TAG, "OCDoResource error");
2811 FindAndDeleteClientCB(clientCB);
2812 CADestroyToken(token);
2820 // This is the owner of the payload object, so we free it
2821 OCPayloadDestroy(payload);
2822 OICFree(requestInfo.info.payload);
2824 OICFree(resourceUri);
2825 OICFree(resourceType);
2826 OICFree(requestInfo.info.options);
2830 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2834 * This ftn is implemented one of two ways in the case of observation:
2836 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2837 * Remove the callback associated on client side.
2838 * When the next notification comes in from server,
2839 * reply with RESET message to server.
2840 * Keep in mind that the server will react to RESET only
2841 * if the last notification was sent as CON
2843 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2844 * and it is associated with an observe request
2845 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2846 * Send CON Observe request to server with
2847 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2848 * Remove the callback associated on client side.
2850 OCStackResult ret = OC_STACK_OK;
2851 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2852 CARequestInfo_t requestInfo = {.method = CA_GET};
2856 return OC_STACK_INVALID_PARAM;
2859 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2862 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2863 return OC_STACK_ERROR;
2866 switch (clientCB->method)
2868 case OC_REST_OBSERVE:
2869 case OC_REST_OBSERVE_ALL:
2871 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2873 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2875 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2877 FindAndDeleteClientCB(clientCB);
2881 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2883 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2884 requestInfo.info.token = clientCB->token;
2885 requestInfo.info.tokenLength = clientCB->tokenLength;
2887 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2888 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2890 return OC_STACK_ERROR;
2892 requestInfo.info.numOptions = numOptions + 1;
2893 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2896 ret = OCSendRequest(&endpoint, &requestInfo);
2898 if (requestInfo.info.options)
2900 OICFree (requestInfo.info.options);
2902 if (requestInfo.info.resourceUri)
2904 OICFree (requestInfo.info.resourceUri);
2909 case OC_REST_DISCOVER:
2910 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2911 clientCB->requestUri);
2912 FindAndDeleteClientCB(clientCB);
2915 #ifdef WITH_PRESENCE
2916 case OC_REST_PRESENCE:
2917 FindAndDeleteClientCB(clientCB);
2922 ret = OC_STACK_INVALID_METHOD;
2930 * @brief Register Persistent storage callback.
2931 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2933 * OC_STACK_OK - No errors; Success
2934 * OC_STACK_INVALID_PARAM - Invalid parameter
2936 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2938 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2939 if(!persistentStorageHandler)
2941 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2942 return OC_STACK_INVALID_PARAM;
2946 if( !persistentStorageHandler->open ||
2947 !persistentStorageHandler->close ||
2948 !persistentStorageHandler->read ||
2949 !persistentStorageHandler->unlink ||
2950 !persistentStorageHandler->write)
2952 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2953 return OC_STACK_INVALID_PARAM;
2956 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2959 #ifdef WITH_PRESENCE
2961 OCStackResult OCProcessPresence()
2963 OCStackResult result = OC_STACK_OK;
2965 // the following line floods the log with messages that are irrelevant
2966 // to most purposes. Uncomment as needed.
2967 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2968 ClientCB* cbNode = NULL;
2969 OCClientResponse clientResponse;
2970 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2972 LL_FOREACH(cbList, cbNode)
2974 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2979 uint32_t now = GetTicks(0);
2980 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2981 cbNode->presence->TTLlevel);
2982 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2984 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2989 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2991 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2992 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2994 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2996 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2998 clientResponse.sequenceNumber = 0;
2999 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3000 clientResponse.devAddr = *cbNode->devAddr;
3001 FixUpClientResponse(&clientResponse);
3002 clientResponse.payload = NULL;
3004 // Increment the TTLLevel (going to a next state), so we don't keep
3005 // sending presence notification to client.
3006 cbNode->presence->TTLlevel++;
3007 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3008 cbNode->presence->TTLlevel);
3010 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3011 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3013 FindAndDeleteClientCB(cbNode);
3017 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3022 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3023 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3024 CARequestInfo_t requestInfo = {.method = CA_GET};
3026 OIC_LOG(DEBUG, TAG, "time to test server presence");
3028 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3030 requestData.type = CA_MSG_NONCONFIRM;
3031 requestData.token = cbNode->token;
3032 requestData.tokenLength = cbNode->tokenLength;
3033 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3034 requestInfo.method = CA_GET;
3035 requestInfo.info = requestData;
3037 result = OCSendRequest(&endpoint, &requestInfo);
3038 if (OC_STACK_OK != result)
3043 cbNode->presence->TTLlevel++;
3044 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3047 if (result != OC_STACK_OK)
3049 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3054 #endif // WITH_PRESENCE
3056 OCStackResult OCProcess()
3058 #ifdef WITH_PRESENCE
3059 OCProcessPresence();
3061 CAHandleRequestResponse();
3063 #ifdef ROUTING_GATEWAY
3073 #ifdef WITH_PRESENCE
3074 OCStackResult OCStartPresence(const uint32_t ttl)
3076 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3077 OCChangeResourceProperty(
3078 &(((OCResource *)presenceResource.handle)->resourceProperties),
3081 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3083 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3084 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3088 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3089 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3093 presenceResource.presenceTTL = ttl;
3095 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3097 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3099 presenceState = OC_PRESENCE_INITIALIZED;
3101 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3103 CAToken_t caToken = NULL;
3104 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3105 if (caResult != CA_STATUS_OK)
3107 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3108 CADestroyToken(caToken);
3109 return OC_STACK_ERROR;
3112 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3113 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3114 CADestroyToken(caToken);
3117 // Each time OCStartPresence is called
3118 // a different random 32-bit integer number is used
3119 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3121 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3122 OC_PRESENCE_TRIGGER_CREATE);
3125 OCStackResult OCStopPresence()
3127 OCStackResult result = OC_STACK_ERROR;
3129 if(presenceResource.handle)
3131 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3133 // make resource inactive
3134 result = OCChangeResourceProperty(
3135 &(((OCResource *) presenceResource.handle)->resourceProperties),
3139 if(result != OC_STACK_OK)
3142 "Changing the presence resource properties to ACTIVE not successful");
3146 return SendStopNotification();
3150 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3151 void* callbackParameter)
3153 defaultDeviceHandler = entityHandler;
3154 defaultDeviceHandlerCallbackParameter = callbackParameter;
3159 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3161 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3163 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3165 if (validatePlatformInfo(platformInfo))
3167 return SavePlatformInfo(platformInfo);
3171 return OC_STACK_INVALID_PARAM;
3176 return OC_STACK_ERROR;
3180 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3182 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3184 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3186 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3187 return OC_STACK_INVALID_PARAM;
3190 if (deviceInfo.types)
3192 OCStringLL *type = deviceInfo.types;
3193 OCResource *resource = findResource((OCResource *) deviceResource);
3196 return OC_STACK_INVALID_PARAM;
3201 OCBindResourceTypeToResource(deviceResource, type->value);
3205 return SaveDeviceInfo(deviceInfo);
3208 OCStackResult OCCreateResource(OCResourceHandle *handle,
3209 const char *resourceTypeName,
3210 const char *resourceInterfaceName,
3211 const char *uri, OCEntityHandler entityHandler,
3212 void* callbackParam,
3213 uint8_t resourceProperties)
3216 OCResource *pointer = NULL;
3217 OCStackResult result = OC_STACK_ERROR;
3219 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3221 if(myStackMode == OC_CLIENT)
3223 return OC_STACK_INVALID_PARAM;
3225 // Validate parameters
3226 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3228 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3229 return OC_STACK_INVALID_URI;
3231 // Is it presented during resource discovery?
3232 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3234 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3235 return OC_STACK_INVALID_PARAM;
3238 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3240 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3244 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3246 // Make sure resourceProperties bitmask has allowed properties specified
3247 if (resourceProperties
3248 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3249 OC_EXPLICIT_DISCOVERABLE
3258 OIC_LOG(ERROR, TAG, "Invalid property");
3259 return OC_STACK_INVALID_PARAM;
3262 // If the headResource is NULL, then no resources have been created...
3263 pointer = headResource;
3266 // At least one resources is in the resource list, so we need to search for
3267 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3270 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3272 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3273 return OC_STACK_INVALID_PARAM;
3275 pointer = pointer->next;
3278 // Create the pointer and insert it into the resource list
3279 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3282 result = OC_STACK_NO_MEMORY;
3285 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3287 insertResource(pointer);
3290 pointer->uri = OICStrdup(uri);
3293 result = OC_STACK_NO_MEMORY;
3297 // Set properties. Set OC_ACTIVE
3298 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3301 // Add the resourcetype to the resource
3302 result = BindResourceTypeToResource(pointer, resourceTypeName);
3303 if (result != OC_STACK_OK)
3305 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3309 // Add the resourceinterface to the resource
3310 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3311 if (result != OC_STACK_OK)
3313 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3317 // If an entity handler has been passed, attach it to the newly created
3318 // resource. Otherwise, set the default entity handler.
3321 pointer->entityHandler = entityHandler;
3322 pointer->entityHandlerCallbackParam = callbackParam;
3326 pointer->entityHandler = defaultResourceEHandler;
3327 pointer->entityHandlerCallbackParam = NULL;
3330 // Initialize a pointer indicating child resources in case of collection
3331 pointer->rsrcChildResourcesHead = NULL;
3334 result = OC_STACK_OK;
3336 #ifdef WITH_PRESENCE
3337 if (presenceResource.handle)
3339 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3340 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3344 if (result != OC_STACK_OK)
3346 // Deep delete of resource and other dynamic elements that it contains
3347 deleteResource(pointer);
3352 OCStackResult OCBindResource(
3353 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3355 OCResource *resource = NULL;
3356 OCChildResource *tempChildResource = NULL;
3357 OCChildResource *newChildResource = NULL;
3359 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3361 // Validate parameters
3362 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3363 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3364 // Container cannot contain itself
3365 if (collectionHandle == resourceHandle)
3367 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3368 return OC_STACK_INVALID_PARAM;
3371 // Use the handle to find the resource in the resource linked list
3372 resource = findResource((OCResource *) collectionHandle);
3375 OIC_LOG(ERROR, TAG, "Collection handle not found");
3376 return OC_STACK_INVALID_PARAM;
3379 // Look for an open slot to add add the child resource.
3380 // If found, add it and return success
3382 tempChildResource = resource->rsrcChildResourcesHead;
3384 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3386 // TODO: what if one of child resource was deregistered without unbinding?
3387 tempChildResource = tempChildResource->next;
3390 // Do memory allocation for child resource
3391 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3392 if(!newChildResource)
3394 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3395 return OC_STACK_ERROR;
3398 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3399 newChildResource->next = NULL;
3401 if(!resource->rsrcChildResourcesHead)
3403 resource->rsrcChildResourcesHead = newChildResource;
3406 tempChildResource->next = newChildResource;
3409 OIC_LOG(INFO, TAG, "resource bound");
3411 #ifdef WITH_PRESENCE
3412 if (presenceResource.handle)
3414 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3415 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3416 OC_PRESENCE_TRIGGER_CHANGE);
3423 OCStackResult OCUnBindResource(
3424 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3426 OCResource *resource = NULL;
3427 OCChildResource *tempChildResource = NULL;
3428 OCChildResource *tempLastChildResource = NULL;
3430 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3432 // Validate parameters
3433 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3434 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3435 // Container cannot contain itself
3436 if (collectionHandle == resourceHandle)
3438 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3439 return OC_STACK_INVALID_PARAM;
3442 // Use the handle to find the resource in the resource linked list
3443 resource = findResource((OCResource *) collectionHandle);
3446 OIC_LOG(ERROR, TAG, "Collection handle not found");
3447 return OC_STACK_INVALID_PARAM;
3450 // Look for an open slot to add add the child resource.
3451 // If found, add it and return success
3452 if(!resource->rsrcChildResourcesHead)
3454 OIC_LOG(INFO, TAG, "resource not found in collection");
3456 // Unable to add resourceHandle, so return error
3457 return OC_STACK_ERROR;
3461 tempChildResource = resource->rsrcChildResourcesHead;
3463 while (tempChildResource)
3465 if(tempChildResource->rsrcResource == resourceHandle)
3467 // if resource going to be unbinded is the head one.
3468 if( tempChildResource == resource->rsrcChildResourcesHead )
3470 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3471 OICFree(resource->rsrcChildResourcesHead);
3472 resource->rsrcChildResourcesHead = temp;
3477 OCChildResource *temp = tempChildResource->next;
3478 OICFree(tempChildResource);
3479 tempLastChildResource->next = temp;
3483 OIC_LOG(INFO, TAG, "resource unbound");
3485 // Send notification when resource is unbounded successfully.
3486 #ifdef WITH_PRESENCE
3487 if (presenceResource.handle)
3489 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3490 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3491 OC_PRESENCE_TRIGGER_CHANGE);
3494 tempChildResource = NULL;
3495 tempLastChildResource = NULL;
3501 tempLastChildResource = tempChildResource;
3502 tempChildResource = tempChildResource->next;
3505 OIC_LOG(INFO, TAG, "resource not found in collection");
3507 tempChildResource = NULL;
3508 tempLastChildResource = NULL;
3510 // Unable to add resourceHandle, so return error
3511 return OC_STACK_ERROR;
3514 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3516 if (!resourceItemName)
3520 // Per RFC 6690 only registered values must follow the first rule below.
3521 // At this point in time the only values registered begin with "core", and
3522 // all other values are specified as opaque strings where multiple values
3523 // are separated by a space.
3524 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3526 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3528 if (resourceItemName[index] != '.'
3529 && resourceItemName[index] != '-'
3530 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3531 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3539 for (size_t index = 0; resourceItemName[index]; ++index)
3541 if (resourceItemName[index] == ' '
3542 || resourceItemName[index] == '\t'
3543 || resourceItemName[index] == '\r'
3544 || resourceItemName[index] == '\n')
3554 OCStackResult BindResourceTypeToResource(OCResource* resource,
3555 const char *resourceTypeName)
3557 OCResourceType *pointer = NULL;
3559 OCStackResult result = OC_STACK_ERROR;
3561 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3563 if (!ValidateResourceTypeInterface(resourceTypeName))
3565 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3566 return OC_STACK_INVALID_PARAM;
3569 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3572 result = OC_STACK_NO_MEMORY;
3576 str = OICStrdup(resourceTypeName);
3579 result = OC_STACK_NO_MEMORY;
3582 pointer->resourcetypename = str;
3583 pointer->next = NULL;
3585 insertResourceType(resource, pointer);
3586 result = OC_STACK_OK;
3589 if (result != OC_STACK_OK)
3598 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3599 const char *resourceInterfaceName)
3601 OCResourceInterface *pointer = NULL;
3603 OCStackResult result = OC_STACK_ERROR;
3605 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3607 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3609 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3610 return OC_STACK_INVALID_PARAM;
3613 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3615 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3618 result = OC_STACK_NO_MEMORY;
3622 str = OICStrdup(resourceInterfaceName);
3625 result = OC_STACK_NO_MEMORY;
3628 pointer->name = str;
3630 // Bind the resourceinterface to the resource
3631 insertResourceInterface(resource, pointer);
3633 result = OC_STACK_OK;
3636 if (result != OC_STACK_OK)
3645 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3646 const char *resourceTypeName)
3649 OCStackResult result = OC_STACK_ERROR;
3650 OCResource *resource = NULL;
3652 resource = findResource((OCResource *) handle);
3655 OIC_LOG(ERROR, TAG, "Resource not found");
3656 return OC_STACK_ERROR;
3659 result = BindResourceTypeToResource(resource, resourceTypeName);
3661 #ifdef WITH_PRESENCE
3662 if(presenceResource.handle)
3664 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3665 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3672 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3673 const char *resourceInterfaceName)
3676 OCStackResult result = OC_STACK_ERROR;
3677 OCResource *resource = NULL;
3679 resource = findResource((OCResource *) handle);
3682 OIC_LOG(ERROR, TAG, "Resource not found");
3683 return OC_STACK_ERROR;
3686 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3688 #ifdef WITH_PRESENCE
3689 if (presenceResource.handle)
3691 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3692 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3699 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3701 OCResource *pointer = headResource;
3703 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3707 *numResources = *numResources + 1;
3708 pointer = pointer->next;
3713 OCResourceHandle OCGetResourceHandle(uint8_t index)
3715 OCResource *pointer = headResource;
3717 for( uint8_t i = 0; i < index && pointer; ++i)
3719 pointer = pointer->next;
3721 return (OCResourceHandle) pointer;
3724 OCStackResult OCDeleteResource(OCResourceHandle handle)
3728 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3729 return OC_STACK_INVALID_PARAM;
3732 OCResource *resource = findResource((OCResource *) handle);
3733 if (resource == NULL)
3735 OIC_LOG(ERROR, TAG, "Resource not found");
3736 return OC_STACK_NO_RESOURCE;
3739 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3741 OIC_LOG(ERROR, TAG, "Error deleting resource");
3742 return OC_STACK_ERROR;
3748 const char *OCGetResourceUri(OCResourceHandle handle)
3750 OCResource *resource = NULL;
3752 resource = findResource((OCResource *) handle);
3755 return resource->uri;
3757 return (const char *) NULL;
3760 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3762 OCResource *resource = NULL;
3764 resource = findResource((OCResource *) handle);
3767 return resource->resourceProperties;
3769 return (OCResourceProperty)-1;
3772 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3773 uint8_t *numResourceTypes)
3775 OCResource *resource = NULL;
3776 OCResourceType *pointer = NULL;
3778 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3779 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3781 *numResourceTypes = 0;
3783 resource = findResource((OCResource *) handle);
3786 pointer = resource->rsrcType;
3789 *numResourceTypes = *numResourceTypes + 1;
3790 pointer = pointer->next;
3796 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3798 OCResourceType *resourceType = NULL;
3800 resourceType = findResourceTypeAtIndex(handle, index);
3803 return resourceType->resourcetypename;
3805 return (const char *) NULL;
3808 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3809 uint8_t *numResourceInterfaces)
3811 OCResourceInterface *pointer = NULL;
3812 OCResource *resource = NULL;
3814 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3815 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3817 *numResourceInterfaces = 0;
3818 resource = findResource((OCResource *) handle);
3821 pointer = resource->rsrcInterface;
3824 *numResourceInterfaces = *numResourceInterfaces + 1;
3825 pointer = pointer->next;
3831 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3833 OCResourceInterface *resourceInterface = NULL;
3835 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3836 if (resourceInterface)
3838 return resourceInterface->name;
3840 return (const char *) NULL;
3843 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3846 OCResource *resource = NULL;
3847 OCChildResource *tempChildResource = NULL;
3850 resource = findResource((OCResource *) collectionHandle);
3856 tempChildResource = resource->rsrcChildResourcesHead;
3858 while(tempChildResource)
3862 return tempChildResource->rsrcResource;
3865 tempChildResource = tempChildResource->next;
3868 // In this case, the number of resource handles in the collection exceeds the index
3869 tempChildResource = NULL;
3873 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3874 OCEntityHandler entityHandler,
3875 void* callbackParam)
3877 OCResource *resource = NULL;
3879 // Validate parameters
3880 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3882 // Use the handle to find the resource in the resource linked list
3883 resource = findResource((OCResource *)handle);
3886 OIC_LOG(ERROR, TAG, "Resource not found");
3887 return OC_STACK_ERROR;
3891 resource->entityHandler = entityHandler;
3892 resource->entityHandlerCallbackParam = callbackParam;
3894 #ifdef WITH_PRESENCE
3895 if (presenceResource.handle)
3897 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3898 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3905 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3907 OCResource *resource = NULL;
3909 resource = findResource((OCResource *)handle);
3912 OIC_LOG(ERROR, TAG, "Resource not found");
3917 return resource->entityHandler;
3920 void incrementSequenceNumber(OCResource * resPtr)
3922 // Increment the sequence number
3923 resPtr->sequenceNum += 1;
3924 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3926 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3931 #ifdef WITH_PRESENCE
3932 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3933 OCPresenceTrigger trigger)
3935 OCResource *resPtr = NULL;
3936 OCStackResult result = OC_STACK_ERROR;
3937 OCMethod method = OC_REST_PRESENCE;
3938 uint32_t maxAge = 0;
3939 resPtr = findResource((OCResource *) presenceResource.handle);
3942 return OC_STACK_NO_RESOURCE;
3945 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3947 maxAge = presenceResource.presenceTTL;
3949 result = SendAllObserverNotification(method, resPtr, maxAge,
3950 trigger, resourceType, OC_LOW_QOS);
3956 OCStackResult SendStopNotification()
3958 OCResource *resPtr = NULL;
3959 OCStackResult result = OC_STACK_ERROR;
3960 OCMethod method = OC_REST_PRESENCE;
3961 resPtr = findResource((OCResource *) presenceResource.handle);
3964 return OC_STACK_NO_RESOURCE;
3967 // maxAge is 0. ResourceType is NULL.
3968 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3974 #endif // WITH_PRESENCE
3975 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3977 OCResource *resPtr = NULL;
3978 OCStackResult result = OC_STACK_ERROR;
3979 OCMethod method = OC_REST_NOMETHOD;
3980 uint32_t maxAge = 0;
3982 OIC_LOG(INFO, TAG, "Notifying all observers");
3983 #ifdef WITH_PRESENCE
3984 if(handle == presenceResource.handle)
3988 #endif // WITH_PRESENCE
3989 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3991 // Verify that the resource exists
3992 resPtr = findResource ((OCResource *) handle);
3995 return OC_STACK_NO_RESOURCE;
3999 //only increment in the case of regular observing (not presence)
4000 incrementSequenceNumber(resPtr);
4001 method = OC_REST_OBSERVE;
4002 maxAge = MAX_OBSERVE_AGE;
4003 #ifdef WITH_PRESENCE
4004 result = SendAllObserverNotification (method, resPtr, maxAge,
4005 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4007 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4014 OCNotifyListOfObservers (OCResourceHandle handle,
4015 OCObservationId *obsIdList,
4016 uint8_t numberOfIds,
4017 const OCRepPayload *payload,
4018 OCQualityOfService qos)
4020 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4022 OCResource *resPtr = NULL;
4023 //TODO: we should allow the server to define this
4024 uint32_t maxAge = MAX_OBSERVE_AGE;
4026 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4027 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4028 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4030 resPtr = findResource ((OCResource *) handle);
4031 if (NULL == resPtr || myStackMode == OC_CLIENT)
4033 return OC_STACK_NO_RESOURCE;
4037 incrementSequenceNumber(resPtr);
4039 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4040 payload, maxAge, qos));
4043 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4045 OCStackResult result = OC_STACK_ERROR;
4046 OCServerRequest *serverRequest = NULL;
4048 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4050 // Validate input parameters
4051 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4052 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4055 // Get pointer to request info
4056 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4059 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4060 result = serverRequest->ehResponseHandler(ehResponse);
4066 //#ifdef DIRECT_PAIRING
4067 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4069 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4070 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4072 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4076 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4079 const OCDPDev_t* OCGetDirectPairedDevices()
4081 return (const OCDPDev_t*)DPGetPairedDevices();
4084 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4085 OCDirectPairingCB resultCallback)
4087 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4088 if(NULL == peer || NULL == pinNumber)
4090 OIC_LOG(ERROR, TAG, "Invalid parameters");
4091 return OC_STACK_INVALID_PARAM;
4093 if (NULL == resultCallback)
4095 OIC_LOG(ERROR, TAG, "Invalid callback");
4096 return OC_STACK_INVALID_CALLBACK;
4099 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4100 pinNumber, (OCDirectPairingResultCB)resultCallback);
4102 //#endif // DIRECT_PAIRING
4104 //-----------------------------------------------------------------------------
4105 // Private internal function definitions
4106 //-----------------------------------------------------------------------------
4107 static OCDoHandle GenerateInvocationHandle()
4109 OCDoHandle handle = NULL;
4110 // Generate token here, it will be deleted when the transaction is deleted
4111 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4114 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4120 #ifdef WITH_PRESENCE
4121 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4122 OCResourceProperty resourceProperties, uint8_t enable)
4126 return OC_STACK_INVALID_PARAM;
4128 if (resourceProperties
4129 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4131 OIC_LOG(ERROR, TAG, "Invalid property");
4132 return OC_STACK_INVALID_PARAM;
4136 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4140 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4146 OCStackResult initResources()
4148 OCStackResult result = OC_STACK_OK;
4150 headResource = NULL;
4151 tailResource = NULL;
4152 // Init Virtual Resources
4153 #ifdef WITH_PRESENCE
4154 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4156 result = OCCreateResource(&presenceResource.handle,
4157 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4159 OC_RSRVD_PRESENCE_URI,
4163 //make resource inactive
4164 result = OCChangeResourceProperty(
4165 &(((OCResource *) presenceResource.handle)->resourceProperties),
4168 #ifndef WITH_ARDUINO
4169 if (result == OC_STACK_OK)
4171 result = SRMInitSecureResources();
4175 if(result == OC_STACK_OK)
4177 CreateResetProfile();
4178 result = OCCreateResource(&deviceResource,
4179 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4180 OC_RSRVD_INTERFACE_DEFAULT,
4181 OC_RSRVD_DEVICE_URI,
4185 if(result == OC_STACK_OK)
4187 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4188 OC_RSRVD_INTERFACE_READ);
4192 if(result == OC_STACK_OK)
4194 result = OCCreateResource(&platformResource,
4195 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4196 OC_RSRVD_INTERFACE_DEFAULT,
4197 OC_RSRVD_PLATFORM_URI,
4201 if(result == OC_STACK_OK)
4203 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4204 OC_RSRVD_INTERFACE_READ);
4211 void insertResource(OCResource *resource)
4215 headResource = resource;
4216 tailResource = resource;
4220 tailResource->next = resource;
4221 tailResource = resource;
4223 resource->next = NULL;
4226 OCResource *findResource(OCResource *resource)
4228 OCResource *pointer = headResource;
4232 if (pointer == resource)
4236 pointer = pointer->next;
4241 void deleteAllResources()
4243 OCResource *pointer = headResource;
4244 OCResource *temp = NULL;
4248 temp = pointer->next;
4249 #ifdef WITH_PRESENCE
4250 if (pointer != (OCResource *) presenceResource.handle)
4252 #endif // WITH_PRESENCE
4253 deleteResource(pointer);
4254 #ifdef WITH_PRESENCE
4256 #endif // WITH_PRESENCE
4259 memset(&platformResource, 0, sizeof(platformResource));
4260 memset(&deviceResource, 0, sizeof(deviceResource));
4262 memset(&brokerResource, 0, sizeof(brokerResource));
4265 SRMDeInitSecureResources();
4267 #ifdef WITH_PRESENCE
4268 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4269 // presence notification attributed to their deletion to be processed.
4270 deleteResource((OCResource *) presenceResource.handle);
4271 memset(&presenceResource, 0, sizeof(presenceResource));
4272 #endif // WITH_PRESENCE
4275 OCStackResult deleteResource(OCResource *resource)
4277 OCResource *prev = NULL;
4278 OCResource *temp = NULL;
4281 OIC_LOG(DEBUG,TAG,"resource is NULL");
4282 return OC_STACK_INVALID_PARAM;
4285 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4287 temp = headResource;
4290 if (temp == resource)
4292 // Invalidate all Resource Properties.
4293 resource->resourceProperties = (OCResourceProperty) 0;
4294 #ifdef WITH_PRESENCE
4295 if(resource != (OCResource *) presenceResource.handle)
4297 #endif // WITH_PRESENCE
4298 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4299 #ifdef WITH_PRESENCE
4302 if(presenceResource.handle)
4304 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4305 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4308 // Only resource in list.
4309 if (temp == headResource && temp == tailResource)
4311 headResource = NULL;
4312 tailResource = NULL;
4315 else if (temp == headResource)
4317 headResource = temp->next;
4320 else if (temp == tailResource)
4322 tailResource = prev;
4323 tailResource->next = NULL;
4327 prev->next = temp->next;
4330 deleteResourceElements(temp);
4341 return OC_STACK_ERROR;
4344 void deleteResourceElements(OCResource *resource)
4351 OICFree(resource->uri);
4352 deleteResourceType(resource->rsrcType);
4353 deleteResourceInterface(resource->rsrcInterface);
4356 void deleteResourceType(OCResourceType *resourceType)
4358 OCResourceType *pointer = resourceType;
4359 OCResourceType *next = NULL;
4363 next = pointer->next;
4364 OICFree(pointer->resourcetypename);
4370 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4372 OCResourceInterface *pointer = resourceInterface;
4373 OCResourceInterface *next = NULL;
4377 next = pointer->next;
4378 OICFree(pointer->name);
4384 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4386 OCResourceType *pointer = NULL;
4387 OCResourceType *previous = NULL;
4388 if (!resource || !resourceType)
4392 // resource type list is empty.
4393 else if (!resource->rsrcType)
4395 resource->rsrcType = resourceType;
4399 pointer = resource->rsrcType;
4403 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4405 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4406 OICFree(resourceType->resourcetypename);
4407 OICFree(resourceType);
4411 pointer = pointer->next;
4416 previous->next = resourceType;
4419 resourceType->next = NULL;
4421 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4424 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4426 OCResource *resource = NULL;
4427 OCResourceType *pointer = NULL;
4429 // Find the specified resource
4430 resource = findResource((OCResource *) handle);
4436 // Make sure a resource has a resourcetype
4437 if (!resource->rsrcType)
4442 // Iterate through the list
4443 pointer = resource->rsrcType;
4444 for(uint8_t i = 0; i< index && pointer; ++i)
4446 pointer = pointer->next;
4451 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4453 if(resourceTypeList && resourceTypeName)
4455 OCResourceType * rtPointer = resourceTypeList;
4456 while(resourceTypeName && rtPointer)
4458 if(rtPointer->resourcetypename &&
4459 strcmp(resourceTypeName, (const char *)
4460 (rtPointer->resourcetypename)) == 0)
4464 rtPointer = rtPointer->next;
4472 * Insert a new interface into interface linked list only if not already present.
4473 * If alredy present, 2nd arg is free'd.
4474 * Default interface will always be first if present.
4476 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4478 OCResourceInterface *pointer = NULL;
4479 OCResourceInterface *previous = NULL;
4481 newInterface->next = NULL;
4483 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4485 if (!*firstInterface)
4487 // If first interface is not oic.if.baseline, by default add it as first interface type.
4488 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4490 *firstInterface = newInterface;
4494 OCStackResult result = BindResourceInterfaceToResource(resource,
4495 OC_RSRVD_INTERFACE_DEFAULT);
4496 if (result != OC_STACK_OK)
4498 OICFree(newInterface->name);
4499 OICFree(newInterface);
4502 if (*firstInterface)
4504 (*firstInterface)->next = newInterface;
4508 // If once add oic.if.baseline, later too below code take care of freeing memory.
4509 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4511 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4513 OICFree(newInterface->name);
4514 OICFree(newInterface);
4517 // This code will not hit anymore, keeping
4520 newInterface->next = *firstInterface;
4521 *firstInterface = newInterface;
4526 pointer = *firstInterface;
4529 if (strcmp(newInterface->name, pointer->name) == 0)
4531 OICFree(newInterface->name);
4532 OICFree(newInterface);
4536 pointer = pointer->next;
4541 previous->next = newInterface;
4546 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4549 OCResource *resource = NULL;
4550 OCResourceInterface *pointer = NULL;
4552 // Find the specified resource
4553 resource = findResource((OCResource *) handle);
4559 // Make sure a resource has a resourceinterface
4560 if (!resource->rsrcInterface)
4565 // Iterate through the list
4566 pointer = resource->rsrcInterface;
4568 for (uint8_t i = 0; i < index && pointer; ++i)
4570 pointer = pointer->next;
4576 * This function splits the uri using the '?' delimiter.
4577 * "uriWithoutQuery" is the block of characters between the beginning
4578 * till the delimiter or '\0' which ever comes first.
4579 * "query" is whatever is to the right of the delimiter if present.
4580 * No delimiter sets the query to NULL.
4581 * If either are present, they will be malloc'ed into the params 2, 3.
4582 * The first param, *uri is left untouched.
4584 * NOTE: This function does not account for whitespace at the end of the uri NOR
4585 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4586 * part of the query.
4588 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4592 return OC_STACK_INVALID_URI;
4594 if(!query || !uriWithoutQuery)
4596 return OC_STACK_INVALID_PARAM;
4600 *uriWithoutQuery = NULL;
4602 size_t uriWithoutQueryLen = 0;
4603 size_t queryLen = 0;
4604 size_t uriLen = strlen(uri);
4606 char *pointerToDelimiter = strstr(uri, "?");
4608 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4609 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4611 if (uriWithoutQueryLen)
4613 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4614 if (!*uriWithoutQuery)
4618 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4622 *query = (char *) OICCalloc(queryLen + 1, 1);
4625 OICFree(*uriWithoutQuery);
4626 *uriWithoutQuery = NULL;
4629 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4635 return OC_STACK_NO_MEMORY;
4638 static const OicUuid_t* OCGetServerInstanceID(void)
4640 static bool generated = false;
4641 static OicUuid_t sid;
4647 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4649 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4656 const char* OCGetServerInstanceIDString(void)
4658 static bool generated = false;
4659 static char sidStr[UUID_STRING_SIZE];
4666 const OicUuid_t *sid = OCGetServerInstanceID();
4667 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4669 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4677 CAResult_t OCSelectNetwork()
4679 CAResult_t retResult = CA_STATUS_FAILED;
4680 CAResult_t caResult = CA_STATUS_OK;
4682 CATransportAdapter_t connTypes[] = {
4684 CA_ADAPTER_RFCOMM_BTEDR,
4685 CA_ADAPTER_GATT_BTLE,
4688 ,CA_ADAPTER_REMOTE_ACCESS
4695 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4697 for(int i = 0; i<numConnTypes; i++)
4699 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4700 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4702 caResult = CASelectNetwork(connTypes[i]);
4703 if(caResult == CA_STATUS_OK)
4705 retResult = CA_STATUS_OK;
4710 if(retResult != CA_STATUS_OK)
4712 return caResult; // Returns error of appropriate transport that failed fatally.
4718 OCStackResult CAResultToOCResult(CAResult_t caResult)
4724 case CA_STATUS_INVALID_PARAM:
4725 return OC_STACK_INVALID_PARAM;
4726 case CA_ADAPTER_NOT_ENABLED:
4727 return OC_STACK_ADAPTER_NOT_ENABLED;
4728 case CA_SERVER_STARTED_ALREADY:
4730 case CA_SERVER_NOT_STARTED:
4731 return OC_STACK_ERROR;
4732 case CA_DESTINATION_NOT_REACHABLE:
4733 return OC_STACK_COMM_ERROR;
4734 case CA_SOCKET_OPERATION_FAILED:
4735 return OC_STACK_COMM_ERROR;
4736 case CA_SEND_FAILED:
4737 return OC_STACK_COMM_ERROR;
4738 case CA_RECEIVE_FAILED:
4739 return OC_STACK_COMM_ERROR;
4740 case CA_MEMORY_ALLOC_FAILED:
4741 return OC_STACK_NO_MEMORY;
4742 case CA_REQUEST_TIMEOUT:
4743 return OC_STACK_TIMEOUT;
4744 case CA_DESTINATION_DISCONNECTED:
4745 return OC_STACK_COMM_ERROR;
4746 case CA_STATUS_FAILED:
4747 return OC_STACK_ERROR;
4748 case CA_NOT_SUPPORTED:
4749 return OC_STACK_NOTIMPL;
4751 return OC_STACK_ERROR;
4755 bool OCResultToSuccess(OCStackResult ocResult)
4760 case OC_STACK_RESOURCE_CREATED:
4761 case OC_STACK_RESOURCE_DELETED:
4762 case OC_STACK_CONTINUE:
4763 case OC_STACK_RESOURCE_CHANGED: