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].", method);
708 case OC_STACK_RESOURCE_CREATED:
711 case OC_STACK_RESOURCE_DELETED:
714 case OC_STACK_INVALID_QUERY:
717 case OC_STACK_INVALID_OPTION:
720 case OC_STACK_NO_RESOURCE:
723 case OC_STACK_COMM_ERROR:
724 ret = CA_RETRANSMIT_TIMEOUT;
726 case OC_STACK_UNAUTHORIZED_REQ:
727 ret = CA_UNAUTHORIZED_REQ;
735 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
737 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
739 // supply default behavior.
740 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
742 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
744 if ((caFlags & OC_MASK_SCOPE) == 0)
746 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
751 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
753 return (OCTransportFlags)caFlags;
756 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
758 uint32_t lowerBound = 0;
759 uint32_t higherBound = 0;
761 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
763 return OC_STACK_INVALID_PARAM;
766 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
768 cbNode->presence->TTL = maxAgeSeconds;
770 for (int index = 0; index < PresenceTimeOutSize; index++)
772 // Guard against overflow
773 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
776 lowerBound = GetTicks((PresenceTimeOut[index] *
777 cbNode->presence->TTL *
778 MILLISECONDS_PER_SECOND)/100);
782 lowerBound = GetTicks(UINT32_MAX);
785 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
788 higherBound = GetTicks((PresenceTimeOut[index + 1] *
789 cbNode->presence->TTL *
790 MILLISECONDS_PER_SECOND)/100);
794 higherBound = GetTicks(UINT32_MAX);
797 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
799 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
800 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
801 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
804 cbNode->presence->TTLlevel = 0;
806 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
810 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
812 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
814 return OC_RSRVD_TRIGGER_CREATE;
816 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
818 return OC_RSRVD_TRIGGER_CHANGE;
822 return OC_RSRVD_TRIGGER_DELETE;
826 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
830 return OC_PRESENCE_TRIGGER_CREATE;
832 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
834 return OC_PRESENCE_TRIGGER_CREATE;
836 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
838 return OC_PRESENCE_TRIGGER_CHANGE;
842 return OC_PRESENCE_TRIGGER_DELETE;
847 * Encode an address string to match RFC6874.
849 * @param outputAddress a char array to be written with the encoded string.
851 * @param outputSize size of outputAddress buffer.
853 * @param inputAddress a char array of size <= CA_MAX_URI_LENGTH
854 * containing a valid IPv6 address string.
856 * @return OC_STACK_OK if encoding succeeded.
857 * Else an error occured.
859 OCStackResult encodeAddressForRFC6874(char *outputAddress,
861 const char *inputAddress)
863 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
864 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
866 /** @todo Use a max IPv6 string length instead of CA_MAX_URI_LENGTH. */
867 #define ENCODE_MAX_INPUT_LENGTH CA_MAX_URI_LENGTH
869 size_t inputLength = strnlen(inputAddress, ENCODE_MAX_INPUT_LENGTH);
871 if (inputLength >= ENCODE_MAX_INPUT_LENGTH)
873 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: too long/unterminated!");
874 return OC_STACK_INVALID_PARAM;
877 // inputSize includes the null terminator
878 size_t inputSize = inputLength + 1;
880 if (inputSize > outputSize)
882 OIC_LOG_V(ERROR, TAG,
883 "encodeAddressForRFC6874 failed: "
884 "outputSize (%d) < inputSize (%d)",
885 outputSize, inputSize);
887 return OC_STACK_ERROR;
890 char* percentChar = strchr(inputAddress, '%');
892 // If there is no '%' character, then no change is required to the string.
893 if (NULL == percentChar)
895 OICStrcpy(outputAddress, outputSize, inputAddress);
899 const char* addressPart = &inputAddress[0];
900 const char* scopeIdPart = percentChar + 1;
902 // Sanity check to make sure this string doesn't have more '%' characters
903 if (NULL != strchr(scopeIdPart, '%'))
905 return OC_STACK_ERROR;
908 // If no string follows the first '%', then the input was invalid.
909 if (scopeIdPart[0] == '\0')
911 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
912 return OC_STACK_ERROR;
915 // Check to see if the string is already encoded
916 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
918 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
919 return OC_STACK_ERROR;
922 // Fail if we don't have room for encoded string's two additional chars
923 if (outputSize < (inputSize + 2))
925 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
926 return OC_STACK_ERROR;
929 // Restore the null terminator with an escaped '%' character, per RFC6874
930 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
931 strcat(outputAddress, "%25");
932 strcat(outputAddress, scopeIdPart);
938 * The cononical presence allows constructed URIs to be string compared.
940 * requestUri must be a char array of size CA_MAX_URI_LENGTH
942 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
945 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
946 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
947 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
949 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
951 if (ep->adapter == CA_ADAPTER_IP)
953 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
955 if ('\0' == ep->addr[0]) // multicast
957 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
961 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
963 OCStackResult result = encodeAddressForRFC6874(addressEncoded,
964 sizeof(addressEncoded),
967 if (OC_STACK_OK != result)
972 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
973 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
978 if ('\0' == ep->addr[0]) // multicast
980 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
981 ep->port = OC_MULTICAST_PORT;
983 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
984 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
988 // might work for other adapters (untested, but better than nothing)
989 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
990 OC_RSRVD_PRESENCE_URI);
994 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
995 const CAResponseInfo_t *responseInfo)
997 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
998 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1000 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1001 ClientCB * cbNode = NULL;
1002 char *resourceTypeName = NULL;
1003 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1004 OCStackResult result = OC_STACK_ERROR;
1005 uint32_t maxAge = 0;
1007 char presenceUri[CA_MAX_URI_LENGTH];
1009 int presenceSubscribe = 0;
1010 int multicastPresenceSubscribe = 0;
1012 if (responseInfo->result != CA_CONTENT)
1014 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1015 return OC_STACK_ERROR;
1018 // check for unicast presence
1019 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
1020 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1022 return OC_STACK_INVALID_URI;
1025 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1028 presenceSubscribe = 1;
1032 // check for multiicast presence
1033 CAEndpoint_t ep = { .adapter = endpoint->adapter,
1034 .flags = endpoint->flags };
1036 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
1038 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1041 multicastPresenceSubscribe = 1;
1045 if (!presenceSubscribe && !multicastPresenceSubscribe)
1047 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1051 response.payload = NULL;
1052 response.result = OC_STACK_OK;
1054 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1055 FixUpClientResponse(&response);
1057 if (responseInfo->info.payload)
1059 result = OCParsePayload(&response.payload,
1060 PAYLOAD_TYPE_PRESENCE,
1061 responseInfo->info.payload,
1062 responseInfo->info.payloadSize);
1064 if(result != OC_STACK_OK)
1066 OIC_LOG(ERROR, TAG, "Presence parse failed");
1069 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1071 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1072 result = OC_STACK_ERROR;
1075 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1076 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1077 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1080 if (presenceSubscribe)
1082 if(cbNode->sequenceNumber == response.sequenceNumber)
1084 OIC_LOG(INFO, TAG, "No presence change");
1085 ResetPresenceTTL(cbNode, maxAge);
1086 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1092 OIC_LOG(INFO, TAG, "Stopping presence");
1093 response.result = OC_STACK_PRESENCE_STOPPED;
1094 if(cbNode->presence)
1096 OICFree(cbNode->presence->timeOut);
1097 OICFree(cbNode->presence);
1098 cbNode->presence = NULL;
1103 if(!cbNode->presence)
1105 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1107 if(!(cbNode->presence))
1109 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1110 result = OC_STACK_NO_MEMORY;
1114 VERIFY_NON_NULL_V(cbNode->presence);
1115 cbNode->presence->timeOut = NULL;
1116 cbNode->presence->timeOut = (uint32_t *)
1117 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1118 if(!(cbNode->presence->timeOut)){
1120 "Could not allocate memory for cbNode->presence->timeOut");
1121 OICFree(cbNode->presence);
1122 result = OC_STACK_NO_MEMORY;
1127 ResetPresenceTTL(cbNode, maxAge);
1129 cbNode->sequenceNumber = response.sequenceNumber;
1131 // Ensure that a filter is actually applied.
1132 if( resourceTypeName && cbNode->filterResourceType)
1134 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1143 // This is the multicast case
1144 OCMulticastNode* mcNode = NULL;
1145 mcNode = GetMCPresenceNode(presenceUri);
1149 if(mcNode->nonce == response.sequenceNumber)
1151 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1154 mcNode->nonce = response.sequenceNumber;
1158 OIC_LOG(INFO, TAG, "Stopping presence");
1159 response.result = OC_STACK_PRESENCE_STOPPED;
1164 char* uri = OICStrdup(presenceUri);
1168 "No Memory for URI to store in the presence node");
1169 result = OC_STACK_NO_MEMORY;
1173 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1174 if(result == OC_STACK_NO_MEMORY)
1177 "No Memory for Multicast Presence Node");
1181 // presence node now owns uri
1184 // Ensure that a filter is actually applied.
1185 if(resourceTypeName && cbNode->filterResourceType)
1187 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1194 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1196 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1198 FindAndDeleteClientCB(cbNode);
1202 OCPayloadDestroy(response.payload);
1206 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1208 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1210 if(responseInfo->info.resourceUri &&
1211 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1213 HandlePresenceResponse(endPoint, responseInfo);
1217 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1218 responseInfo->info.tokenLength, NULL, NULL);
1220 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1221 responseInfo->info.tokenLength);
1225 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1226 if(responseInfo->result == CA_EMPTY)
1228 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1229 // We do not have a case for the client to receive a RESET
1230 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1232 //This is the case of receiving an ACK on a request to a slow resource!
1233 OIC_LOG(INFO, TAG, "This is a pure ACK");
1234 //TODO: should we inform the client
1235 // app that at least the request was received at the server?
1238 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1240 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1241 OIC_LOG(INFO, TAG, "Calling into application address space");
1243 OCClientResponse response =
1244 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1245 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1246 FixUpClientResponse(&response);
1247 response.resourceUri = responseInfo->info.resourceUri;
1248 memcpy(response.identity.id, responseInfo->info.identity.id,
1249 sizeof (response.identity.id));
1250 response.identity.id_length = responseInfo->info.identity.id_length;
1252 response.result = CAResponseToOCStackResult(responseInfo->result);
1253 cbNode->callBack(cbNode->context,
1254 cbNode->handle, &response);
1255 FindAndDeleteClientCB(cbNode);
1259 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1260 OIC_LOG(INFO, TAG, "Calling into application address space");
1262 OCClientResponse response =
1263 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1264 response.sequenceNumber = -1;
1265 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1266 FixUpClientResponse(&response);
1267 response.resourceUri = responseInfo->info.resourceUri;
1268 memcpy(response.identity.id, responseInfo->info.identity.id,
1269 sizeof (response.identity.id));
1270 response.identity.id_length = responseInfo->info.identity.id_length;
1272 response.result = CAResponseToOCStackResult(responseInfo->result);
1274 if(responseInfo->info.payload &&
1275 responseInfo->info.payloadSize)
1277 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1278 // check the security resource
1279 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1281 type = PAYLOAD_TYPE_SECURITY;
1283 else if (cbNode->method == OC_REST_DISCOVER)
1285 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1286 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1288 type = PAYLOAD_TYPE_DISCOVERY;
1291 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1293 type = PAYLOAD_TYPE_DISCOVERY;
1296 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1298 type = PAYLOAD_TYPE_DEVICE;
1300 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1302 type = PAYLOAD_TYPE_PLATFORM;
1304 #ifdef ROUTING_GATEWAY
1305 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1307 type = PAYLOAD_TYPE_REPRESENTATION;
1310 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1312 type = PAYLOAD_TYPE_RD;
1315 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1317 type = PAYLOAD_TYPE_REPRESENTATION;
1322 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1323 cbNode->method, cbNode->requestUri);
1327 else if (cbNode->method == OC_REST_GET ||
1328 cbNode->method == OC_REST_PUT ||
1329 cbNode->method == OC_REST_POST ||
1330 cbNode->method == OC_REST_OBSERVE ||
1331 cbNode->method == OC_REST_OBSERVE_ALL ||
1332 cbNode->method == OC_REST_DELETE)
1334 char targetUri[MAX_URI_LENGTH];
1335 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1336 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1337 if (strcmp(targetUri, cbNode->requestUri) == 0)
1339 type = PAYLOAD_TYPE_RD;
1341 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1343 type = PAYLOAD_TYPE_PLATFORM;
1345 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1347 type = PAYLOAD_TYPE_DEVICE;
1349 if (type == PAYLOAD_TYPE_INVALID)
1351 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1352 cbNode->method, cbNode->requestUri);
1353 type = PAYLOAD_TYPE_REPRESENTATION;
1358 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1359 cbNode->method, cbNode->requestUri);
1363 if(OC_STACK_OK != OCParsePayload(&response.payload,
1365 responseInfo->info.payload,
1366 responseInfo->info.payloadSize))
1368 OIC_LOG(ERROR, TAG, "Error converting payload");
1369 OCPayloadDestroy(response.payload);
1374 response.numRcvdVendorSpecificHeaderOptions = 0;
1375 if(responseInfo->info.numOptions > 0)
1378 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1379 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1382 uint32_t observationOption;
1383 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1384 for (observationOption=0, i=0;
1385 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1389 (observationOption << 8) | optionData[i];
1391 response.sequenceNumber = observationOption;
1392 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1397 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1400 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1402 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1403 OCPayloadDestroy(response.payload);
1407 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1409 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1410 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1414 if (cbNode->method == OC_REST_OBSERVE &&
1415 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1416 response.sequenceNumber <= cbNode->sequenceNumber)
1418 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1419 response.sequenceNumber);
1423 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1426 cbNode->sequenceNumber = response.sequenceNumber;
1428 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1430 FindAndDeleteClientCB(cbNode);
1434 // To keep discovery callbacks active.
1435 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1436 MILLISECONDS_PER_SECOND);
1440 //Need to send ACK when the response is CON
1441 if(responseInfo->info.type == CA_MSG_CONFIRM)
1443 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1444 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1447 OCPayloadDestroy(response.payload);
1454 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1455 if(responseInfo->result == CA_EMPTY)
1457 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1458 if(responseInfo->info.type == CA_MSG_RESET)
1460 OIC_LOG(INFO, TAG, "This is a RESET");
1461 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1462 OC_OBSERVER_NOT_INTERESTED);
1464 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1466 OIC_LOG(INFO, TAG, "This is a pure ACK");
1467 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1468 OC_OBSERVER_STILL_INTERESTED);
1471 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1473 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1474 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1475 OC_OBSERVER_FAILED_COMM);
1480 if(!cbNode && !observer)
1482 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1483 || myStackMode == OC_GATEWAY)
1485 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1486 if(responseInfo->result == CA_EMPTY)
1488 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1492 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1493 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1494 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1498 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1499 || myStackMode == OC_GATEWAY)
1501 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1502 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1504 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1505 responseInfo->info.messageId);
1507 if (responseInfo->info.type == CA_MSG_RESET)
1509 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1510 responseInfo->info.messageId);
1517 OIC_LOG(INFO, TAG, "Exit OCHandleResponse");
1520 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1522 VERIFY_NON_NULL_NR(endPoint, FATAL);
1523 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1525 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1527 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1528 #ifdef ROUTING_GATEWAY
1529 bool needRIHandling = false;
1531 * Routing manager is going to update either of endpoint or response or both.
1532 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1533 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1536 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1538 if(ret != OC_STACK_OK || !needRIHandling)
1540 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1546 * Put source in sender endpoint so that the next packet from application can be routed to
1547 * proper destination and remove "RM" coap header option before passing request / response to
1548 * RI as this option will make no sense to either RI or application.
1550 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1551 (uint8_t *) &(responseInfo->info.numOptions),
1552 (CAEndpoint_t *) endPoint);
1555 OCHandleResponse(endPoint, responseInfo);
1557 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1561 * This function handles error response from CA
1562 * code shall be added to handle the errors
1564 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1566 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1568 if (NULL == endPoint)
1570 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1574 if (NULL == errorInfo)
1576 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1580 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1581 errorInfo->info.tokenLength, NULL, NULL);
1584 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1585 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1586 FixUpClientResponse(&response);
1587 response.resourceUri = errorInfo->info.resourceUri;
1588 memcpy(response.identity.id, errorInfo->info.identity.id,
1589 sizeof (response.identity.id));
1590 response.identity.id_length = errorInfo->info.identity.id_length;
1591 response.result = CAResultToOCStackResult(errorInfo->result);
1593 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1594 FindAndDeleteClientCB(cbNode);
1597 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1601 * This function sends out Direct Stack Responses. These are responses that are not coming
1602 * from the application entity handler. These responses have no payload and are usually ACKs,
1603 * RESETs or some error conditions that were caught by the stack.
1605 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1606 const CAResponseResult_t responseResult, const CAMessageType_t type,
1607 const uint8_t numOptions, const CAHeaderOption_t *options,
1608 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1610 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1611 CAResponseInfo_t respInfo = {
1612 .result = responseResult
1614 respInfo.info.messageId = coapID;
1615 respInfo.info.numOptions = numOptions;
1617 if (respInfo.info.numOptions)
1619 respInfo.info.options =
1620 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1621 memcpy (respInfo.info.options, options,
1622 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1626 respInfo.info.payload = NULL;
1627 respInfo.info.token = token;
1628 respInfo.info.tokenLength = tokenLength;
1629 respInfo.info.type = type;
1630 respInfo.info.resourceUri = OICStrdup (resourceUri);
1631 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1633 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1634 // Add the destination to route option from the endpoint->routeData.
1635 bool doPost = false;
1636 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1637 if(OC_STACK_OK != result)
1639 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1644 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1645 CARequestInfo_t reqInfo = {.method = CA_POST };
1646 /* The following initialization is not done in a single initializer block as in
1647 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1648 * does not have designated initalizers. This is a work-around for now.
1650 reqInfo.info.type = CA_MSG_NONCONFIRM;
1651 reqInfo.info.messageId = coapID;
1652 reqInfo.info.tokenLength = tokenLength;
1653 reqInfo.info.token = token;
1654 reqInfo.info.numOptions = respInfo.info.numOptions;
1655 reqInfo.info.payload = NULL;
1656 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1657 if (reqInfo.info.numOptions)
1659 reqInfo.info.options =
1660 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1661 if (NULL == reqInfo.info.options)
1663 OIC_LOG(ERROR, TAG, "Calloc failed");
1664 return OC_STACK_NO_MEMORY;
1666 memcpy (reqInfo.info.options, respInfo.info.options,
1667 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1670 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1671 OICFree (reqInfo.info.resourceUri);
1672 OICFree (reqInfo.info.options);
1673 OICFree (respInfo.info.resourceUri);
1674 OICFree (respInfo.info.options);
1675 if (CA_STATUS_OK != caResult)
1677 OIC_LOG(ERROR, TAG, "CASendRequest error");
1678 return CAResultToOCResult(caResult);
1684 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1686 // resourceUri in the info field is cloned in the CA layer and
1687 // thus ownership is still here.
1688 OICFree (respInfo.info.resourceUri);
1689 OICFree (respInfo.info.options);
1690 if(CA_STATUS_OK != caResult)
1692 OIC_LOG(ERROR, TAG, "CASendResponse error");
1693 return CAResultToOCResult(caResult);
1696 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1700 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1702 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1703 OCStackResult result = OC_STACK_ERROR;
1704 if(!protocolRequest)
1706 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1707 return OC_STACK_INVALID_PARAM;
1710 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1711 protocolRequest->tokenLength);
1714 OIC_LOG(INFO, TAG, "This is a new Server Request");
1715 result = AddServerRequest(&request, protocolRequest->coapID,
1716 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1717 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1718 protocolRequest->observationOption, protocolRequest->qos,
1719 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1720 protocolRequest->payload, protocolRequest->requestToken,
1721 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1722 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1723 &protocolRequest->devAddr);
1724 if (OC_STACK_OK != result)
1726 OIC_LOG(ERROR, TAG, "Error adding server request");
1732 OIC_LOG(ERROR, TAG, "Out of Memory");
1733 return OC_STACK_NO_MEMORY;
1736 if(!protocolRequest->reqMorePacket)
1738 request->requestComplete = 1;
1743 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1746 if(request->requestComplete)
1748 OIC_LOG(INFO, TAG, "This Server Request is complete");
1749 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1750 OCResource *resource = NULL;
1751 result = DetermineResourceHandling (request, &resHandling, &resource);
1752 if (result == OC_STACK_OK)
1754 result = ProcessRequest(resHandling, resource, request);
1759 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1760 result = OC_STACK_CONTINUE;
1765 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1767 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1770 if (requestInfo->info.resourceUri &&
1771 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1773 HandleKeepAliveRequest(endPoint, requestInfo);
1778 OCStackResult requestResult = OC_STACK_ERROR;
1780 if(myStackMode == OC_CLIENT)
1782 //TODO: should the client be responding to requests?
1786 OCServerProtocolRequest serverRequest = {0};
1788 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1790 char * uriWithoutQuery = NULL;
1791 char * query = NULL;
1793 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1795 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1797 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1800 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1801 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1803 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1805 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1806 OICFree(uriWithoutQuery);
1810 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1811 OICFree(uriWithoutQuery);
1818 if(strlen(query) < MAX_QUERY_LENGTH)
1820 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1825 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1831 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1833 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1834 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1835 if (!serverRequest.payload)
1837 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1840 memcpy (serverRequest.payload, requestInfo->info.payload,
1841 requestInfo->info.payloadSize);
1845 serverRequest.reqTotalSize = 0;
1848 switch (requestInfo->method)
1851 serverRequest.method = OC_REST_GET;
1854 serverRequest.method = OC_REST_PUT;
1857 serverRequest.method = OC_REST_POST;
1860 serverRequest.method = OC_REST_DELETE;
1863 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1864 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1865 requestInfo->info.type, requestInfo->info.numOptions,
1866 requestInfo->info.options, requestInfo->info.token,
1867 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1868 OICFree(serverRequest.payload);
1872 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1873 requestInfo->info.tokenLength);
1875 serverRequest.tokenLength = requestInfo->info.tokenLength;
1876 if (serverRequest.tokenLength) {
1878 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1880 if (!serverRequest.requestToken)
1882 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1883 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1884 requestInfo->info.type, requestInfo->info.numOptions,
1885 requestInfo->info.options, requestInfo->info.token,
1886 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1887 OICFree(serverRequest.payload);
1890 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1893 switch (requestInfo->info.acceptFormat)
1895 case CA_FORMAT_APPLICATION_CBOR:
1896 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1898 case CA_FORMAT_UNDEFINED:
1899 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1902 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1905 if (requestInfo->info.type == CA_MSG_CONFIRM)
1907 serverRequest.qos = OC_HIGH_QOS;
1911 serverRequest.qos = OC_LOW_QOS;
1913 // CA does not need the following field
1914 // Are we sure CA does not need them? how is it responding to multicast
1915 serverRequest.delayedResNeeded = 0;
1917 serverRequest.coapID = requestInfo->info.messageId;
1919 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1921 // copy vendor specific header options
1922 uint8_t tempNum = (requestInfo->info.numOptions);
1924 // Assume no observation requested and it is a pure GET.
1925 // If obs registration/de-registration requested it'll be fetched from the
1926 // options in GetObserveHeaderOption()
1927 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1929 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1930 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1933 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1934 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1935 requestInfo->info.type, requestInfo->info.numOptions,
1936 requestInfo->info.options, requestInfo->info.token,
1937 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1938 OICFree(serverRequest.payload);
1939 OICFree(serverRequest.requestToken);
1942 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1943 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1945 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1946 sizeof(CAHeaderOption_t)*tempNum);
1949 requestResult = HandleStackRequests (&serverRequest);
1951 // Send ACK to client as precursor to slow response
1952 if (requestResult == OC_STACK_SLOW_RESOURCE)
1954 if (requestInfo->info.type == CA_MSG_CONFIRM)
1956 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1957 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1960 else if(!OCResultToSuccess(requestResult))
1962 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1964 CAResponseResult_t stackResponse =
1965 OCToCAStackResult(requestResult, serverRequest.method);
1967 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1968 requestInfo->info.type, requestInfo->info.numOptions,
1969 requestInfo->info.options, requestInfo->info.token,
1970 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1972 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1973 // The token is copied in there, and is thus still owned by this function.
1974 OICFree(serverRequest.payload);
1975 OICFree(serverRequest.requestToken);
1976 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1979 //This function will be called back by CA layer when a request is received
1980 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1982 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1985 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1991 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
1995 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1996 #ifdef ROUTING_GATEWAY
1997 bool needRIHandling = false;
1998 bool isEmptyMsg = false;
2000 * Routing manager is going to update either of endpoint or request or both.
2001 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2002 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2003 * destination. It can also remove "RM" coap header option before passing request / response to
2004 * RI as this option will make no sense to either RI or application.
2006 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2007 &needRIHandling, &isEmptyMsg);
2008 if(OC_STACK_OK != ret || !needRIHandling)
2010 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2016 * Put source in sender endpoint so that the next packet from application can be routed to
2017 * proper destination and remove RM header option.
2019 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2020 (uint8_t *) &(requestInfo->info.numOptions),
2021 (CAEndpoint_t *) endPoint);
2023 #ifdef ROUTING_GATEWAY
2027 * In Gateways, the MSGType in route option is used to check if the actual
2028 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2029 * EMPTY response is sent in the form of POST request which need to be changed
2030 * to a EMPTY response by RM. This translation is done in this part of the code.
2032 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2033 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2034 .info.messageId = requestInfo->info.messageId,
2035 .info.type = CA_MSG_ACKNOWLEDGE};
2036 OCHandleResponse(endPoint, &respInfo);
2042 // Normal handling of the packet
2043 OCHandleRequests(endPoint, requestInfo);
2045 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2048 bool validatePlatformInfo(OCPlatformInfo info)
2051 if (!info.platformID)
2053 OIC_LOG(ERROR, TAG, "No platform ID found.");
2057 if (info.manufacturerName)
2059 size_t lenManufacturerName = strlen(info.manufacturerName);
2061 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2063 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2069 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2073 if (info.manufacturerUrl)
2075 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2077 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2084 //-----------------------------------------------------------------------------
2086 //-----------------------------------------------------------------------------
2088 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2091 !raInfo->username ||
2092 !raInfo->hostname ||
2093 !raInfo->xmpp_domain)
2096 return OC_STACK_INVALID_PARAM;
2098 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2099 gRASetInfo = (result == OC_STACK_OK)? true : false;
2105 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2109 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2112 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2114 if(stackState == OC_STACK_INITIALIZED)
2116 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2117 OCStop() between them are ignored.");
2121 #ifndef ROUTING_GATEWAY
2122 if (OC_GATEWAY == mode)
2124 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2125 return OC_STACK_INVALID_PARAM;
2132 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2133 return OC_STACK_ERROR;
2137 OCStackResult result = OC_STACK_ERROR;
2138 OIC_LOG(INFO, TAG, "Entering OCInit");
2141 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2142 || (mode == OC_GATEWAY)))
2144 OIC_LOG(ERROR, TAG, "Invalid mode");
2145 return OC_STACK_ERROR;
2149 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2151 caglobals.client = true;
2153 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2155 caglobals.server = true;
2158 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2159 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2161 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2163 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2164 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2166 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2169 defaultDeviceHandler = NULL;
2170 defaultDeviceHandlerCallbackParameter = NULL;
2172 result = CAResultToOCResult(CAInitialize());
2173 VERIFY_SUCCESS(result, OC_STACK_OK);
2175 result = CAResultToOCResult(OCSelectNetwork());
2176 VERIFY_SUCCESS(result, OC_STACK_OK);
2178 switch (myStackMode)
2181 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2182 result = CAResultToOCResult(CAStartDiscoveryServer());
2183 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2186 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2187 result = CAResultToOCResult(CAStartListeningServer());
2188 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2190 case OC_CLIENT_SERVER:
2192 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2193 result = CAResultToOCResult(CAStartListeningServer());
2194 if(result == OC_STACK_OK)
2196 result = CAResultToOCResult(CAStartDiscoveryServer());
2200 VERIFY_SUCCESS(result, OC_STACK_OK);
2203 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2206 #ifdef WITH_PRESENCE
2207 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2208 #endif // WITH_PRESENCE
2210 //Update Stack state to initialized
2211 stackState = OC_STACK_INITIALIZED;
2213 // Initialize resource
2214 if(myStackMode != OC_CLIENT)
2216 result = initResources();
2219 // Initialize the SRM Policy Engine
2220 if(result == OC_STACK_OK)
2222 result = SRMInitPolicyEngine();
2223 // TODO after BeachHead delivery: consolidate into single SRMInit()
2225 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2226 RMSetStackMode(mode);
2227 #ifdef ROUTING_GATEWAY
2228 if (OC_GATEWAY == myStackMode)
2230 result = RMInitialize();
2236 if (result == OC_STACK_OK)
2238 result = InitializeKeepAlive(myStackMode);
2243 if(result != OC_STACK_OK)
2245 OIC_LOG(ERROR, TAG, "Stack initialization error");
2246 deleteAllResources();
2248 stackState = OC_STACK_UNINITIALIZED;
2253 OCStackResult OCStop()
2255 OIC_LOG(INFO, TAG, "Entering OCStop");
2257 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2259 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2262 else if (stackState != OC_STACK_INITIALIZED)
2264 OIC_LOG(ERROR, TAG, "Stack not initialized");
2265 return OC_STACK_ERROR;
2268 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2270 #ifdef WITH_PRESENCE
2271 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2272 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2273 presenceResource.presenceTTL = 0;
2274 #endif // WITH_PRESENCE
2276 #ifdef ROUTING_GATEWAY
2277 if (OC_GATEWAY == myStackMode)
2284 TerminateKeepAlive(myStackMode);
2287 // Free memory dynamically allocated for resources
2288 deleteAllResources();
2290 DeletePlatformInfo();
2292 // Remove all observers
2293 DeleteObserverList();
2294 // Remove all the client callbacks
2295 DeleteClientCBList();
2297 // De-init the SRM Policy Engine
2298 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2299 SRMDeInitPolicyEngine();
2302 stackState = OC_STACK_UNINITIALIZED;
2306 OCStackResult OCStartMulticastServer()
2308 if(stackState != OC_STACK_INITIALIZED)
2310 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2311 return OC_STACK_ERROR;
2313 CAResult_t ret = CAStartListeningServer();
2314 if (CA_STATUS_OK != ret)
2316 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2317 return OC_STACK_ERROR;
2322 OCStackResult OCStopMulticastServer()
2324 CAResult_t ret = CAStopListeningServer();
2325 if (CA_STATUS_OK != ret)
2327 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2328 return OC_STACK_ERROR;
2333 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2338 return CA_MSG_CONFIRM;
2343 return CA_MSG_NONCONFIRM;
2348 * A request uri consists of the following components in order:
2351 * CoAP over UDP prefix "coap://"
2352 * CoAP over TCP prefix "coap+tcp://"
2354 * IPv6 address "[1234::5678]"
2355 * IPv4 address "192.168.1.1"
2356 * optional port ":5683"
2357 * resource uri "/oc/core..."
2359 * for PRESENCE requests, extract resource type.
2361 static OCStackResult ParseRequestUri(const char *fullUri,
2362 OCTransportAdapter adapter,
2363 OCTransportFlags flags,
2364 OCDevAddr **devAddr,
2366 char **resourceType)
2368 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2370 OCStackResult result = OC_STACK_OK;
2371 OCDevAddr *da = NULL;
2375 // provide defaults for all returned values
2382 *resourceUri = NULL;
2386 *resourceType = NULL;
2389 // delimit url prefix, if any
2390 const char *start = fullUri;
2391 char *slash2 = strstr(start, "//");
2396 char *slash = strchr(start, '/');
2399 return OC_STACK_INVALID_URI;
2402 // process url scheme
2403 size_t prefixLen = slash2 - fullUri;
2407 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2413 // TODO: this logic should come in with unit tests exercising the various strings
2414 // processs url prefix, if any
2415 size_t urlLen = slash - start;
2419 if (urlLen && devAddr)
2420 { // construct OCDevAddr
2421 if (start[0] == '[')
2423 char *close = strchr(++start, ']');
2424 if (!close || close > slash)
2426 return OC_STACK_INVALID_URI;
2429 if (close[1] == ':')
2436 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2440 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2442 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2446 char *dot = strchr(start, '.');
2447 if (dot && dot < slash)
2449 colon = strchr(start, ':');
2450 end = (colon && colon < slash) ? colon : slash;
2455 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2459 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2461 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2469 if (len >= sizeof(da->addr))
2471 return OC_STACK_INVALID_URI;
2473 // collect port, if any
2474 if (colon && colon < slash)
2476 for (colon++; colon < slash; colon++)
2479 if (c < '0' || c > '9')
2481 return OC_STACK_INVALID_URI;
2483 port = 10 * port + c - '0';
2488 if (len >= sizeof(da->addr))
2490 return OC_STACK_INVALID_URI;
2493 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2496 return OC_STACK_NO_MEMORY;
2498 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2500 da->adapter = adapter;
2502 if (!strncmp(fullUri, "coaps:", 6))
2504 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2509 // process resource uri, if any
2511 { // request uri and query
2512 size_t ulen = strlen(slash); // resource uri length
2513 size_t tlen = 0; // resource type length
2516 static const char strPresence[] = "/oic/ad?rt=";
2517 static const size_t lenPresence = sizeof(strPresence) - 1;
2518 if (!strncmp(slash, strPresence, lenPresence))
2520 type = slash + lenPresence;
2521 tlen = ulen - lenPresence;
2526 *resourceUri = (char *)OICMalloc(ulen + 1);
2529 result = OC_STACK_NO_MEMORY;
2532 strcpy(*resourceUri, slash);
2535 if (type && resourceType)
2537 *resourceType = (char *)OICMalloc(tlen + 1);
2540 result = OC_STACK_NO_MEMORY;
2544 OICStrcpy(*resourceType, (tlen+1), type);
2551 // free all returned values
2558 OICFree(*resourceUri);
2562 OICFree(*resourceType);
2567 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2568 char *resourceUri, char **requestUri)
2570 char uri[CA_MAX_URI_LENGTH];
2572 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2574 *requestUri = OICStrdup(uri);
2577 return OC_STACK_NO_MEMORY;
2584 * Discover or Perform requests on a specified resource
2586 OCStackResult OCDoResource(OCDoHandle *handle,
2588 const char *requestUri,
2589 const OCDevAddr *destination,
2591 OCConnectivityType connectivityType,
2592 OCQualityOfService qos,
2593 OCCallbackData *cbData,
2594 OCHeaderOption *options,
2597 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2599 // Validate input parameters
2600 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2601 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2602 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2604 OCStackResult result = OC_STACK_ERROR;
2605 CAResult_t caResult;
2606 CAToken_t token = NULL;
2607 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2608 ClientCB *clientCB = NULL;
2609 OCDoHandle resHandle = NULL;
2610 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2611 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2613 OCTransportAdapter adapter;
2614 OCTransportFlags flags;
2615 // the request contents are put here
2616 CARequestInfo_t requestInfo = {.method = CA_GET};
2617 // requestUri will be parsed into the following three variables
2618 OCDevAddr *devAddr = NULL;
2619 char *resourceUri = NULL;
2620 char *resourceType = NULL;
2623 * Support original behavior with address on resourceUri argument.
2625 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2626 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2628 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2630 if (result != OC_STACK_OK)
2632 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2639 case OC_REST_OBSERVE:
2640 case OC_REST_OBSERVE_ALL:
2641 case OC_REST_CANCEL_OBSERVE:
2642 requestInfo.method = CA_GET;
2645 requestInfo.method = CA_PUT;
2648 requestInfo.method = CA_POST;
2650 case OC_REST_DELETE:
2651 requestInfo.method = CA_DELETE;
2653 case OC_REST_DISCOVER:
2655 if (destination || devAddr)
2657 requestInfo.isMulticast = false;
2661 tmpDevAddr.adapter = adapter;
2662 tmpDevAddr.flags = flags;
2663 destination = &tmpDevAddr;
2664 requestInfo.isMulticast = true;
2666 // CA_DISCOVER will become GET and isMulticast
2667 requestInfo.method = CA_GET;
2669 #ifdef WITH_PRESENCE
2670 case OC_REST_PRESENCE:
2671 // Replacing method type with GET because "presence"
2672 // is a stack layer only implementation.
2673 requestInfo.method = CA_GET;
2677 result = OC_STACK_INVALID_METHOD;
2681 if (!devAddr && !destination)
2683 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2684 result = OC_STACK_INVALID_PARAM;
2688 /* If not original behavior, use destination argument */
2689 if (destination && !devAddr)
2691 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2694 result = OC_STACK_NO_MEMORY;
2697 *devAddr = *destination;
2700 resHandle = GenerateInvocationHandle();
2703 result = OC_STACK_NO_MEMORY;
2707 caResult = CAGenerateToken(&token, tokenLength);
2708 if (caResult != CA_STATUS_OK)
2710 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2711 result= OC_STACK_ERROR;
2715 // fill in request data
2716 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2717 requestInfo.info.token = token;
2718 requestInfo.info.tokenLength = tokenLength;
2719 requestInfo.info.resourceUri = resourceUri;
2721 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2723 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2724 options, numOptions, OC_OBSERVE_REGISTER);
2725 if (result != OC_STACK_OK)
2729 requestInfo.info.numOptions = numOptions + 1;
2733 requestInfo.info.numOptions = numOptions;
2734 requestInfo.info.options =
2735 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2736 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2737 numOptions * sizeof(CAHeaderOption_t));
2740 CopyDevAddrToEndpoint(devAddr, &endpoint);
2745 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2748 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2751 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2755 requestInfo.info.payload = NULL;
2756 requestInfo.info.payloadSize = 0;
2757 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2760 // prepare for response
2761 #ifdef WITH_PRESENCE
2762 if (method == OC_REST_PRESENCE)
2764 char *presenceUri = NULL;
2765 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2766 if (OC_STACK_OK != result)
2771 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2772 // Presence notification will form a canonical uri to
2773 // look for callbacks into the application.
2774 resourceUri = presenceUri;
2778 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2779 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2780 method, devAddr, resourceUri, resourceType, ttl);
2781 if (OC_STACK_OK != result)
2786 devAddr = NULL; // Client CB list entry now owns it
2787 resourceUri = NULL; // Client CB list entry now owns it
2788 resourceType = NULL; // Client CB list entry now owns it
2791 result = OCSendRequest(&endpoint, &requestInfo);
2792 if (OC_STACK_OK != result)
2799 *handle = resHandle;
2803 if (result != OC_STACK_OK)
2805 OIC_LOG(ERROR, TAG, "OCDoResource error");
2806 FindAndDeleteClientCB(clientCB);
2807 CADestroyToken(token);
2815 // This is the owner of the payload object, so we free it
2816 OCPayloadDestroy(payload);
2817 OICFree(requestInfo.info.payload);
2819 OICFree(resourceUri);
2820 OICFree(resourceType);
2821 OICFree(requestInfo.info.options);
2825 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2829 * This ftn is implemented one of two ways in the case of observation:
2831 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2832 * Remove the callback associated on client side.
2833 * When the next notification comes in from server,
2834 * reply with RESET message to server.
2835 * Keep in mind that the server will react to RESET only
2836 * if the last notification was sent as CON
2838 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2839 * and it is associated with an observe request
2840 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2841 * Send CON Observe request to server with
2842 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2843 * Remove the callback associated on client side.
2845 OCStackResult ret = OC_STACK_OK;
2846 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2847 CARequestInfo_t requestInfo = {.method = CA_GET};
2851 return OC_STACK_INVALID_PARAM;
2854 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2857 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2858 return OC_STACK_ERROR;
2861 switch (clientCB->method)
2863 case OC_REST_OBSERVE:
2864 case OC_REST_OBSERVE_ALL:
2866 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2868 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2870 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2872 FindAndDeleteClientCB(clientCB);
2876 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2878 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2879 requestInfo.info.token = clientCB->token;
2880 requestInfo.info.tokenLength = clientCB->tokenLength;
2882 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2883 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2885 return OC_STACK_ERROR;
2887 requestInfo.info.numOptions = numOptions + 1;
2888 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2891 ret = OCSendRequest(&endpoint, &requestInfo);
2893 if (requestInfo.info.options)
2895 OICFree (requestInfo.info.options);
2897 if (requestInfo.info.resourceUri)
2899 OICFree (requestInfo.info.resourceUri);
2904 case OC_REST_DISCOVER:
2905 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2906 clientCB->requestUri);
2907 FindAndDeleteClientCB(clientCB);
2910 #ifdef WITH_PRESENCE
2911 case OC_REST_PRESENCE:
2912 FindAndDeleteClientCB(clientCB);
2917 ret = OC_STACK_INVALID_METHOD;
2925 * @brief Register Persistent storage callback.
2926 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2928 * OC_STACK_OK - No errors; Success
2929 * OC_STACK_INVALID_PARAM - Invalid parameter
2931 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2933 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2934 if(!persistentStorageHandler)
2936 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2937 return OC_STACK_INVALID_PARAM;
2941 if( !persistentStorageHandler->open ||
2942 !persistentStorageHandler->close ||
2943 !persistentStorageHandler->read ||
2944 !persistentStorageHandler->unlink ||
2945 !persistentStorageHandler->write)
2947 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2948 return OC_STACK_INVALID_PARAM;
2951 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2954 #ifdef WITH_PRESENCE
2956 OCStackResult OCProcessPresence()
2958 OCStackResult result = OC_STACK_OK;
2960 // the following line floods the log with messages that are irrelevant
2961 // to most purposes. Uncomment as needed.
2962 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2963 ClientCB* cbNode = NULL;
2964 OCClientResponse clientResponse;
2965 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2967 LL_FOREACH(cbList, cbNode)
2969 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2974 uint32_t now = GetTicks(0);
2975 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2976 cbNode->presence->TTLlevel);
2977 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2979 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2984 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2986 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2987 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2989 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2991 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2993 clientResponse.sequenceNumber = 0;
2994 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2995 clientResponse.devAddr = *cbNode->devAddr;
2996 FixUpClientResponse(&clientResponse);
2997 clientResponse.payload = NULL;
2999 // Increment the TTLLevel (going to a next state), so we don't keep
3000 // sending presence notification to client.
3001 cbNode->presence->TTLlevel++;
3002 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3003 cbNode->presence->TTLlevel);
3005 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3006 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3008 FindAndDeleteClientCB(cbNode);
3012 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3017 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3018 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3019 CARequestInfo_t requestInfo = {.method = CA_GET};
3021 OIC_LOG(DEBUG, TAG, "time to test server presence");
3023 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3025 requestData.type = CA_MSG_NONCONFIRM;
3026 requestData.token = cbNode->token;
3027 requestData.tokenLength = cbNode->tokenLength;
3028 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3029 requestInfo.method = CA_GET;
3030 requestInfo.info = requestData;
3032 result = OCSendRequest(&endpoint, &requestInfo);
3033 if (OC_STACK_OK != result)
3038 cbNode->presence->TTLlevel++;
3039 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3042 if (result != OC_STACK_OK)
3044 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3049 #endif // WITH_PRESENCE
3051 OCStackResult OCProcess()
3053 #ifdef WITH_PRESENCE
3054 OCProcessPresence();
3056 CAHandleRequestResponse();
3058 #ifdef ROUTING_GATEWAY
3068 #ifdef WITH_PRESENCE
3069 OCStackResult OCStartPresence(const uint32_t ttl)
3071 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3072 OCChangeResourceProperty(
3073 &(((OCResource *)presenceResource.handle)->resourceProperties),
3076 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3078 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3079 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3083 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3084 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3088 presenceResource.presenceTTL = ttl;
3090 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3092 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3094 presenceState = OC_PRESENCE_INITIALIZED;
3096 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3098 CAToken_t caToken = NULL;
3099 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3100 if (caResult != CA_STATUS_OK)
3102 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3103 CADestroyToken(caToken);
3104 return OC_STACK_ERROR;
3107 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3108 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3109 CADestroyToken(caToken);
3112 // Each time OCStartPresence is called
3113 // a different random 32-bit integer number is used
3114 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3116 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3117 OC_PRESENCE_TRIGGER_CREATE);
3120 OCStackResult OCStopPresence()
3122 OCStackResult result = OC_STACK_ERROR;
3124 if(presenceResource.handle)
3126 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3128 // make resource inactive
3129 result = OCChangeResourceProperty(
3130 &(((OCResource *) presenceResource.handle)->resourceProperties),
3134 if(result != OC_STACK_OK)
3137 "Changing the presence resource properties to ACTIVE not successful");
3141 return SendStopNotification();
3145 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3146 void* callbackParameter)
3148 defaultDeviceHandler = entityHandler;
3149 defaultDeviceHandlerCallbackParameter = callbackParameter;
3154 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3156 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3158 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3160 if (validatePlatformInfo(platformInfo))
3162 return SavePlatformInfo(platformInfo);
3166 return OC_STACK_INVALID_PARAM;
3171 return OC_STACK_ERROR;
3175 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3177 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3179 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3181 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3182 return OC_STACK_INVALID_PARAM;
3185 if (deviceInfo.types)
3187 OCStringLL *type = deviceInfo.types;
3188 OCResource *resource = findResource((OCResource *) deviceResource);
3191 return OC_STACK_INVALID_PARAM;
3196 OCBindResourceTypeToResource(deviceResource, type->value);
3200 return SaveDeviceInfo(deviceInfo);
3203 OCStackResult OCCreateResource(OCResourceHandle *handle,
3204 const char *resourceTypeName,
3205 const char *resourceInterfaceName,
3206 const char *uri, OCEntityHandler entityHandler,
3207 void* callbackParam,
3208 uint8_t resourceProperties)
3211 OCResource *pointer = NULL;
3212 OCStackResult result = OC_STACK_ERROR;
3214 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3216 if(myStackMode == OC_CLIENT)
3218 return OC_STACK_INVALID_PARAM;
3220 // Validate parameters
3221 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3223 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3224 return OC_STACK_INVALID_URI;
3226 // Is it presented during resource discovery?
3227 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3229 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3230 return OC_STACK_INVALID_PARAM;
3233 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3235 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3239 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3241 // Make sure resourceProperties bitmask has allowed properties specified
3242 if (resourceProperties
3243 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3244 OC_EXPLICIT_DISCOVERABLE
3253 OIC_LOG(ERROR, TAG, "Invalid property");
3254 return OC_STACK_INVALID_PARAM;
3257 // If the headResource is NULL, then no resources have been created...
3258 pointer = headResource;
3261 // At least one resources is in the resource list, so we need to search for
3262 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3265 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3267 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3268 return OC_STACK_INVALID_PARAM;
3270 pointer = pointer->next;
3273 // Create the pointer and insert it into the resource list
3274 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3277 result = OC_STACK_NO_MEMORY;
3280 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3282 insertResource(pointer);
3285 pointer->uri = OICStrdup(uri);
3288 result = OC_STACK_NO_MEMORY;
3292 // Set properties. Set OC_ACTIVE
3293 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3296 // Add the resourcetype to the resource
3297 result = BindResourceTypeToResource(pointer, resourceTypeName);
3298 if (result != OC_STACK_OK)
3300 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3304 // Add the resourceinterface to the resource
3305 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3306 if (result != OC_STACK_OK)
3308 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3312 // If an entity handler has been passed, attach it to the newly created
3313 // resource. Otherwise, set the default entity handler.
3316 pointer->entityHandler = entityHandler;
3317 pointer->entityHandlerCallbackParam = callbackParam;
3321 pointer->entityHandler = defaultResourceEHandler;
3322 pointer->entityHandlerCallbackParam = NULL;
3325 // Initialize a pointer indicating child resources in case of collection
3326 pointer->rsrcChildResourcesHead = NULL;
3329 result = OC_STACK_OK;
3331 #ifdef WITH_PRESENCE
3332 if (presenceResource.handle)
3334 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3335 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3339 if (result != OC_STACK_OK)
3341 // Deep delete of resource and other dynamic elements that it contains
3342 deleteResource(pointer);
3347 OCStackResult OCBindResource(
3348 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3350 OCResource *resource = NULL;
3351 OCChildResource *tempChildResource = NULL;
3352 OCChildResource *newChildResource = NULL;
3354 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3356 // Validate parameters
3357 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3358 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3359 // Container cannot contain itself
3360 if (collectionHandle == resourceHandle)
3362 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3363 return OC_STACK_INVALID_PARAM;
3366 // Use the handle to find the resource in the resource linked list
3367 resource = findResource((OCResource *) collectionHandle);
3370 OIC_LOG(ERROR, TAG, "Collection handle not found");
3371 return OC_STACK_INVALID_PARAM;
3374 // Look for an open slot to add add the child resource.
3375 // If found, add it and return success
3377 tempChildResource = resource->rsrcChildResourcesHead;
3379 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3381 // TODO: what if one of child resource was deregistered without unbinding?
3382 tempChildResource = tempChildResource->next;
3385 // Do memory allocation for child resource
3386 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3387 if(!newChildResource)
3389 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3390 return OC_STACK_ERROR;
3393 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3394 newChildResource->next = NULL;
3396 if(!resource->rsrcChildResourcesHead)
3398 resource->rsrcChildResourcesHead = newChildResource;
3401 tempChildResource->next = newChildResource;
3404 OIC_LOG(INFO, TAG, "resource bound");
3406 #ifdef WITH_PRESENCE
3407 if (presenceResource.handle)
3409 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3410 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3411 OC_PRESENCE_TRIGGER_CHANGE);
3418 OCStackResult OCUnBindResource(
3419 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3421 OCResource *resource = NULL;
3422 OCChildResource *tempChildResource = NULL;
3423 OCChildResource *tempLastChildResource = NULL;
3425 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3427 // Validate parameters
3428 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3429 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3430 // Container cannot contain itself
3431 if (collectionHandle == resourceHandle)
3433 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3434 return OC_STACK_INVALID_PARAM;
3437 // Use the handle to find the resource in the resource linked list
3438 resource = findResource((OCResource *) collectionHandle);
3441 OIC_LOG(ERROR, TAG, "Collection handle not found");
3442 return OC_STACK_INVALID_PARAM;
3445 // Look for an open slot to add add the child resource.
3446 // If found, add it and return success
3447 if(!resource->rsrcChildResourcesHead)
3449 OIC_LOG(INFO, TAG, "resource not found in collection");
3451 // Unable to add resourceHandle, so return error
3452 return OC_STACK_ERROR;
3456 tempChildResource = resource->rsrcChildResourcesHead;
3458 while (tempChildResource)
3460 if(tempChildResource->rsrcResource == resourceHandle)
3462 // if resource going to be unbinded is the head one.
3463 if( tempChildResource == resource->rsrcChildResourcesHead )
3465 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3466 OICFree(resource->rsrcChildResourcesHead);
3467 resource->rsrcChildResourcesHead = temp;
3472 OCChildResource *temp = tempChildResource->next;
3473 OICFree(tempChildResource);
3474 tempLastChildResource->next = temp;
3478 OIC_LOG(INFO, TAG, "resource unbound");
3480 // Send notification when resource is unbounded successfully.
3481 #ifdef WITH_PRESENCE
3482 if (presenceResource.handle)
3484 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3485 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3486 OC_PRESENCE_TRIGGER_CHANGE);
3489 tempChildResource = NULL;
3490 tempLastChildResource = NULL;
3496 tempLastChildResource = tempChildResource;
3497 tempChildResource = tempChildResource->next;
3500 OIC_LOG(INFO, TAG, "resource not found in collection");
3502 tempChildResource = NULL;
3503 tempLastChildResource = NULL;
3505 // Unable to add resourceHandle, so return error
3506 return OC_STACK_ERROR;
3509 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3511 if (!resourceItemName)
3515 // Per RFC 6690 only registered values must follow the first rule below.
3516 // At this point in time the only values registered begin with "core", and
3517 // all other values are specified as opaque strings where multiple values
3518 // are separated by a space.
3519 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3521 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3523 if (resourceItemName[index] != '.'
3524 && resourceItemName[index] != '-'
3525 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3526 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3534 for (size_t index = 0; resourceItemName[index]; ++index)
3536 if (resourceItemName[index] == ' '
3537 || resourceItemName[index] == '\t'
3538 || resourceItemName[index] == '\r'
3539 || resourceItemName[index] == '\n')
3549 OCStackResult BindResourceTypeToResource(OCResource* resource,
3550 const char *resourceTypeName)
3552 OCResourceType *pointer = NULL;
3554 OCStackResult result = OC_STACK_ERROR;
3556 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3558 if (!ValidateResourceTypeInterface(resourceTypeName))
3560 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3561 return OC_STACK_INVALID_PARAM;
3564 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3567 result = OC_STACK_NO_MEMORY;
3571 str = OICStrdup(resourceTypeName);
3574 result = OC_STACK_NO_MEMORY;
3577 pointer->resourcetypename = str;
3578 pointer->next = NULL;
3580 insertResourceType(resource, pointer);
3581 result = OC_STACK_OK;
3584 if (result != OC_STACK_OK)
3593 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3594 const char *resourceInterfaceName)
3596 OCResourceInterface *pointer = NULL;
3598 OCStackResult result = OC_STACK_ERROR;
3600 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3602 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3604 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3605 return OC_STACK_INVALID_PARAM;
3608 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3610 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3613 result = OC_STACK_NO_MEMORY;
3617 str = OICStrdup(resourceInterfaceName);
3620 result = OC_STACK_NO_MEMORY;
3623 pointer->name = str;
3625 // Bind the resourceinterface to the resource
3626 insertResourceInterface(resource, pointer);
3628 result = OC_STACK_OK;
3631 if (result != OC_STACK_OK)
3640 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3641 const char *resourceTypeName)
3644 OCStackResult result = OC_STACK_ERROR;
3645 OCResource *resource = NULL;
3647 resource = findResource((OCResource *) handle);
3650 OIC_LOG(ERROR, TAG, "Resource not found");
3651 return OC_STACK_ERROR;
3654 result = BindResourceTypeToResource(resource, resourceTypeName);
3656 #ifdef WITH_PRESENCE
3657 if(presenceResource.handle)
3659 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3660 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3667 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3668 const char *resourceInterfaceName)
3671 OCStackResult result = OC_STACK_ERROR;
3672 OCResource *resource = NULL;
3674 resource = findResource((OCResource *) handle);
3677 OIC_LOG(ERROR, TAG, "Resource not found");
3678 return OC_STACK_ERROR;
3681 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3683 #ifdef WITH_PRESENCE
3684 if (presenceResource.handle)
3686 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3687 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3694 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3696 OCResource *pointer = headResource;
3698 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3702 *numResources = *numResources + 1;
3703 pointer = pointer->next;
3708 OCResourceHandle OCGetResourceHandle(uint8_t index)
3710 OCResource *pointer = headResource;
3712 for( uint8_t i = 0; i < index && pointer; ++i)
3714 pointer = pointer->next;
3716 return (OCResourceHandle) pointer;
3719 OCStackResult OCDeleteResource(OCResourceHandle handle)
3723 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3724 return OC_STACK_INVALID_PARAM;
3727 OCResource *resource = findResource((OCResource *) handle);
3728 if (resource == NULL)
3730 OIC_LOG(ERROR, TAG, "Resource not found");
3731 return OC_STACK_NO_RESOURCE;
3734 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3736 OIC_LOG(ERROR, TAG, "Error deleting resource");
3737 return OC_STACK_ERROR;
3743 const char *OCGetResourceUri(OCResourceHandle handle)
3745 OCResource *resource = NULL;
3747 resource = findResource((OCResource *) handle);
3750 return resource->uri;
3752 return (const char *) NULL;
3755 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3757 OCResource *resource = NULL;
3759 resource = findResource((OCResource *) handle);
3762 return resource->resourceProperties;
3764 return (OCResourceProperty)-1;
3767 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3768 uint8_t *numResourceTypes)
3770 OCResource *resource = NULL;
3771 OCResourceType *pointer = NULL;
3773 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3774 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3776 *numResourceTypes = 0;
3778 resource = findResource((OCResource *) handle);
3781 pointer = resource->rsrcType;
3784 *numResourceTypes = *numResourceTypes + 1;
3785 pointer = pointer->next;
3791 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3793 OCResourceType *resourceType = NULL;
3795 resourceType = findResourceTypeAtIndex(handle, index);
3798 return resourceType->resourcetypename;
3800 return (const char *) NULL;
3803 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3804 uint8_t *numResourceInterfaces)
3806 OCResourceInterface *pointer = NULL;
3807 OCResource *resource = NULL;
3809 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3810 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3812 *numResourceInterfaces = 0;
3813 resource = findResource((OCResource *) handle);
3816 pointer = resource->rsrcInterface;
3819 *numResourceInterfaces = *numResourceInterfaces + 1;
3820 pointer = pointer->next;
3826 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3828 OCResourceInterface *resourceInterface = NULL;
3830 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3831 if (resourceInterface)
3833 return resourceInterface->name;
3835 return (const char *) NULL;
3838 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3841 OCResource *resource = NULL;
3842 OCChildResource *tempChildResource = NULL;
3845 resource = findResource((OCResource *) collectionHandle);
3851 tempChildResource = resource->rsrcChildResourcesHead;
3853 while(tempChildResource)
3857 return tempChildResource->rsrcResource;
3860 tempChildResource = tempChildResource->next;
3863 // In this case, the number of resource handles in the collection exceeds the index
3864 tempChildResource = NULL;
3868 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3869 OCEntityHandler entityHandler,
3870 void* callbackParam)
3872 OCResource *resource = NULL;
3874 // Validate parameters
3875 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3877 // Use the handle to find the resource in the resource linked list
3878 resource = findResource((OCResource *)handle);
3881 OIC_LOG(ERROR, TAG, "Resource not found");
3882 return OC_STACK_ERROR;
3886 resource->entityHandler = entityHandler;
3887 resource->entityHandlerCallbackParam = callbackParam;
3889 #ifdef WITH_PRESENCE
3890 if (presenceResource.handle)
3892 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3893 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3900 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3902 OCResource *resource = NULL;
3904 resource = findResource((OCResource *)handle);
3907 OIC_LOG(ERROR, TAG, "Resource not found");
3912 return resource->entityHandler;
3915 void incrementSequenceNumber(OCResource * resPtr)
3917 // Increment the sequence number
3918 resPtr->sequenceNum += 1;
3919 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3921 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3926 #ifdef WITH_PRESENCE
3927 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3928 OCPresenceTrigger trigger)
3930 OCResource *resPtr = NULL;
3931 OCStackResult result = OC_STACK_ERROR;
3932 OCMethod method = OC_REST_PRESENCE;
3933 uint32_t maxAge = 0;
3934 resPtr = findResource((OCResource *) presenceResource.handle);
3937 return OC_STACK_NO_RESOURCE;
3940 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3942 maxAge = presenceResource.presenceTTL;
3944 result = SendAllObserverNotification(method, resPtr, maxAge,
3945 trigger, resourceType, OC_LOW_QOS);
3951 OCStackResult SendStopNotification()
3953 OCResource *resPtr = NULL;
3954 OCStackResult result = OC_STACK_ERROR;
3955 OCMethod method = OC_REST_PRESENCE;
3956 resPtr = findResource((OCResource *) presenceResource.handle);
3959 return OC_STACK_NO_RESOURCE;
3962 // maxAge is 0. ResourceType is NULL.
3963 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3969 #endif // WITH_PRESENCE
3970 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3972 OCResource *resPtr = NULL;
3973 OCStackResult result = OC_STACK_ERROR;
3974 OCMethod method = OC_REST_NOMETHOD;
3975 uint32_t maxAge = 0;
3977 OIC_LOG(INFO, TAG, "Notifying all observers");
3978 #ifdef WITH_PRESENCE
3979 if(handle == presenceResource.handle)
3983 #endif // WITH_PRESENCE
3984 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3986 // Verify that the resource exists
3987 resPtr = findResource ((OCResource *) handle);
3990 return OC_STACK_NO_RESOURCE;
3994 //only increment in the case of regular observing (not presence)
3995 incrementSequenceNumber(resPtr);
3996 method = OC_REST_OBSERVE;
3997 maxAge = MAX_OBSERVE_AGE;
3998 #ifdef WITH_PRESENCE
3999 result = SendAllObserverNotification (method, resPtr, maxAge,
4000 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4002 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4009 OCNotifyListOfObservers (OCResourceHandle handle,
4010 OCObservationId *obsIdList,
4011 uint8_t numberOfIds,
4012 const OCRepPayload *payload,
4013 OCQualityOfService qos)
4015 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4017 OCResource *resPtr = NULL;
4018 //TODO: we should allow the server to define this
4019 uint32_t maxAge = MAX_OBSERVE_AGE;
4021 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4022 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4023 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4025 resPtr = findResource ((OCResource *) handle);
4026 if (NULL == resPtr || myStackMode == OC_CLIENT)
4028 return OC_STACK_NO_RESOURCE;
4032 incrementSequenceNumber(resPtr);
4034 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4035 payload, maxAge, qos));
4038 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4040 OCStackResult result = OC_STACK_ERROR;
4041 OCServerRequest *serverRequest = NULL;
4043 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4045 // Validate input parameters
4046 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4047 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4050 // Get pointer to request info
4051 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4054 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4055 result = serverRequest->ehResponseHandler(ehResponse);
4061 //#ifdef DIRECT_PAIRING
4062 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4064 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4065 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4067 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4071 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4074 const OCDPDev_t* OCGetDirectPairedDevices()
4076 return (const OCDPDev_t*)DPGetPairedDevices();
4079 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4080 OCDirectPairingCB resultCallback)
4082 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4083 if(NULL == peer || NULL == pinNumber)
4085 OIC_LOG(ERROR, TAG, "Invalid parameters");
4086 return OC_STACK_INVALID_PARAM;
4088 if (NULL == resultCallback)
4090 OIC_LOG(ERROR, TAG, "Invalid callback");
4091 return OC_STACK_INVALID_CALLBACK;
4094 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4095 pinNumber, (OCDirectPairingResultCB)resultCallback);
4097 //#endif // DIRECT_PAIRING
4099 //-----------------------------------------------------------------------------
4100 // Private internal function definitions
4101 //-----------------------------------------------------------------------------
4102 static OCDoHandle GenerateInvocationHandle()
4104 OCDoHandle handle = NULL;
4105 // Generate token here, it will be deleted when the transaction is deleted
4106 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4109 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4115 #ifdef WITH_PRESENCE
4116 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4117 OCResourceProperty resourceProperties, uint8_t enable)
4121 return OC_STACK_INVALID_PARAM;
4123 if (resourceProperties
4124 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4126 OIC_LOG(ERROR, TAG, "Invalid property");
4127 return OC_STACK_INVALID_PARAM;
4131 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4135 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4141 OCStackResult initResources()
4143 OCStackResult result = OC_STACK_OK;
4145 headResource = NULL;
4146 tailResource = NULL;
4147 // Init Virtual Resources
4148 #ifdef WITH_PRESENCE
4149 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4151 result = OCCreateResource(&presenceResource.handle,
4152 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4154 OC_RSRVD_PRESENCE_URI,
4158 //make resource inactive
4159 result = OCChangeResourceProperty(
4160 &(((OCResource *) presenceResource.handle)->resourceProperties),
4163 #ifndef WITH_ARDUINO
4164 if (result == OC_STACK_OK)
4166 result = SRMInitSecureResources();
4170 if(result == OC_STACK_OK)
4172 CreateResetProfile();
4173 result = OCCreateResource(&deviceResource,
4174 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4175 OC_RSRVD_INTERFACE_DEFAULT,
4176 OC_RSRVD_DEVICE_URI,
4180 if(result == OC_STACK_OK)
4182 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4183 OC_RSRVD_INTERFACE_READ);
4187 if(result == OC_STACK_OK)
4189 result = OCCreateResource(&platformResource,
4190 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4191 OC_RSRVD_INTERFACE_DEFAULT,
4192 OC_RSRVD_PLATFORM_URI,
4196 if(result == OC_STACK_OK)
4198 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4199 OC_RSRVD_INTERFACE_READ);
4206 void insertResource(OCResource *resource)
4210 headResource = resource;
4211 tailResource = resource;
4215 tailResource->next = resource;
4216 tailResource = resource;
4218 resource->next = NULL;
4221 OCResource *findResource(OCResource *resource)
4223 OCResource *pointer = headResource;
4227 if (pointer == resource)
4231 pointer = pointer->next;
4236 void deleteAllResources()
4238 OCResource *pointer = headResource;
4239 OCResource *temp = NULL;
4243 temp = pointer->next;
4244 #ifdef WITH_PRESENCE
4245 if (pointer != (OCResource *) presenceResource.handle)
4247 #endif // WITH_PRESENCE
4248 deleteResource(pointer);
4249 #ifdef WITH_PRESENCE
4251 #endif // WITH_PRESENCE
4254 memset(&platformResource, 0, sizeof(platformResource));
4255 memset(&deviceResource, 0, sizeof(deviceResource));
4257 memset(&brokerResource, 0, sizeof(brokerResource));
4260 SRMDeInitSecureResources();
4262 #ifdef WITH_PRESENCE
4263 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4264 // presence notification attributed to their deletion to be processed.
4265 deleteResource((OCResource *) presenceResource.handle);
4266 memset(&presenceResource, 0, sizeof(presenceResource));
4267 #endif // WITH_PRESENCE
4270 OCStackResult deleteResource(OCResource *resource)
4272 OCResource *prev = NULL;
4273 OCResource *temp = NULL;
4276 OIC_LOG(DEBUG,TAG,"resource is NULL");
4277 return OC_STACK_INVALID_PARAM;
4280 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4282 temp = headResource;
4285 if (temp == resource)
4287 // Invalidate all Resource Properties.
4288 resource->resourceProperties = (OCResourceProperty) 0;
4289 #ifdef WITH_PRESENCE
4290 if(resource != (OCResource *) presenceResource.handle)
4292 #endif // WITH_PRESENCE
4293 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4294 #ifdef WITH_PRESENCE
4297 if(presenceResource.handle)
4299 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4300 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4303 // Only resource in list.
4304 if (temp == headResource && temp == tailResource)
4306 headResource = NULL;
4307 tailResource = NULL;
4310 else if (temp == headResource)
4312 headResource = temp->next;
4315 else if (temp == tailResource)
4317 tailResource = prev;
4318 tailResource->next = NULL;
4322 prev->next = temp->next;
4325 deleteResourceElements(temp);
4336 return OC_STACK_ERROR;
4339 void deleteResourceElements(OCResource *resource)
4346 OICFree(resource->uri);
4347 deleteResourceType(resource->rsrcType);
4348 deleteResourceInterface(resource->rsrcInterface);
4351 void deleteResourceType(OCResourceType *resourceType)
4353 OCResourceType *pointer = resourceType;
4354 OCResourceType *next = NULL;
4358 next = pointer->next;
4359 OICFree(pointer->resourcetypename);
4365 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4367 OCResourceInterface *pointer = resourceInterface;
4368 OCResourceInterface *next = NULL;
4372 next = pointer->next;
4373 OICFree(pointer->name);
4379 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4381 OCResourceType *pointer = NULL;
4382 OCResourceType *previous = NULL;
4383 if (!resource || !resourceType)
4387 // resource type list is empty.
4388 else if (!resource->rsrcType)
4390 resource->rsrcType = resourceType;
4394 pointer = resource->rsrcType;
4398 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4400 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4401 OICFree(resourceType->resourcetypename);
4402 OICFree(resourceType);
4406 pointer = pointer->next;
4411 previous->next = resourceType;
4414 resourceType->next = NULL;
4416 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4419 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4421 OCResource *resource = NULL;
4422 OCResourceType *pointer = NULL;
4424 // Find the specified resource
4425 resource = findResource((OCResource *) handle);
4431 // Make sure a resource has a resourcetype
4432 if (!resource->rsrcType)
4437 // Iterate through the list
4438 pointer = resource->rsrcType;
4439 for(uint8_t i = 0; i< index && pointer; ++i)
4441 pointer = pointer->next;
4446 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4448 if(resourceTypeList && resourceTypeName)
4450 OCResourceType * rtPointer = resourceTypeList;
4451 while(resourceTypeName && rtPointer)
4453 if(rtPointer->resourcetypename &&
4454 strcmp(resourceTypeName, (const char *)
4455 (rtPointer->resourcetypename)) == 0)
4459 rtPointer = rtPointer->next;
4467 * Insert a new interface into interface linked list only if not already present.
4468 * If alredy present, 2nd arg is free'd.
4469 * Default interface will always be first if present.
4471 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4473 OCResourceInterface *pointer = NULL;
4474 OCResourceInterface *previous = NULL;
4476 newInterface->next = NULL;
4478 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4480 if (!*firstInterface)
4482 // If first interface is not oic.if.baseline, by default add it as first interface type.
4483 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4485 *firstInterface = newInterface;
4489 OCStackResult result = BindResourceInterfaceToResource(resource, OC_RSRVD_INTERFACE_DEFAULT);
4490 if (result != OC_STACK_OK)
4492 OICFree(newInterface->name);
4493 OICFree(newInterface);
4496 if (*firstInterface)
4498 (*firstInterface)->next = newInterface;
4502 // If once add oic.if.baseline, later too below code take care of freeing memory.
4503 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4505 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4507 OICFree(newInterface->name);
4508 OICFree(newInterface);
4511 // This code will not hit anymore, keeping
4514 newInterface->next = *firstInterface;
4515 *firstInterface = newInterface;
4520 pointer = *firstInterface;
4523 if (strcmp(newInterface->name, pointer->name) == 0)
4525 OICFree(newInterface->name);
4526 OICFree(newInterface);
4530 pointer = pointer->next;
4535 previous->next = newInterface;
4540 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4543 OCResource *resource = NULL;
4544 OCResourceInterface *pointer = NULL;
4546 // Find the specified resource
4547 resource = findResource((OCResource *) handle);
4553 // Make sure a resource has a resourceinterface
4554 if (!resource->rsrcInterface)
4559 // Iterate through the list
4560 pointer = resource->rsrcInterface;
4562 for (uint8_t i = 0; i < index && pointer; ++i)
4564 pointer = pointer->next;
4570 * This function splits the uri using the '?' delimiter.
4571 * "uriWithoutQuery" is the block of characters between the beginning
4572 * till the delimiter or '\0' which ever comes first.
4573 * "query" is whatever is to the right of the delimiter if present.
4574 * No delimiter sets the query to NULL.
4575 * If either are present, they will be malloc'ed into the params 2, 3.
4576 * The first param, *uri is left untouched.
4578 * NOTE: This function does not account for whitespace at the end of the uri NOR
4579 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4580 * part of the query.
4582 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4586 return OC_STACK_INVALID_URI;
4588 if(!query || !uriWithoutQuery)
4590 return OC_STACK_INVALID_PARAM;
4594 *uriWithoutQuery = NULL;
4596 size_t uriWithoutQueryLen = 0;
4597 size_t queryLen = 0;
4598 size_t uriLen = strlen(uri);
4600 char *pointerToDelimiter = strstr(uri, "?");
4602 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4603 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4605 if (uriWithoutQueryLen)
4607 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4608 if (!*uriWithoutQuery)
4612 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4616 *query = (char *) OICCalloc(queryLen + 1, 1);
4619 OICFree(*uriWithoutQuery);
4620 *uriWithoutQuery = NULL;
4623 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4629 return OC_STACK_NO_MEMORY;
4632 static const OicUuid_t* OCGetServerInstanceID(void)
4634 static bool generated = false;
4635 static OicUuid_t sid;
4641 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4643 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4650 const char* OCGetServerInstanceIDString(void)
4652 static bool generated = false;
4653 static char sidStr[UUID_STRING_SIZE];
4660 const OicUuid_t *sid = OCGetServerInstanceID();
4661 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4663 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4671 CAResult_t OCSelectNetwork()
4673 CAResult_t retResult = CA_STATUS_FAILED;
4674 CAResult_t caResult = CA_STATUS_OK;
4676 CATransportAdapter_t connTypes[] = {
4678 CA_ADAPTER_RFCOMM_BTEDR,
4679 CA_ADAPTER_GATT_BTLE,
4682 ,CA_ADAPTER_REMOTE_ACCESS
4689 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4691 for(int i = 0; i<numConnTypes; i++)
4693 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4694 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4696 caResult = CASelectNetwork(connTypes[i]);
4697 if(caResult == CA_STATUS_OK)
4699 retResult = CA_STATUS_OK;
4704 if(retResult != CA_STATUS_OK)
4706 return caResult; // Returns error of appropriate transport that failed fatally.
4712 OCStackResult CAResultToOCResult(CAResult_t caResult)
4718 case CA_STATUS_INVALID_PARAM:
4719 return OC_STACK_INVALID_PARAM;
4720 case CA_ADAPTER_NOT_ENABLED:
4721 return OC_STACK_ADAPTER_NOT_ENABLED;
4722 case CA_SERVER_STARTED_ALREADY:
4724 case CA_SERVER_NOT_STARTED:
4725 return OC_STACK_ERROR;
4726 case CA_DESTINATION_NOT_REACHABLE:
4727 return OC_STACK_COMM_ERROR;
4728 case CA_SOCKET_OPERATION_FAILED:
4729 return OC_STACK_COMM_ERROR;
4730 case CA_SEND_FAILED:
4731 return OC_STACK_COMM_ERROR;
4732 case CA_RECEIVE_FAILED:
4733 return OC_STACK_COMM_ERROR;
4734 case CA_MEMORY_ALLOC_FAILED:
4735 return OC_STACK_NO_MEMORY;
4736 case CA_REQUEST_TIMEOUT:
4737 return OC_STACK_TIMEOUT;
4738 case CA_DESTINATION_DISCONNECTED:
4739 return OC_STACK_COMM_ERROR;
4740 case CA_STATUS_FAILED:
4741 return OC_STACK_ERROR;
4742 case CA_NOT_SUPPORTED:
4743 return OC_STACK_NOTIMPL;
4745 return OC_STACK_ERROR;
4749 bool OCResultToSuccess(OCStackResult ocResult)
4754 case OC_STACK_RESOURCE_CREATED:
4755 case OC_STACK_RESOURCE_DELETED:
4756 case OC_STACK_CONTINUE:
4757 case OC_STACK_RESOURCE_CHANGED: