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 "doxmresource.h"
56 #include "cainterface.h"
57 #include "ocpayload.h"
58 #include "ocpayloadcbor.h"
59 #include "platform_features.h"
61 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
62 #include "routingutility.h"
63 #ifdef ROUTING_GATEWAY
64 #include "routingmanager.h"
69 #include "oickeepalive.h"
72 //#ifdef DIRECT_PAIRING
73 #include "directpairing.h"
76 #ifdef HAVE_ARDUINO_TIME_H
79 #ifdef HAVE_SYS_TIME_H
82 #include "coap_time.h"
86 #ifdef HAVE_ARPA_INET_H
87 #include <arpa/inet.h>
91 #define UINT32_MAX (0xFFFFFFFFUL)
94 //-----------------------------------------------------------------------------
96 //-----------------------------------------------------------------------------
99 OC_STACK_UNINITIALIZED = 0,
100 OC_STACK_INITIALIZED,
101 OC_STACK_UNINIT_IN_PROGRESS
107 OC_PRESENCE_UNINITIALIZED = 0,
108 OC_PRESENCE_INITIALIZED
112 //-----------------------------------------------------------------------------
114 //-----------------------------------------------------------------------------
115 static OCStackState stackState = OC_STACK_UNINITIALIZED;
117 OCResource *headResource = NULL;
118 static OCResource *tailResource = NULL;
119 static OCResourceHandle platformResource = {0};
120 static OCResourceHandle deviceResource = {0};
122 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
123 static PresenceResource presenceResource = {0};
124 static uint8_t PresenceTimeOutSize = 0;
125 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
128 static OCMode myStackMode;
130 //TODO: revisit this design
131 static bool gRASetInfo = false;
133 OCDeviceEntityHandler defaultDeviceHandler;
134 void* defaultDeviceHandlerCallbackParameter = NULL;
135 static const char COAP_TCP[] = "coap+tcp:";
136 static const char CORESPEC[] = "core";
138 //-----------------------------------------------------------------------------
140 //-----------------------------------------------------------------------------
141 #define TAG "OIC_RI_STACK"
142 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
143 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
144 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
145 TAG, #arg " is NULL"); return (retVal); } }
146 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
147 TAG, #arg " is NULL"); return; } }
148 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
151 //TODO: we should allow the server to define this
152 #define MAX_OBSERVE_AGE (0x2FFFFUL)
154 #define MILLISECONDS_PER_SECOND (1000)
156 //-----------------------------------------------------------------------------
157 // Private internal function prototypes
158 //-----------------------------------------------------------------------------
161 * Generate handle of OCDoResource invocation for callback management.
163 * @return Generated OCDoResource handle.
165 static OCDoHandle GenerateInvocationHandle();
168 * Initialize resource data structures, variables, etc.
170 * @return ::OC_STACK_OK on success, some other value upon failure.
172 static OCStackResult initResources();
175 * Add a resource to the end of the linked list of resources.
177 * @param resource Resource to be added
179 static void insertResource(OCResource *resource);
182 * Find a resource in the linked list of resources.
184 * @param resource Resource to be found.
185 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
188 static OCResource *findResource(OCResource *resource);
191 * Insert a resource type into a resource's resource type linked list.
192 * If resource type already exists, it will not be inserted and the
193 * resourceType will be free'd.
194 * resourceType->next should be null to avoid memory leaks.
195 * Function returns silently for null args.
197 * @param resource Resource where resource type is to be inserted.
198 * @param resourceType Resource type to be inserted.
200 static void insertResourceType(OCResource *resource,
201 OCResourceType *resourceType);
204 * Get a resource type at the specified index within a resource.
206 * @param handle Handle of resource.
207 * @param index Index of resource type.
209 * @return Pointer to resource type if found, NULL otherwise.
211 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
215 * Insert a resource interface into a resource's resource interface linked list.
216 * If resource interface already exists, it will not be inserted and the
217 * resourceInterface will be free'd.
218 * resourceInterface->next should be null to avoid memory leaks.
220 * @param resource Resource where resource interface is to be inserted.
221 * @param resourceInterface Resource interface to be inserted.
223 static void insertResourceInterface(OCResource *resource,
224 OCResourceInterface *resourceInterface);
227 * Get a resource interface at the specified index within a resource.
229 * @param handle Handle of resource.
230 * @param index Index of resource interface.
232 * @return Pointer to resource interface if found, NULL otherwise.
234 static OCResourceInterface *findResourceInterfaceAtIndex(
235 OCResourceHandle handle, uint8_t index);
238 * Delete all of the dynamically allocated elements that were created for the resource type.
240 * @param resourceType Specified resource type.
242 static void deleteResourceType(OCResourceType *resourceType);
245 * Delete all of the dynamically allocated elements that were created for the resource interface.
247 * @param resourceInterface Specified resource interface.
249 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
252 * Delete all of the dynamically allocated elements that were created for the resource.
254 * @param resource Specified resource.
256 static void deleteResourceElements(OCResource *resource);
259 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
262 * @param handle Handle of resource to be deleted.
264 * @return ::OC_STACK_OK on success, some other value upon failure.
266 static OCStackResult deleteResource(OCResource *resource);
269 * Delete all of the resources in the resource list.
271 static void deleteAllResources();
274 * Increment resource sequence number. Handles rollover.
276 * @param resPtr Pointer to resource.
278 static void incrementSequenceNumber(OCResource * resPtr);
281 * Attempts to initialize every network interface that the CA Layer might have compiled in.
283 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
284 * return something other than @ref CA_STATUS_OK, then this function fails.
286 * @return ::CA_STATUS_OK on success, some other value upon failure.
288 static CAResult_t OCSelectNetwork();
291 * Get the CoAP ticks after the specified number of milli-seconds.
293 * @param afterMilliSeconds Milli-seconds.
297 static uint32_t GetTicks(uint32_t afterMilliSeconds);
300 * Convert CAResult_t to OCStackResult.
302 * @param caResult CAResult_t code.
303 * @return ::OC_STACK_OK on success, some other value upon failure.
305 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
308 * Convert CAResponseResult_t to OCStackResult.
310 * @param caCode CAResponseResult_t code.
311 * @return ::OC_STACK_OK on success, some other value upon failure.
313 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
316 * Convert OCStackResult to CAResponseResult_t.
318 * @param caCode OCStackResult code.
319 * @param method OCMethod method the return code replies to.
320 * @return ::CA_CONTENT on OK, some other value upon failure.
322 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
325 * Convert OCTransportFlags_t to CATransportModifiers_t.
327 * @param ocConType OCTransportFlags_t input.
328 * @return CATransportFlags
330 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
333 * Convert CATransportFlags_t to OCTransportModifiers_t.
335 * @param caConType CATransportFlags_t input.
336 * @return OCTransportFlags
338 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
341 * Handle response from presence request.
343 * @param endPoint CA remote endpoint.
344 * @param responseInfo CA response info.
345 * @return ::OC_STACK_OK on success, some other value upon failure.
347 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
348 const CAResponseInfo_t *responseInfo);
351 * This function will be called back by CA layer when a response is received.
353 * @param endPoint CA remote endpoint.
354 * @param responseInfo CA response info.
356 static void HandleCAResponses(const CAEndpoint_t* endPoint,
357 const CAResponseInfo_t* responseInfo);
360 * This function will be called back by CA layer when a request is received.
362 * @param endPoint CA remote endpoint.
363 * @param requestInfo CA request info.
365 static void HandleCARequests(const CAEndpoint_t* endPoint,
366 const CARequestInfo_t* requestInfo);
369 * Extract query from a URI.
371 * @param uri Full URI with query.
372 * @param query Pointer to string that will contain query.
373 * @param newURI Pointer to string that will contain URI.
374 * @return ::OC_STACK_OK on success, some other value upon failure.
376 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
379 * Finds a resource type in an OCResourceType link-list.
381 * @param resourceTypeList The link-list to be searched through.
382 * @param resourceTypeName The key to search for.
384 * @return Resource type that matches the key (ie. resourceTypeName) or
385 * NULL if there is either an invalid parameter or this function was unable to find the key.
387 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
388 const char * resourceTypeName);
391 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
392 * TTL will be set to maxAge.
394 * @param cbNode Callback Node for which presence ttl is to be reset.
395 * @param maxAge New value of ttl in seconds.
397 * @return ::OC_STACK_OK on success, some other value upon failure.
399 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
402 * Ensure the accept header option is set appropriatly before sending the requests and routing
403 * header option is updated with destination.
405 * @param object CA remote endpoint.
406 * @param requestInfo CA request info.
408 * @return ::OC_STACK_OK on success, some other value upon failure.
410 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
412 //-----------------------------------------------------------------------------
413 // Internal functions
414 //-----------------------------------------------------------------------------
416 uint32_t GetTicks(uint32_t afterMilliSeconds)
421 // Guard against overflow of uint32_t
422 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
423 COAP_TICKS_PER_SECOND)
425 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
433 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
435 VERIFY_NON_NULL_NR(in, FATAL);
436 VERIFY_NON_NULL_NR(out, FATAL);
438 out->adapter = (OCTransportAdapter)in->adapter;
439 out->flags = CAToOCTransportFlags(in->flags);
440 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
441 out->port = in->port;
442 out->ifindex = in->ifindex;
443 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
444 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
448 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
450 VERIFY_NON_NULL_NR(in, FATAL);
451 VERIFY_NON_NULL_NR(out, FATAL);
453 out->adapter = (CATransportAdapter_t)in->adapter;
454 out->flags = OCToCATransportFlags(in->flags);
455 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
456 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
457 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
459 out->port = in->port;
460 out->ifindex = in->ifindex;
463 void FixUpClientResponse(OCClientResponse *cr)
465 VERIFY_NON_NULL_NR(cr, FATAL);
467 cr->addr = &cr->devAddr;
468 cr->connType = (OCConnectivityType)
469 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
472 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
474 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
475 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
477 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
478 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
479 if (OC_STACK_OK != rmResult)
481 OIC_LOG(ERROR, TAG, "Add destination option failed");
486 // OC stack prefer CBOR encoded payloads.
487 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
488 CAResult_t result = CASendRequest(object, requestInfo);
489 if(CA_STATUS_OK != result)
491 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
492 return CAResultToOCResult(result);
496 //-----------------------------------------------------------------------------
497 // Internal API function
498 //-----------------------------------------------------------------------------
500 // This internal function is called to update the stack with the status of
501 // observers and communication failures
502 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
504 OCStackResult result = OC_STACK_ERROR;
505 ResourceObserver * observer = NULL;
506 OCEntityHandlerRequest ehRequest = {0};
510 case OC_OBSERVER_NOT_INTERESTED:
511 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
512 observer = GetObserverUsingToken (token, tokenLength);
515 result = FormOCEntityHandlerRequest(&ehRequest,
516 (OCRequestHandle)NULL,
519 (OCResourceHandle)NULL,
520 NULL, PAYLOAD_TYPE_REPRESENTATION,
522 OC_OBSERVE_DEREGISTER,
525 if(result != OC_STACK_OK)
529 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
530 observer->resource->entityHandlerCallbackParam);
533 result = DeleteObserverUsingToken (token, tokenLength);
534 if(result == OC_STACK_OK)
536 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
540 result = OC_STACK_OK;
541 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
545 case OC_OBSERVER_STILL_INTERESTED:
546 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
547 observer = GetObserverUsingToken (token, tokenLength);
550 observer->forceHighQos = 0;
551 observer->failedCommCount = 0;
552 result = OC_STACK_OK;
556 result = OC_STACK_OBSERVER_NOT_FOUND;
560 case OC_OBSERVER_FAILED_COMM:
561 OIC_LOG(DEBUG, TAG, "observer is unreachable");
562 observer = GetObserverUsingToken (token, tokenLength);
565 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
567 result = FormOCEntityHandlerRequest(&ehRequest,
568 (OCRequestHandle)NULL,
571 (OCResourceHandle)NULL,
572 NULL, PAYLOAD_TYPE_REPRESENTATION,
574 OC_OBSERVE_DEREGISTER,
577 if(result != OC_STACK_OK)
579 return OC_STACK_ERROR;
581 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
582 observer->resource->entityHandlerCallbackParam);
584 result = DeleteObserverUsingToken (token, tokenLength);
585 if(result == OC_STACK_OK)
587 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
591 result = OC_STACK_OK;
592 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
597 observer->failedCommCount++;
598 result = OC_STACK_CONTINUE;
600 observer->forceHighQos = 1;
601 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
605 OIC_LOG(ERROR, TAG, "Unknown status");
606 result = OC_STACK_ERROR;
612 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
614 OCStackResult ret = OC_STACK_ERROR;
618 case CA_ADAPTER_NOT_ENABLED:
619 case CA_SERVER_NOT_STARTED:
620 ret = OC_STACK_ADAPTER_NOT_ENABLED;
622 case CA_MEMORY_ALLOC_FAILED:
623 ret = OC_STACK_NO_MEMORY;
625 case CA_STATUS_INVALID_PARAM:
626 ret = OC_STACK_INVALID_PARAM;
634 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
636 OCStackResult ret = OC_STACK_ERROR;
641 ret = OC_STACK_RESOURCE_CREATED;
644 ret = OC_STACK_RESOURCE_DELETED;
647 ret = OC_STACK_RESOURCE_CHANGED;
654 ret = OC_STACK_INVALID_QUERY;
656 case CA_UNAUTHORIZED_REQ:
657 ret = OC_STACK_UNAUTHORIZED_REQ;
660 ret = OC_STACK_INVALID_OPTION;
663 ret = OC_STACK_NO_RESOURCE;
665 case CA_RETRANSMIT_TIMEOUT:
666 ret = OC_STACK_COMM_ERROR;
668 case CA_REQUEST_ENTITY_TOO_LARGE:
669 ret = OC_STACK_TOO_LARGE_REQ;
677 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
679 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
688 // This Response Code is like HTTP 204 "No Content" but only used in
689 // response to POST and PUT requests.
693 // This Response Code is like HTTP 200 "OK" but only used in response to
698 // This should not happen but,
699 // give it a value just in case but output an error
701 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
704 case OC_STACK_RESOURCE_CREATED:
707 case OC_STACK_RESOURCE_DELETED:
710 case OC_STACK_INVALID_QUERY:
713 case OC_STACK_INVALID_OPTION:
716 case OC_STACK_NO_RESOURCE:
719 case OC_STACK_COMM_ERROR:
720 ret = CA_RETRANSMIT_TIMEOUT;
722 case OC_STACK_UNAUTHORIZED_REQ:
723 ret = CA_UNAUTHORIZED_REQ;
731 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
733 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
735 // supply default behavior.
736 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
738 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
740 if ((caFlags & OC_MASK_SCOPE) == 0)
742 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
747 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
749 return (OCTransportFlags)caFlags;
752 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
754 uint32_t lowerBound = 0;
755 uint32_t higherBound = 0;
757 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
759 return OC_STACK_INVALID_PARAM;
762 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
764 cbNode->presence->TTL = maxAgeSeconds;
766 for (int index = 0; index < PresenceTimeOutSize; index++)
768 // Guard against overflow
769 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
772 lowerBound = GetTicks((PresenceTimeOut[index] *
773 cbNode->presence->TTL *
774 MILLISECONDS_PER_SECOND)/100);
778 lowerBound = GetTicks(UINT32_MAX);
781 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
784 higherBound = GetTicks((PresenceTimeOut[index + 1] *
785 cbNode->presence->TTL *
786 MILLISECONDS_PER_SECOND)/100);
790 higherBound = GetTicks(UINT32_MAX);
793 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
795 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
796 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
797 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
800 cbNode->presence->TTLlevel = 0;
802 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
806 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
808 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
810 return OC_RSRVD_TRIGGER_CREATE;
812 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
814 return OC_RSRVD_TRIGGER_CHANGE;
818 return OC_RSRVD_TRIGGER_DELETE;
822 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
826 return OC_PRESENCE_TRIGGER_CREATE;
828 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
830 return OC_PRESENCE_TRIGGER_CREATE;
832 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
834 return OC_PRESENCE_TRIGGER_CHANGE;
838 return OC_PRESENCE_TRIGGER_DELETE;
843 * Encode an address string to match RFC6874.
845 * @param outputAddress a char array to be written with the encoded string.
847 * @param outputSize size of outputAddress buffer.
849 * @param inputAddress a char array of size <= CA_MAX_URI_LENGTH
850 * containing a valid IPv6 address string.
852 * @return OC_STACK_OK if encoding succeeded.
853 * Else an error occured.
855 OCStackResult encodeAddressForRFC6874(char *outputAddress,
857 const char *inputAddress)
859 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
860 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
862 /** @todo Use a max IPv6 string length instead of CA_MAX_URI_LENGTH. */
863 #define ENCODE_MAX_INPUT_LENGTH CA_MAX_URI_LENGTH
865 size_t inputLength = strnlen(inputAddress, ENCODE_MAX_INPUT_LENGTH);
867 if (inputLength >= ENCODE_MAX_INPUT_LENGTH)
869 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: too long/unterminated!");
870 return OC_STACK_INVALID_PARAM;
873 // inputSize includes the null terminator
874 size_t inputSize = inputLength + 1;
876 if (inputSize > outputSize)
878 OIC_LOG_V(ERROR, TAG,
879 "encodeAddressForRFC6874 failed: "
880 "outputSize (%d) < inputSize (%d)",
881 outputSize, inputSize);
883 return OC_STACK_ERROR;
886 char* percentChar = strchr(inputAddress, '%');
888 // If there is no '%' character, then no change is required to the string.
889 if (NULL == percentChar)
891 OICStrcpy(outputAddress, outputSize, inputAddress);
895 const char* addressPart = &inputAddress[0];
896 const char* scopeIdPart = percentChar + 1;
898 // Sanity check to make sure this string doesn't have more '%' characters
899 if (NULL != strchr(scopeIdPart, '%'))
901 return OC_STACK_ERROR;
904 // If no string follows the first '%', then the input was invalid.
905 if (scopeIdPart[0] == '\0')
907 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
908 return OC_STACK_ERROR;
911 // Check to see if the string is already encoded
912 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
914 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
915 return OC_STACK_ERROR;
918 // Fail if we don't have room for encoded string's two additional chars
919 if (outputSize < (inputSize + 2))
921 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
922 return OC_STACK_ERROR;
925 // Restore the null terminator with an escaped '%' character, per RFC6874
926 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
927 strcat(outputAddress, "%25");
928 strcat(outputAddress, scopeIdPart);
934 * The cononical presence allows constructed URIs to be string compared.
936 * requestUri must be a char array of size CA_MAX_URI_LENGTH
938 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
941 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
942 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
943 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
945 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
947 if (ep->adapter == CA_ADAPTER_IP)
949 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
951 if ('\0' == ep->addr[0]) // multicast
953 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
957 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
959 OCStackResult result = encodeAddressForRFC6874(addressEncoded,
960 sizeof(addressEncoded),
963 if (OC_STACK_OK != result)
968 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
969 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
974 if ('\0' == ep->addr[0]) // multicast
976 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
977 ep->port = OC_MULTICAST_PORT;
979 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
980 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
984 // might work for other adapters (untested, but better than nothing)
985 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
986 OC_RSRVD_PRESENCE_URI);
990 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
991 const CAResponseInfo_t *responseInfo)
993 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
994 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
996 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
997 ClientCB * cbNode = NULL;
998 char *resourceTypeName = NULL;
999 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1000 OCStackResult result = OC_STACK_ERROR;
1001 uint32_t maxAge = 0;
1003 char presenceUri[CA_MAX_URI_LENGTH];
1005 int presenceSubscribe = 0;
1006 int multicastPresenceSubscribe = 0;
1008 if (responseInfo->result != CA_CONTENT)
1010 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1011 return OC_STACK_ERROR;
1014 // check for unicast presence
1015 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
1016 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1018 return OC_STACK_INVALID_URI;
1021 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1024 presenceSubscribe = 1;
1028 // check for multiicast presence
1029 CAEndpoint_t ep = { .adapter = endpoint->adapter,
1030 .flags = endpoint->flags };
1032 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
1034 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1037 multicastPresenceSubscribe = 1;
1041 if (!presenceSubscribe && !multicastPresenceSubscribe)
1043 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1047 response.payload = NULL;
1048 response.result = OC_STACK_OK;
1050 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1051 FixUpClientResponse(&response);
1053 if (responseInfo->info.payload)
1055 result = OCParsePayload(&response.payload,
1056 PAYLOAD_TYPE_PRESENCE,
1057 responseInfo->info.payload,
1058 responseInfo->info.payloadSize);
1060 if(result != OC_STACK_OK)
1062 OIC_LOG(ERROR, TAG, "Presence parse failed");
1065 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1067 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1068 result = OC_STACK_ERROR;
1071 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1072 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1073 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1076 if (presenceSubscribe)
1078 if(cbNode->sequenceNumber == response.sequenceNumber)
1080 OIC_LOG(INFO, TAG, "No presence change");
1081 ResetPresenceTTL(cbNode, maxAge);
1082 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1088 OIC_LOG(INFO, TAG, "Stopping presence");
1089 response.result = OC_STACK_PRESENCE_STOPPED;
1090 if(cbNode->presence)
1092 OICFree(cbNode->presence->timeOut);
1093 OICFree(cbNode->presence);
1094 cbNode->presence = NULL;
1099 if(!cbNode->presence)
1101 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1103 if(!(cbNode->presence))
1105 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1106 result = OC_STACK_NO_MEMORY;
1110 VERIFY_NON_NULL_V(cbNode->presence);
1111 cbNode->presence->timeOut = NULL;
1112 cbNode->presence->timeOut = (uint32_t *)
1113 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1114 if(!(cbNode->presence->timeOut)){
1116 "Could not allocate memory for cbNode->presence->timeOut");
1117 OICFree(cbNode->presence);
1118 result = OC_STACK_NO_MEMORY;
1123 ResetPresenceTTL(cbNode, maxAge);
1125 cbNode->sequenceNumber = response.sequenceNumber;
1127 // Ensure that a filter is actually applied.
1128 if( resourceTypeName && cbNode->filterResourceType)
1130 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1139 // This is the multicast case
1140 OCMulticastNode* mcNode = NULL;
1141 mcNode = GetMCPresenceNode(presenceUri);
1145 if(mcNode->nonce == response.sequenceNumber)
1147 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1150 mcNode->nonce = response.sequenceNumber;
1154 OIC_LOG(INFO, TAG, "Stopping presence");
1155 response.result = OC_STACK_PRESENCE_STOPPED;
1160 char* uri = OICStrdup(presenceUri);
1164 "No Memory for URI to store in the presence node");
1165 result = OC_STACK_NO_MEMORY;
1169 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1170 if(result == OC_STACK_NO_MEMORY)
1173 "No Memory for Multicast Presence Node");
1177 // presence node now owns uri
1180 // Ensure that a filter is actually applied.
1181 if(resourceTypeName && cbNode->filterResourceType)
1183 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1190 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1192 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1194 FindAndDeleteClientCB(cbNode);
1198 OCPayloadDestroy(response.payload);
1202 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1204 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1206 if(responseInfo->info.resourceUri &&
1207 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1209 HandlePresenceResponse(endPoint, responseInfo);
1213 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1214 responseInfo->info.tokenLength, NULL, NULL);
1216 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1217 responseInfo->info.tokenLength);
1221 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1222 if(responseInfo->result == CA_EMPTY)
1224 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1225 // We do not have a case for the client to receive a RESET
1226 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1228 //This is the case of receiving an ACK on a request to a slow resource!
1229 OIC_LOG(INFO, TAG, "This is a pure ACK");
1230 //TODO: should we inform the client
1231 // app that at least the request was received at the server?
1234 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1236 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1237 OIC_LOG(INFO, TAG, "Calling into application address space");
1239 OCClientResponse response =
1240 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1241 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1242 FixUpClientResponse(&response);
1243 response.resourceUri = responseInfo->info.resourceUri;
1244 memcpy(response.identity.id, responseInfo->info.identity.id,
1245 sizeof (response.identity.id));
1246 response.identity.id_length = responseInfo->info.identity.id_length;
1248 response.result = CAResponseToOCStackResult(responseInfo->result);
1249 cbNode->callBack(cbNode->context,
1250 cbNode->handle, &response);
1251 FindAndDeleteClientCB(cbNode);
1255 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1256 OIC_LOG(INFO, TAG, "Calling into application address space");
1258 OCClientResponse response =
1259 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1260 response.sequenceNumber = -1;
1261 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1262 FixUpClientResponse(&response);
1263 response.resourceUri = responseInfo->info.resourceUri;
1264 memcpy(response.identity.id, responseInfo->info.identity.id,
1265 sizeof (response.identity.id));
1266 response.identity.id_length = responseInfo->info.identity.id_length;
1268 response.result = CAResponseToOCStackResult(responseInfo->result);
1270 if(responseInfo->info.payload &&
1271 responseInfo->info.payloadSize)
1273 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1274 // check the security resource
1275 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1277 type = PAYLOAD_TYPE_SECURITY;
1279 else if (cbNode->method == OC_REST_DISCOVER)
1281 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1282 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1284 type = PAYLOAD_TYPE_DISCOVERY;
1286 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1288 type = PAYLOAD_TYPE_DEVICE;
1290 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1292 type = PAYLOAD_TYPE_PLATFORM;
1294 #ifdef ROUTING_GATEWAY
1295 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1297 type = PAYLOAD_TYPE_REPRESENTATION;
1300 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1302 type = PAYLOAD_TYPE_RD;
1305 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1307 type = PAYLOAD_TYPE_REPRESENTATION;
1312 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1313 cbNode->method, cbNode->requestUri);
1317 else if (cbNode->method == OC_REST_GET ||
1318 cbNode->method == OC_REST_PUT ||
1319 cbNode->method == OC_REST_POST ||
1320 cbNode->method == OC_REST_OBSERVE ||
1321 cbNode->method == OC_REST_OBSERVE_ALL ||
1322 cbNode->method == OC_REST_DELETE)
1324 char targetUri[MAX_URI_LENGTH];
1325 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1326 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1327 if (strcmp(targetUri, cbNode->requestUri) == 0)
1329 type = PAYLOAD_TYPE_RD;
1331 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1333 type = PAYLOAD_TYPE_PLATFORM;
1335 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1337 type = PAYLOAD_TYPE_DEVICE;
1339 if (type == PAYLOAD_TYPE_INVALID)
1341 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1342 cbNode->method, cbNode->requestUri);
1343 type = PAYLOAD_TYPE_REPRESENTATION;
1348 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1349 cbNode->method, cbNode->requestUri);
1353 if(OC_STACK_OK != OCParsePayload(&response.payload,
1355 responseInfo->info.payload,
1356 responseInfo->info.payloadSize))
1358 OIC_LOG(ERROR, TAG, "Error converting payload");
1359 OCPayloadDestroy(response.payload);
1364 response.numRcvdVendorSpecificHeaderOptions = 0;
1365 if(responseInfo->info.numOptions > 0)
1368 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1369 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1372 uint32_t observationOption;
1373 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1374 for (observationOption=0, i=0;
1375 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1379 (observationOption << 8) | optionData[i];
1381 response.sequenceNumber = observationOption;
1383 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1388 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1391 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1393 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1394 OCPayloadDestroy(response.payload);
1398 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1400 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1401 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1405 if (cbNode->method == OC_REST_OBSERVE &&
1406 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1407 response.sequenceNumber <= cbNode->sequenceNumber)
1409 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1410 response.sequenceNumber);
1414 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1417 cbNode->sequenceNumber = response.sequenceNumber;
1419 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1421 FindAndDeleteClientCB(cbNode);
1425 // To keep discovery callbacks active.
1426 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1427 MILLISECONDS_PER_SECOND);
1431 //Need to send ACK when the response is CON
1432 if(responseInfo->info.type == CA_MSG_CONFIRM)
1434 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1435 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1438 OCPayloadDestroy(response.payload);
1445 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1446 if(responseInfo->result == CA_EMPTY)
1448 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1449 if(responseInfo->info.type == CA_MSG_RESET)
1451 OIC_LOG(INFO, TAG, "This is a RESET");
1452 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1453 OC_OBSERVER_NOT_INTERESTED);
1455 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1457 OIC_LOG(INFO, TAG, "This is a pure ACK");
1458 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1459 OC_OBSERVER_STILL_INTERESTED);
1462 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1464 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1465 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1466 OC_OBSERVER_FAILED_COMM);
1471 if(!cbNode && !observer)
1473 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1474 || myStackMode == OC_GATEWAY)
1476 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1477 if(responseInfo->result == CA_EMPTY)
1479 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1483 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1484 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1485 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1489 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1490 || myStackMode == OC_GATEWAY)
1492 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1493 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1495 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1496 responseInfo->info.messageId);
1498 if (responseInfo->info.type == CA_MSG_RESET)
1500 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1501 responseInfo->info.messageId);
1508 OIC_LOG(INFO, TAG, "Exit OCHandleResponse");
1511 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1513 VERIFY_NON_NULL_NR(endPoint, FATAL);
1514 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1516 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1518 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1519 #ifdef ROUTING_GATEWAY
1520 bool needRIHandling = false;
1522 * Routing manager is going to update either of endpoint or response or both.
1523 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1524 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1527 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1529 if(ret != OC_STACK_OK || !needRIHandling)
1531 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1537 * Put source in sender endpoint so that the next packet from application can be routed to
1538 * proper destination and remove "RM" coap header option before passing request / response to
1539 * RI as this option will make no sense to either RI or application.
1541 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1542 (uint8_t *) &(responseInfo->info.numOptions),
1543 (CAEndpoint_t *) endPoint);
1546 OCHandleResponse(endPoint, responseInfo);
1548 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1552 * This function handles error response from CA
1553 * code shall be added to handle the errors
1555 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1557 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1559 if (NULL == endPoint)
1561 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1565 if (NULL == errorInfo)
1567 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1571 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1572 errorInfo->info.tokenLength, NULL, NULL);
1575 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1576 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1577 FixUpClientResponse(&response);
1578 response.resourceUri = errorInfo->info.resourceUri;
1579 memcpy(response.identity.id, errorInfo->info.identity.id,
1580 sizeof (response.identity.id));
1581 response.identity.id_length = errorInfo->info.identity.id_length;
1582 response.result = CAResultToOCStackResult(errorInfo->result);
1584 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1585 FindAndDeleteClientCB(cbNode);
1588 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1592 * This function sends out Direct Stack Responses. These are responses that are not coming
1593 * from the application entity handler. These responses have no payload and are usually ACKs,
1594 * RESETs or some error conditions that were caught by the stack.
1596 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1597 const CAResponseResult_t responseResult, const CAMessageType_t type,
1598 const uint8_t numOptions, const CAHeaderOption_t *options,
1599 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1601 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1602 CAResponseInfo_t respInfo = {
1603 .result = responseResult
1605 respInfo.info.messageId = coapID;
1606 respInfo.info.numOptions = numOptions;
1608 if (respInfo.info.numOptions)
1610 respInfo.info.options =
1611 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1612 memcpy (respInfo.info.options, options,
1613 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1617 respInfo.info.payload = NULL;
1618 respInfo.info.token = token;
1619 respInfo.info.tokenLength = tokenLength;
1620 respInfo.info.type = type;
1621 respInfo.info.resourceUri = OICStrdup (resourceUri);
1622 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1624 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1625 // Add the destination to route option from the endpoint->routeData.
1626 bool doPost = false;
1627 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1628 if(OC_STACK_OK != result)
1630 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1635 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1636 CARequestInfo_t reqInfo = {.method = CA_POST };
1637 /* The following initialization is not done in a single initializer block as in
1638 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1639 * does not have designated initalizers. This is a work-around for now.
1641 reqInfo.info.type = CA_MSG_NONCONFIRM;
1642 reqInfo.info.messageId = coapID;
1643 reqInfo.info.tokenLength = tokenLength;
1644 reqInfo.info.token = token;
1645 reqInfo.info.numOptions = respInfo.info.numOptions;
1646 reqInfo.info.payload = NULL;
1647 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1648 if (reqInfo.info.numOptions)
1650 reqInfo.info.options =
1651 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1652 if (NULL == reqInfo.info.options)
1654 OIC_LOG(ERROR, TAG, "Calloc failed");
1655 return OC_STACK_NO_MEMORY;
1657 memcpy (reqInfo.info.options, respInfo.info.options,
1658 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1661 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1662 OICFree (reqInfo.info.resourceUri);
1663 OICFree (reqInfo.info.options);
1664 OICFree (respInfo.info.resourceUri);
1665 OICFree (respInfo.info.options);
1666 if (CA_STATUS_OK != caResult)
1668 OIC_LOG(ERROR, TAG, "CASendRequest error");
1669 return CAResultToOCResult(caResult);
1675 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1677 // resourceUri in the info field is cloned in the CA layer and
1678 // thus ownership is still here.
1679 OICFree (respInfo.info.resourceUri);
1680 OICFree (respInfo.info.options);
1681 if(CA_STATUS_OK != caResult)
1683 OIC_LOG(ERROR, TAG, "CASendResponse error");
1684 return CAResultToOCResult(caResult);
1687 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1691 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1693 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1694 OCStackResult result = OC_STACK_ERROR;
1695 if(!protocolRequest)
1697 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1698 return OC_STACK_INVALID_PARAM;
1701 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1702 protocolRequest->tokenLength);
1705 OIC_LOG(INFO, TAG, "This is a new Server Request");
1706 result = AddServerRequest(&request, protocolRequest->coapID,
1707 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1708 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1709 protocolRequest->observationOption, protocolRequest->qos,
1710 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1711 protocolRequest->payload, protocolRequest->requestToken,
1712 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1713 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1714 &protocolRequest->devAddr);
1715 if (OC_STACK_OK != result)
1717 OIC_LOG(ERROR, TAG, "Error adding server request");
1723 OIC_LOG(ERROR, TAG, "Out of Memory");
1724 return OC_STACK_NO_MEMORY;
1727 if(!protocolRequest->reqMorePacket)
1729 request->requestComplete = 1;
1734 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1737 if(request->requestComplete)
1739 OIC_LOG(INFO, TAG, "This Server Request is complete");
1740 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1741 OCResource *resource = NULL;
1742 result = DetermineResourceHandling (request, &resHandling, &resource);
1743 if (result == OC_STACK_OK)
1745 result = ProcessRequest(resHandling, resource, request);
1750 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1751 result = OC_STACK_CONTINUE;
1756 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1758 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1761 if (requestInfo->info.resourceUri &&
1762 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1764 HandleKeepAliveRequest(endPoint, requestInfo);
1769 OCStackResult requestResult = OC_STACK_ERROR;
1771 if(myStackMode == OC_CLIENT)
1773 //TODO: should the client be responding to requests?
1777 OCServerProtocolRequest serverRequest = {0};
1779 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1781 char * uriWithoutQuery = NULL;
1782 char * query = NULL;
1784 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1786 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1788 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1791 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1792 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1794 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1796 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1797 OICFree(uriWithoutQuery);
1801 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1802 OICFree(uriWithoutQuery);
1809 if(strlen(query) < MAX_QUERY_LENGTH)
1811 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1816 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1822 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1824 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1825 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1826 if (!serverRequest.payload)
1828 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1831 memcpy (serverRequest.payload, requestInfo->info.payload,
1832 requestInfo->info.payloadSize);
1836 serverRequest.reqTotalSize = 0;
1839 switch (requestInfo->method)
1842 serverRequest.method = OC_REST_GET;
1845 serverRequest.method = OC_REST_PUT;
1848 serverRequest.method = OC_REST_POST;
1851 serverRequest.method = OC_REST_DELETE;
1854 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1855 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1856 requestInfo->info.type, requestInfo->info.numOptions,
1857 requestInfo->info.options, requestInfo->info.token,
1858 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1859 OICFree(serverRequest.payload);
1863 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1864 requestInfo->info.tokenLength);
1866 serverRequest.tokenLength = requestInfo->info.tokenLength;
1867 if (serverRequest.tokenLength) {
1869 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1871 if (!serverRequest.requestToken)
1873 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1874 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1875 requestInfo->info.type, requestInfo->info.numOptions,
1876 requestInfo->info.options, requestInfo->info.token,
1877 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1878 OICFree(serverRequest.payload);
1881 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1884 switch (requestInfo->info.acceptFormat)
1886 case CA_FORMAT_APPLICATION_CBOR:
1887 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1889 case CA_FORMAT_UNDEFINED:
1890 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1893 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1896 if (requestInfo->info.type == CA_MSG_CONFIRM)
1898 serverRequest.qos = OC_HIGH_QOS;
1902 serverRequest.qos = OC_LOW_QOS;
1904 // CA does not need the following field
1905 // Are we sure CA does not need them? how is it responding to multicast
1906 serverRequest.delayedResNeeded = 0;
1908 serverRequest.coapID = requestInfo->info.messageId;
1910 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1912 // copy vendor specific header options
1913 uint8_t tempNum = (requestInfo->info.numOptions);
1915 // Assume no observation requested and it is a pure GET.
1916 // If obs registration/de-registration requested it'll be fetched from the
1917 // options in GetObserveHeaderOption()
1918 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1920 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1921 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1924 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1925 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1926 requestInfo->info.type, requestInfo->info.numOptions,
1927 requestInfo->info.options, requestInfo->info.token,
1928 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1929 OICFree(serverRequest.payload);
1930 OICFree(serverRequest.requestToken);
1933 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1934 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1936 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1937 sizeof(CAHeaderOption_t)*tempNum);
1940 requestResult = HandleStackRequests (&serverRequest);
1942 // Send ACK to client as precursor to slow response
1943 if (requestResult == OC_STACK_SLOW_RESOURCE)
1945 if (requestInfo->info.type == CA_MSG_CONFIRM)
1947 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1948 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1951 else if(!OCResultToSuccess(requestResult))
1953 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1955 CAResponseResult_t stackResponse =
1956 OCToCAStackResult(requestResult, serverRequest.method);
1958 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1959 requestInfo->info.type, requestInfo->info.numOptions,
1960 requestInfo->info.options, requestInfo->info.token,
1961 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1963 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1964 // The token is copied in there, and is thus still owned by this function.
1965 OICFree(serverRequest.payload);
1966 OICFree(serverRequest.requestToken);
1967 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1970 //This function will be called back by CA layer when a request is received
1971 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1973 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1976 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1982 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
1986 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1987 #ifdef ROUTING_GATEWAY
1988 bool needRIHandling = false;
1989 bool isEmptyMsg = false;
1991 * Routing manager is going to update either of endpoint or request or both.
1992 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1993 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1994 * destination. It can also remove "RM" coap header option before passing request / response to
1995 * RI as this option will make no sense to either RI or application.
1997 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1998 &needRIHandling, &isEmptyMsg);
1999 if(OC_STACK_OK != ret || !needRIHandling)
2001 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2007 * Put source in sender endpoint so that the next packet from application can be routed to
2008 * proper destination and remove RM header option.
2010 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2011 (uint8_t *) &(requestInfo->info.numOptions),
2012 (CAEndpoint_t *) endPoint);
2014 #ifdef ROUTING_GATEWAY
2018 * In Gateways, the MSGType in route option is used to check if the actual
2019 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2020 * EMPTY response is sent in the form of POST request which need to be changed
2021 * to a EMPTY response by RM. This translation is done in this part of the code.
2023 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2024 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2025 .info.messageId = requestInfo->info.messageId,
2026 .info.type = CA_MSG_ACKNOWLEDGE};
2027 OCHandleResponse(endPoint, &respInfo);
2033 // Normal handling of the packet
2034 OCHandleRequests(endPoint, requestInfo);
2036 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2039 bool validatePlatformInfo(OCPlatformInfo info)
2042 if (!info.platformID)
2044 OIC_LOG(ERROR, TAG, "No platform ID found.");
2048 if (info.manufacturerName)
2050 size_t lenManufacturerName = strlen(info.manufacturerName);
2052 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2054 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2060 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2064 if (info.manufacturerUrl)
2066 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2068 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2075 //-----------------------------------------------------------------------------
2077 //-----------------------------------------------------------------------------
2079 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2082 !raInfo->username ||
2083 !raInfo->hostname ||
2084 !raInfo->xmpp_domain)
2087 return OC_STACK_INVALID_PARAM;
2089 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2090 gRASetInfo = (result == OC_STACK_OK)? true : false;
2096 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2100 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2103 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2105 if(stackState == OC_STACK_INITIALIZED)
2107 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2108 OCStop() between them are ignored.");
2112 #ifndef ROUTING_GATEWAY
2113 if (OC_GATEWAY == mode)
2115 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2116 return OC_STACK_INVALID_PARAM;
2123 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2124 return OC_STACK_ERROR;
2128 OCStackResult result = OC_STACK_ERROR;
2129 OIC_LOG(INFO, TAG, "Entering OCInit");
2132 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2133 || (mode == OC_GATEWAY)))
2135 OIC_LOG(ERROR, TAG, "Invalid mode");
2136 return OC_STACK_ERROR;
2140 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2142 caglobals.client = true;
2144 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2146 caglobals.server = true;
2149 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2150 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2152 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2154 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2155 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2157 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2160 defaultDeviceHandler = NULL;
2161 defaultDeviceHandlerCallbackParameter = NULL;
2163 result = CAResultToOCResult(CAInitialize());
2164 VERIFY_SUCCESS(result, OC_STACK_OK);
2166 result = CAResultToOCResult(OCSelectNetwork());
2167 VERIFY_SUCCESS(result, OC_STACK_OK);
2169 switch (myStackMode)
2172 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2173 result = CAResultToOCResult(CAStartDiscoveryServer());
2174 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2177 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2178 result = CAResultToOCResult(CAStartListeningServer());
2179 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2181 case OC_CLIENT_SERVER:
2183 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2184 result = CAResultToOCResult(CAStartListeningServer());
2185 if(result == OC_STACK_OK)
2187 result = CAResultToOCResult(CAStartDiscoveryServer());
2191 VERIFY_SUCCESS(result, OC_STACK_OK);
2194 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2197 #ifdef WITH_PRESENCE
2198 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2199 #endif // WITH_PRESENCE
2201 //Update Stack state to initialized
2202 stackState = OC_STACK_INITIALIZED;
2204 // Initialize resource
2205 if(myStackMode != OC_CLIENT)
2207 result = initResources();
2210 // Initialize the SRM Policy Engine
2211 if(result == OC_STACK_OK)
2213 result = SRMInitPolicyEngine();
2214 // TODO after BeachHead delivery: consolidate into single SRMInit()
2216 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2217 RMSetStackMode(mode);
2218 #ifdef ROUTING_GATEWAY
2219 if (OC_GATEWAY == myStackMode)
2221 result = RMInitialize();
2227 if (result == OC_STACK_OK)
2229 result = InitializeKeepAlive(myStackMode);
2234 if(result != OC_STACK_OK)
2236 OIC_LOG(ERROR, TAG, "Stack initialization error");
2237 deleteAllResources();
2239 stackState = OC_STACK_UNINITIALIZED;
2244 OCStackResult OCStop()
2246 OIC_LOG(INFO, TAG, "Entering OCStop");
2248 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2250 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2253 else if (stackState != OC_STACK_INITIALIZED)
2255 OIC_LOG(ERROR, TAG, "Stack not initialized");
2256 return OC_STACK_ERROR;
2259 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2261 #ifdef WITH_PRESENCE
2262 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2263 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2264 presenceResource.presenceTTL = 0;
2265 #endif // WITH_PRESENCE
2267 #ifdef ROUTING_GATEWAY
2268 if (OC_GATEWAY == myStackMode)
2275 TerminateKeepAlive(myStackMode);
2278 // Free memory dynamically allocated for resources
2279 deleteAllResources();
2281 DeletePlatformInfo();
2283 // Remove all observers
2284 DeleteObserverList();
2285 // Remove all the client callbacks
2286 DeleteClientCBList();
2288 // De-init the SRM Policy Engine
2289 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2290 SRMDeInitPolicyEngine();
2293 stackState = OC_STACK_UNINITIALIZED;
2297 OCStackResult OCStartMulticastServer()
2299 if(stackState != OC_STACK_INITIALIZED)
2301 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2302 return OC_STACK_ERROR;
2304 CAResult_t ret = CAStartListeningServer();
2305 if (CA_STATUS_OK != ret)
2307 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2308 return OC_STACK_ERROR;
2313 OCStackResult OCStopMulticastServer()
2315 CAResult_t ret = CAStopListeningServer();
2316 if (CA_STATUS_OK != ret)
2318 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2319 return OC_STACK_ERROR;
2324 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2329 return CA_MSG_CONFIRM;
2334 return CA_MSG_NONCONFIRM;
2339 * A request uri consists of the following components in order:
2342 * CoAP over UDP prefix "coap://"
2343 * CoAP over TCP prefix "coap+tcp://"
2345 * IPv6 address "[1234::5678]"
2346 * IPv4 address "192.168.1.1"
2347 * optional port ":5683"
2348 * resource uri "/oc/core..."
2350 * for PRESENCE requests, extract resource type.
2352 static OCStackResult ParseRequestUri(const char *fullUri,
2353 OCTransportAdapter adapter,
2354 OCTransportFlags flags,
2355 OCDevAddr **devAddr,
2357 char **resourceType)
2359 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2361 OCStackResult result = OC_STACK_OK;
2362 OCDevAddr *da = NULL;
2366 // provide defaults for all returned values
2373 *resourceUri = NULL;
2377 *resourceType = NULL;
2380 // delimit url prefix, if any
2381 const char *start = fullUri;
2382 char *slash2 = strstr(start, "//");
2387 char *slash = strchr(start, '/');
2390 return OC_STACK_INVALID_URI;
2393 // process url scheme
2394 size_t prefixLen = slash2 - fullUri;
2398 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2404 // TODO: this logic should come in with unit tests exercising the various strings
2405 // processs url prefix, if any
2406 size_t urlLen = slash - start;
2410 if (urlLen && devAddr)
2411 { // construct OCDevAddr
2412 if (start[0] == '[')
2414 char *close = strchr(++start, ']');
2415 if (!close || close > slash)
2417 return OC_STACK_INVALID_URI;
2420 if (close[1] == ':')
2427 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2431 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2433 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2437 char *dot = strchr(start, '.');
2438 if (dot && dot < slash)
2440 colon = strchr(start, ':');
2441 end = (colon && colon < slash) ? colon : slash;
2446 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2450 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2452 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2460 if (len >= sizeof(da->addr))
2462 return OC_STACK_INVALID_URI;
2464 // collect port, if any
2465 if (colon && colon < slash)
2467 for (colon++; colon < slash; colon++)
2470 if (c < '0' || c > '9')
2472 return OC_STACK_INVALID_URI;
2474 port = 10 * port + c - '0';
2479 if (len >= sizeof(da->addr))
2481 return OC_STACK_INVALID_URI;
2484 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2487 return OC_STACK_NO_MEMORY;
2489 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2491 da->adapter = adapter;
2493 if (!strncmp(fullUri, "coaps:", 6))
2495 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2500 // process resource uri, if any
2502 { // request uri and query
2503 size_t ulen = strlen(slash); // resource uri length
2504 size_t tlen = 0; // resource type length
2507 static const char strPresence[] = "/oic/ad?rt=";
2508 static const size_t lenPresence = sizeof(strPresence) - 1;
2509 if (!strncmp(slash, strPresence, lenPresence))
2511 type = slash + lenPresence;
2512 tlen = ulen - lenPresence;
2517 *resourceUri = (char *)OICMalloc(ulen + 1);
2520 result = OC_STACK_NO_MEMORY;
2523 strcpy(*resourceUri, slash);
2526 if (type && resourceType)
2528 *resourceType = (char *)OICMalloc(tlen + 1);
2531 result = OC_STACK_NO_MEMORY;
2535 OICStrcpy(*resourceType, (tlen+1), type);
2542 // free all returned values
2549 OICFree(*resourceUri);
2553 OICFree(*resourceType);
2558 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2559 char *resourceUri, char **requestUri)
2561 char uri[CA_MAX_URI_LENGTH];
2563 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2565 *requestUri = OICStrdup(uri);
2568 return OC_STACK_NO_MEMORY;
2575 * Discover or Perform requests on a specified resource
2577 OCStackResult OCDoResource(OCDoHandle *handle,
2579 const char *requestUri,
2580 const OCDevAddr *destination,
2582 OCConnectivityType connectivityType,
2583 OCQualityOfService qos,
2584 OCCallbackData *cbData,
2585 OCHeaderOption *options,
2588 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2590 // Validate input parameters
2591 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2592 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2593 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2595 OCStackResult result = OC_STACK_ERROR;
2596 CAResult_t caResult;
2597 CAToken_t token = NULL;
2598 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2599 ClientCB *clientCB = NULL;
2600 OCDoHandle resHandle = NULL;
2601 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2602 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2604 OCTransportAdapter adapter;
2605 OCTransportFlags flags;
2606 // the request contents are put here
2607 CARequestInfo_t requestInfo = {.method = CA_GET};
2608 // requestUri will be parsed into the following three variables
2609 OCDevAddr *devAddr = NULL;
2610 char *resourceUri = NULL;
2611 char *resourceType = NULL;
2614 * Support original behavior with address on resourceUri argument.
2616 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2617 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2619 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2621 if (result != OC_STACK_OK)
2623 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2630 case OC_REST_OBSERVE:
2631 case OC_REST_OBSERVE_ALL:
2632 case OC_REST_CANCEL_OBSERVE:
2633 requestInfo.method = CA_GET;
2636 requestInfo.method = CA_PUT;
2639 requestInfo.method = CA_POST;
2641 case OC_REST_DELETE:
2642 requestInfo.method = CA_DELETE;
2644 case OC_REST_DISCOVER:
2646 if (destination || devAddr)
2648 requestInfo.isMulticast = false;
2652 tmpDevAddr.adapter = adapter;
2653 tmpDevAddr.flags = flags;
2654 destination = &tmpDevAddr;
2655 requestInfo.isMulticast = true;
2657 // CA_DISCOVER will become GET and isMulticast
2658 requestInfo.method = CA_GET;
2660 #ifdef WITH_PRESENCE
2661 case OC_REST_PRESENCE:
2662 // Replacing method type with GET because "presence"
2663 // is a stack layer only implementation.
2664 requestInfo.method = CA_GET;
2668 result = OC_STACK_INVALID_METHOD;
2672 if (!devAddr && !destination)
2674 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2675 result = OC_STACK_INVALID_PARAM;
2679 /* If not original behavior, use destination argument */
2680 if (destination && !devAddr)
2682 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2685 result = OC_STACK_NO_MEMORY;
2688 *devAddr = *destination;
2691 resHandle = GenerateInvocationHandle();
2694 result = OC_STACK_NO_MEMORY;
2698 caResult = CAGenerateToken(&token, tokenLength);
2699 if (caResult != CA_STATUS_OK)
2701 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2702 result= OC_STACK_ERROR;
2706 // fill in request data
2707 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2708 requestInfo.info.token = token;
2709 requestInfo.info.tokenLength = tokenLength;
2710 requestInfo.info.resourceUri = resourceUri;
2712 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2714 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2715 options, numOptions, OC_OBSERVE_REGISTER);
2716 if (result != OC_STACK_OK)
2720 requestInfo.info.numOptions = numOptions + 1;
2724 requestInfo.info.numOptions = numOptions;
2725 requestInfo.info.options =
2726 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2727 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2728 numOptions * sizeof(CAHeaderOption_t));
2731 CopyDevAddrToEndpoint(devAddr, &endpoint);
2736 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2739 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2742 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2746 requestInfo.info.payload = NULL;
2747 requestInfo.info.payloadSize = 0;
2748 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2751 // prepare for response
2752 #ifdef WITH_PRESENCE
2753 if (method == OC_REST_PRESENCE)
2755 char *presenceUri = NULL;
2756 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2757 if (OC_STACK_OK != result)
2762 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2763 // Presence notification will form a canonical uri to
2764 // look for callbacks into the application.
2765 resourceUri = presenceUri;
2769 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2770 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2771 method, devAddr, resourceUri, resourceType, ttl);
2772 if (OC_STACK_OK != result)
2777 devAddr = NULL; // Client CB list entry now owns it
2778 resourceUri = NULL; // Client CB list entry now owns it
2779 resourceType = NULL; // Client CB list entry now owns it
2782 result = OCSendRequest(&endpoint, &requestInfo);
2783 if (OC_STACK_OK != result)
2790 *handle = resHandle;
2794 if (result != OC_STACK_OK)
2796 OIC_LOG(ERROR, TAG, "OCDoResource error");
2797 FindAndDeleteClientCB(clientCB);
2798 CADestroyToken(token);
2806 // This is the owner of the payload object, so we free it
2807 OCPayloadDestroy(payload);
2808 OICFree(requestInfo.info.payload);
2810 OICFree(resourceUri);
2811 OICFree(resourceType);
2812 OICFree(requestInfo.info.options);
2816 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2820 * This ftn is implemented one of two ways in the case of observation:
2822 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2823 * Remove the callback associated on client side.
2824 * When the next notification comes in from server,
2825 * reply with RESET message to server.
2826 * Keep in mind that the server will react to RESET only
2827 * if the last notification was sent as CON
2829 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2830 * and it is associated with an observe request
2831 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2832 * Send CON Observe request to server with
2833 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2834 * Remove the callback associated on client side.
2836 OCStackResult ret = OC_STACK_OK;
2837 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2838 CARequestInfo_t requestInfo = {.method = CA_GET};
2842 return OC_STACK_INVALID_PARAM;
2845 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2848 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2849 return OC_STACK_ERROR;
2852 switch (clientCB->method)
2854 case OC_REST_OBSERVE:
2855 case OC_REST_OBSERVE_ALL:
2857 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2859 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2861 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2863 FindAndDeleteClientCB(clientCB);
2867 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2869 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2870 requestInfo.info.token = clientCB->token;
2871 requestInfo.info.tokenLength = clientCB->tokenLength;
2873 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2874 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2876 return OC_STACK_ERROR;
2878 requestInfo.info.numOptions = numOptions + 1;
2879 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2882 ret = OCSendRequest(&endpoint, &requestInfo);
2884 if (requestInfo.info.options)
2886 OICFree (requestInfo.info.options);
2888 if (requestInfo.info.resourceUri)
2890 OICFree (requestInfo.info.resourceUri);
2895 case OC_REST_DISCOVER:
2896 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2897 clientCB->requestUri);
2898 FindAndDeleteClientCB(clientCB);
2901 #ifdef WITH_PRESENCE
2902 case OC_REST_PRESENCE:
2903 FindAndDeleteClientCB(clientCB);
2908 ret = OC_STACK_INVALID_METHOD;
2916 * @brief Register Persistent storage callback.
2917 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2919 * OC_STACK_OK - No errors; Success
2920 * OC_STACK_INVALID_PARAM - Invalid parameter
2922 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2924 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2925 if(!persistentStorageHandler)
2927 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2928 return OC_STACK_INVALID_PARAM;
2932 if( !persistentStorageHandler->open ||
2933 !persistentStorageHandler->close ||
2934 !persistentStorageHandler->read ||
2935 !persistentStorageHandler->unlink ||
2936 !persistentStorageHandler->write)
2938 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2939 return OC_STACK_INVALID_PARAM;
2942 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2945 #ifdef WITH_PRESENCE
2947 OCStackResult OCProcessPresence()
2949 OCStackResult result = OC_STACK_OK;
2951 // the following line floods the log with messages that are irrelevant
2952 // to most purposes. Uncomment as needed.
2953 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2954 ClientCB* cbNode = NULL;
2955 OCClientResponse clientResponse;
2956 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2958 LL_FOREACH(cbList, cbNode)
2960 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2965 uint32_t now = GetTicks(0);
2966 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2967 cbNode->presence->TTLlevel);
2968 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2970 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2975 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2977 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2978 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2980 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2982 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2984 clientResponse.sequenceNumber = 0;
2985 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2986 clientResponse.devAddr = *cbNode->devAddr;
2987 FixUpClientResponse(&clientResponse);
2988 clientResponse.payload = NULL;
2990 // Increment the TTLLevel (going to a next state), so we don't keep
2991 // sending presence notification to client.
2992 cbNode->presence->TTLlevel++;
2993 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2994 cbNode->presence->TTLlevel);
2996 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2997 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2999 FindAndDeleteClientCB(cbNode);
3003 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3008 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3009 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3010 CARequestInfo_t requestInfo = {.method = CA_GET};
3012 OIC_LOG(DEBUG, TAG, "time to test server presence");
3014 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3016 requestData.type = CA_MSG_NONCONFIRM;
3017 requestData.token = cbNode->token;
3018 requestData.tokenLength = cbNode->tokenLength;
3019 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3020 requestInfo.method = CA_GET;
3021 requestInfo.info = requestData;
3023 result = OCSendRequest(&endpoint, &requestInfo);
3024 if (OC_STACK_OK != result)
3029 cbNode->presence->TTLlevel++;
3030 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3033 if (result != OC_STACK_OK)
3035 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3040 #endif // WITH_PRESENCE
3042 OCStackResult OCProcess()
3044 #ifdef WITH_PRESENCE
3045 OCProcessPresence();
3047 CAHandleRequestResponse();
3049 #ifdef ROUTING_GATEWAY
3059 #ifdef WITH_PRESENCE
3060 OCStackResult OCStartPresence(const uint32_t ttl)
3062 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3063 OCChangeResourceProperty(
3064 &(((OCResource *)presenceResource.handle)->resourceProperties),
3067 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3069 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3070 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3074 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3075 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3079 presenceResource.presenceTTL = ttl;
3081 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3083 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3085 presenceState = OC_PRESENCE_INITIALIZED;
3087 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3089 CAToken_t caToken = NULL;
3090 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3091 if (caResult != CA_STATUS_OK)
3093 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3094 CADestroyToken(caToken);
3095 return OC_STACK_ERROR;
3098 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3099 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3100 CADestroyToken(caToken);
3103 // Each time OCStartPresence is called
3104 // a different random 32-bit integer number is used
3105 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3107 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3108 OC_PRESENCE_TRIGGER_CREATE);
3111 OCStackResult OCStopPresence()
3113 OCStackResult result = OC_STACK_ERROR;
3115 if(presenceResource.handle)
3117 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3119 // make resource inactive
3120 result = OCChangeResourceProperty(
3121 &(((OCResource *) presenceResource.handle)->resourceProperties),
3125 if(result != OC_STACK_OK)
3128 "Changing the presence resource properties to ACTIVE not successful");
3132 return SendStopNotification();
3136 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3137 void* callbackParameter)
3139 defaultDeviceHandler = entityHandler;
3140 defaultDeviceHandlerCallbackParameter = callbackParameter;
3145 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3147 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3149 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3151 if (validatePlatformInfo(platformInfo))
3153 return SavePlatformInfo(platformInfo);
3157 return OC_STACK_INVALID_PARAM;
3162 return OC_STACK_ERROR;
3166 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3168 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3170 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3172 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3173 return OC_STACK_INVALID_PARAM;
3176 if (deviceInfo.types)
3178 OCStringLL *type = deviceInfo.types;
3179 OCResource *resource = findResource((OCResource *) deviceResource);
3182 return OC_STACK_INVALID_PARAM;
3187 OCBindResourceTypeToResource(deviceResource, type->value);
3191 return SaveDeviceInfo(deviceInfo);
3194 OCStackResult OCCreateResource(OCResourceHandle *handle,
3195 const char *resourceTypeName,
3196 const char *resourceInterfaceName,
3197 const char *uri, OCEntityHandler entityHandler,
3198 void* callbackParam,
3199 uint8_t resourceProperties)
3202 OCResource *pointer = NULL;
3203 OCStackResult result = OC_STACK_ERROR;
3205 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3207 if(myStackMode == OC_CLIENT)
3209 return OC_STACK_INVALID_PARAM;
3211 // Validate parameters
3212 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3214 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3215 return OC_STACK_INVALID_URI;
3217 // Is it presented during resource discovery?
3218 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3220 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3221 return OC_STACK_INVALID_PARAM;
3224 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3226 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3229 // Make sure resourceProperties bitmask has allowed properties specified
3230 if (resourceProperties
3231 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3232 OC_EXPLICIT_DISCOVERABLE))
3234 OIC_LOG(ERROR, TAG, "Invalid property");
3235 return OC_STACK_INVALID_PARAM;
3238 // If the headResource is NULL, then no resources have been created...
3239 pointer = headResource;
3242 // At least one resources is in the resource list, so we need to search for
3243 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3246 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3248 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3249 return OC_STACK_INVALID_PARAM;
3251 pointer = pointer->next;
3254 // Create the pointer and insert it into the resource list
3255 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3258 result = OC_STACK_NO_MEMORY;
3261 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3263 insertResource(pointer);
3266 pointer->uri = OICStrdup(uri);
3269 result = OC_STACK_NO_MEMORY;
3273 // Set properties. Set OC_ACTIVE
3274 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3277 // Add the resourcetype to the resource
3278 result = BindResourceTypeToResource(pointer, resourceTypeName);
3279 if (result != OC_STACK_OK)
3281 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3285 // Add the resourceinterface to the resource
3286 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3287 if (result != OC_STACK_OK)
3289 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3293 // If an entity handler has been passed, attach it to the newly created
3294 // resource. Otherwise, set the default entity handler.
3297 pointer->entityHandler = entityHandler;
3298 pointer->entityHandlerCallbackParam = callbackParam;
3302 pointer->entityHandler = defaultResourceEHandler;
3303 pointer->entityHandlerCallbackParam = NULL;
3306 // Initialize a pointer indicating child resources in case of collection
3307 pointer->rsrcChildResourcesHead = NULL;
3310 result = OC_STACK_OK;
3312 #ifdef WITH_PRESENCE
3313 if (presenceResource.handle)
3315 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3316 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3320 if (result != OC_STACK_OK)
3322 // Deep delete of resource and other dynamic elements that it contains
3323 deleteResource(pointer);
3328 OCStackResult OCBindResource(
3329 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3331 OCResource *resource = NULL;
3332 OCChildResource *tempChildResource = NULL;
3333 OCChildResource *newChildResource = NULL;
3335 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3337 // Validate parameters
3338 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3339 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3340 // Container cannot contain itself
3341 if (collectionHandle == resourceHandle)
3343 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3344 return OC_STACK_INVALID_PARAM;
3347 // Use the handle to find the resource in the resource linked list
3348 resource = findResource((OCResource *) collectionHandle);
3351 OIC_LOG(ERROR, TAG, "Collection handle not found");
3352 return OC_STACK_INVALID_PARAM;
3355 // Look for an open slot to add add the child resource.
3356 // If found, add it and return success
3358 tempChildResource = resource->rsrcChildResourcesHead;
3360 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3362 // TODO: what if one of child resource was deregistered without unbinding?
3363 tempChildResource = tempChildResource->next;
3366 // Do memory allocation for child resource
3367 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3368 if(!newChildResource)
3370 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3371 return OC_STACK_ERROR;
3374 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3375 newChildResource->next = NULL;
3377 if(!resource->rsrcChildResourcesHead)
3379 resource->rsrcChildResourcesHead = newChildResource;
3382 tempChildResource->next = newChildResource;
3385 OIC_LOG(INFO, TAG, "resource bound");
3387 #ifdef WITH_PRESENCE
3388 if (presenceResource.handle)
3390 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3391 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3392 OC_PRESENCE_TRIGGER_CHANGE);
3399 OCStackResult OCUnBindResource(
3400 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3402 OCResource *resource = NULL;
3403 OCChildResource *tempChildResource = NULL;
3404 OCChildResource *tempLastChildResource = NULL;
3406 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3408 // Validate parameters
3409 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3410 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3411 // Container cannot contain itself
3412 if (collectionHandle == resourceHandle)
3414 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3415 return OC_STACK_INVALID_PARAM;
3418 // Use the handle to find the resource in the resource linked list
3419 resource = findResource((OCResource *) collectionHandle);
3422 OIC_LOG(ERROR, TAG, "Collection handle not found");
3423 return OC_STACK_INVALID_PARAM;
3426 // Look for an open slot to add add the child resource.
3427 // If found, add it and return success
3428 if(!resource->rsrcChildResourcesHead)
3430 OIC_LOG(INFO, TAG, "resource not found in collection");
3432 // Unable to add resourceHandle, so return error
3433 return OC_STACK_ERROR;
3437 tempChildResource = resource->rsrcChildResourcesHead;
3439 while (tempChildResource)
3441 if(tempChildResource->rsrcResource == resourceHandle)
3443 // if resource going to be unbinded is the head one.
3444 if( tempChildResource == resource->rsrcChildResourcesHead )
3446 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3447 OICFree(resource->rsrcChildResourcesHead);
3448 resource->rsrcChildResourcesHead = temp;
3453 OCChildResource *temp = tempChildResource->next;
3454 OICFree(tempChildResource);
3455 tempLastChildResource->next = temp;
3459 OIC_LOG(INFO, TAG, "resource unbound");
3461 // Send notification when resource is unbounded successfully.
3462 #ifdef WITH_PRESENCE
3463 if (presenceResource.handle)
3465 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3466 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3467 OC_PRESENCE_TRIGGER_CHANGE);
3470 tempChildResource = NULL;
3471 tempLastChildResource = NULL;
3477 tempLastChildResource = tempChildResource;
3478 tempChildResource = tempChildResource->next;
3481 OIC_LOG(INFO, TAG, "resource not found in collection");
3483 tempChildResource = NULL;
3484 tempLastChildResource = NULL;
3486 // Unable to add resourceHandle, so return error
3487 return OC_STACK_ERROR;
3490 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3492 if (!resourceItemName)
3496 // Per RFC 6690 only registered values must follow the first rule below.
3497 // At this point in time the only values registered begin with "core", and
3498 // all other values are specified as opaque strings where multiple values
3499 // are separated by a space.
3500 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3502 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3504 if (resourceItemName[index] != '.'
3505 && resourceItemName[index] != '-'
3506 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3507 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3515 for (size_t index = 0; resourceItemName[index]; ++index)
3517 if (resourceItemName[index] == ' '
3518 || resourceItemName[index] == '\t'
3519 || resourceItemName[index] == '\r'
3520 || resourceItemName[index] == '\n')
3530 OCStackResult BindResourceTypeToResource(OCResource* resource,
3531 const char *resourceTypeName)
3533 OCResourceType *pointer = NULL;
3535 OCStackResult result = OC_STACK_ERROR;
3537 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3539 if (!ValidateResourceTypeInterface(resourceTypeName))
3541 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3542 return OC_STACK_INVALID_PARAM;
3545 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3548 result = OC_STACK_NO_MEMORY;
3552 str = OICStrdup(resourceTypeName);
3555 result = OC_STACK_NO_MEMORY;
3558 pointer->resourcetypename = str;
3559 pointer->next = NULL;
3561 insertResourceType(resource, pointer);
3562 result = OC_STACK_OK;
3565 if (result != OC_STACK_OK)
3574 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3575 const char *resourceInterfaceName)
3577 OCResourceInterface *pointer = NULL;
3579 OCStackResult result = OC_STACK_ERROR;
3581 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3583 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3585 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3586 return OC_STACK_INVALID_PARAM;
3589 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3591 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3594 result = OC_STACK_NO_MEMORY;
3598 str = OICStrdup(resourceInterfaceName);
3601 result = OC_STACK_NO_MEMORY;
3604 pointer->name = str;
3606 // Bind the resourceinterface to the resource
3607 insertResourceInterface(resource, pointer);
3609 result = OC_STACK_OK;
3612 if (result != OC_STACK_OK)
3621 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3622 const char *resourceTypeName)
3625 OCStackResult result = OC_STACK_ERROR;
3626 OCResource *resource = NULL;
3628 resource = findResource((OCResource *) handle);
3631 OIC_LOG(ERROR, TAG, "Resource not found");
3632 return OC_STACK_ERROR;
3635 result = BindResourceTypeToResource(resource, resourceTypeName);
3637 #ifdef WITH_PRESENCE
3638 if(presenceResource.handle)
3640 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3641 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3648 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3649 const char *resourceInterfaceName)
3652 OCStackResult result = OC_STACK_ERROR;
3653 OCResource *resource = NULL;
3655 resource = findResource((OCResource *) handle);
3658 OIC_LOG(ERROR, TAG, "Resource not found");
3659 return OC_STACK_ERROR;
3662 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3664 #ifdef WITH_PRESENCE
3665 if (presenceResource.handle)
3667 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3668 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3675 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3677 OCResource *pointer = headResource;
3679 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3683 *numResources = *numResources + 1;
3684 pointer = pointer->next;
3689 OCResourceHandle OCGetResourceHandle(uint8_t index)
3691 OCResource *pointer = headResource;
3693 for( uint8_t i = 0; i < index && pointer; ++i)
3695 pointer = pointer->next;
3697 return (OCResourceHandle) pointer;
3700 OCStackResult OCDeleteResource(OCResourceHandle handle)
3704 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3705 return OC_STACK_INVALID_PARAM;
3708 OCResource *resource = findResource((OCResource *) handle);
3709 if (resource == NULL)
3711 OIC_LOG(ERROR, TAG, "Resource not found");
3712 return OC_STACK_NO_RESOURCE;
3715 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3717 OIC_LOG(ERROR, TAG, "Error deleting resource");
3718 return OC_STACK_ERROR;
3724 const char *OCGetResourceUri(OCResourceHandle handle)
3726 OCResource *resource = NULL;
3728 resource = findResource((OCResource *) handle);
3731 return resource->uri;
3733 return (const char *) NULL;
3736 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3738 OCResource *resource = NULL;
3740 resource = findResource((OCResource *) handle);
3743 return resource->resourceProperties;
3745 return (OCResourceProperty)-1;
3748 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3749 uint8_t *numResourceTypes)
3751 OCResource *resource = NULL;
3752 OCResourceType *pointer = NULL;
3754 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3755 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3757 *numResourceTypes = 0;
3759 resource = findResource((OCResource *) handle);
3762 pointer = resource->rsrcType;
3765 *numResourceTypes = *numResourceTypes + 1;
3766 pointer = pointer->next;
3772 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3774 OCResourceType *resourceType = NULL;
3776 resourceType = findResourceTypeAtIndex(handle, index);
3779 return resourceType->resourcetypename;
3781 return (const char *) NULL;
3784 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3785 uint8_t *numResourceInterfaces)
3787 OCResourceInterface *pointer = NULL;
3788 OCResource *resource = NULL;
3790 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3791 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3793 *numResourceInterfaces = 0;
3794 resource = findResource((OCResource *) handle);
3797 pointer = resource->rsrcInterface;
3800 *numResourceInterfaces = *numResourceInterfaces + 1;
3801 pointer = pointer->next;
3807 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3809 OCResourceInterface *resourceInterface = NULL;
3811 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3812 if (resourceInterface)
3814 return resourceInterface->name;
3816 return (const char *) NULL;
3819 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3822 OCResource *resource = NULL;
3823 OCChildResource *tempChildResource = NULL;
3826 resource = findResource((OCResource *) collectionHandle);
3832 tempChildResource = resource->rsrcChildResourcesHead;
3834 while(tempChildResource)
3838 return tempChildResource->rsrcResource;
3841 tempChildResource = tempChildResource->next;
3844 // In this case, the number of resource handles in the collection exceeds the index
3845 tempChildResource = NULL;
3849 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3850 OCEntityHandler entityHandler,
3851 void* callbackParam)
3853 OCResource *resource = NULL;
3855 // Validate parameters
3856 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3858 // Use the handle to find the resource in the resource linked list
3859 resource = findResource((OCResource *)handle);
3862 OIC_LOG(ERROR, TAG, "Resource not found");
3863 return OC_STACK_ERROR;
3867 resource->entityHandler = entityHandler;
3868 resource->entityHandlerCallbackParam = callbackParam;
3870 #ifdef WITH_PRESENCE
3871 if (presenceResource.handle)
3873 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3874 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3881 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3883 OCResource *resource = NULL;
3885 resource = findResource((OCResource *)handle);
3888 OIC_LOG(ERROR, TAG, "Resource not found");
3893 return resource->entityHandler;
3896 void incrementSequenceNumber(OCResource * resPtr)
3898 // Increment the sequence number
3899 resPtr->sequenceNum += 1;
3900 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3902 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3907 #ifdef WITH_PRESENCE
3908 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3909 OCPresenceTrigger trigger)
3911 OCResource *resPtr = NULL;
3912 OCStackResult result = OC_STACK_ERROR;
3913 OCMethod method = OC_REST_PRESENCE;
3914 uint32_t maxAge = 0;
3915 resPtr = findResource((OCResource *) presenceResource.handle);
3918 return OC_STACK_NO_RESOURCE;
3921 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3923 maxAge = presenceResource.presenceTTL;
3925 result = SendAllObserverNotification(method, resPtr, maxAge,
3926 trigger, resourceType, OC_LOW_QOS);
3932 OCStackResult SendStopNotification()
3934 OCResource *resPtr = NULL;
3935 OCStackResult result = OC_STACK_ERROR;
3936 OCMethod method = OC_REST_PRESENCE;
3937 resPtr = findResource((OCResource *) presenceResource.handle);
3940 return OC_STACK_NO_RESOURCE;
3943 // maxAge is 0. ResourceType is NULL.
3944 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3950 #endif // WITH_PRESENCE
3951 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3953 OCResource *resPtr = NULL;
3954 OCStackResult result = OC_STACK_ERROR;
3955 OCMethod method = OC_REST_NOMETHOD;
3956 uint32_t maxAge = 0;
3958 OIC_LOG(INFO, TAG, "Notifying all observers");
3959 #ifdef WITH_PRESENCE
3960 if(handle == presenceResource.handle)
3964 #endif // WITH_PRESENCE
3965 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3967 // Verify that the resource exists
3968 resPtr = findResource ((OCResource *) handle);
3971 return OC_STACK_NO_RESOURCE;
3975 //only increment in the case of regular observing (not presence)
3976 incrementSequenceNumber(resPtr);
3977 method = OC_REST_OBSERVE;
3978 maxAge = MAX_OBSERVE_AGE;
3979 #ifdef WITH_PRESENCE
3980 result = SendAllObserverNotification (method, resPtr, maxAge,
3981 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3983 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3990 OCNotifyListOfObservers (OCResourceHandle handle,
3991 OCObservationId *obsIdList,
3992 uint8_t numberOfIds,
3993 const OCRepPayload *payload,
3994 OCQualityOfService qos)
3996 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3998 OCResource *resPtr = NULL;
3999 //TODO: we should allow the server to define this
4000 uint32_t maxAge = MAX_OBSERVE_AGE;
4002 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4003 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4004 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4006 resPtr = findResource ((OCResource *) handle);
4007 if (NULL == resPtr || myStackMode == OC_CLIENT)
4009 return OC_STACK_NO_RESOURCE;
4013 incrementSequenceNumber(resPtr);
4015 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4016 payload, maxAge, qos));
4019 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4021 OCStackResult result = OC_STACK_ERROR;
4022 OCServerRequest *serverRequest = NULL;
4024 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4026 // Validate input parameters
4027 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4028 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4031 // Get pointer to request info
4032 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4035 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4036 result = serverRequest->ehResponseHandler(ehResponse);
4042 //#ifdef DIRECT_PAIRING
4043 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4045 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4046 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4048 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4052 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4055 const OCDPDev_t* OCGetDirectPairedDevices()
4057 return (const OCDPDev_t*)DPGetPairedDevices();
4060 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4061 OCDirectPairingCB resultCallback)
4063 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4064 if(NULL == peer || NULL == pinNumber)
4066 OIC_LOG(ERROR, TAG, "Invalid parameters");
4067 return OC_STACK_INVALID_PARAM;
4069 if (NULL == resultCallback)
4071 OIC_LOG(ERROR, TAG, "Invalid callback");
4072 return OC_STACK_INVALID_CALLBACK;
4075 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4076 pinNumber, (OCDirectPairingResultCB)resultCallback);
4078 //#endif // DIRECT_PAIRING
4080 //-----------------------------------------------------------------------------
4081 // Private internal function definitions
4082 //-----------------------------------------------------------------------------
4083 static OCDoHandle GenerateInvocationHandle()
4085 OCDoHandle handle = NULL;
4086 // Generate token here, it will be deleted when the transaction is deleted
4087 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4090 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4096 #ifdef WITH_PRESENCE
4097 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4098 OCResourceProperty resourceProperties, uint8_t enable)
4102 return OC_STACK_INVALID_PARAM;
4104 if (resourceProperties
4105 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4107 OIC_LOG(ERROR, TAG, "Invalid property");
4108 return OC_STACK_INVALID_PARAM;
4112 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4116 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4122 OCStackResult initResources()
4124 OCStackResult result = OC_STACK_OK;
4126 headResource = NULL;
4127 tailResource = NULL;
4128 // Init Virtual Resources
4129 #ifdef WITH_PRESENCE
4130 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4132 result = OCCreateResource(&presenceResource.handle,
4133 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4135 OC_RSRVD_PRESENCE_URI,
4139 //make resource inactive
4140 result = OCChangeResourceProperty(
4141 &(((OCResource *) presenceResource.handle)->resourceProperties),
4144 #ifndef WITH_ARDUINO
4145 if (result == OC_STACK_OK)
4147 result = SRMInitSecureResources();
4151 if(result == OC_STACK_OK)
4153 result = OCCreateResource(&deviceResource,
4154 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4155 OC_RSRVD_INTERFACE_DEFAULT,
4156 OC_RSRVD_DEVICE_URI,
4160 if(result == OC_STACK_OK)
4162 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4163 OC_RSRVD_INTERFACE_READ);
4167 if(result == OC_STACK_OK)
4169 result = OCCreateResource(&platformResource,
4170 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4171 OC_RSRVD_INTERFACE_DEFAULT,
4172 OC_RSRVD_PLATFORM_URI,
4176 if(result == OC_STACK_OK)
4178 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4179 OC_RSRVD_INTERFACE_READ);
4186 void insertResource(OCResource *resource)
4190 headResource = resource;
4191 tailResource = resource;
4195 tailResource->next = resource;
4196 tailResource = resource;
4198 resource->next = NULL;
4201 OCResource *findResource(OCResource *resource)
4203 OCResource *pointer = headResource;
4207 if (pointer == resource)
4211 pointer = pointer->next;
4216 void deleteAllResources()
4218 OCResource *pointer = headResource;
4219 OCResource *temp = NULL;
4223 temp = pointer->next;
4224 #ifdef WITH_PRESENCE
4225 if (pointer != (OCResource *) presenceResource.handle)
4227 #endif // WITH_PRESENCE
4228 deleteResource(pointer);
4229 #ifdef WITH_PRESENCE
4231 #endif // WITH_PRESENCE
4234 memset(&platformResource, 0, sizeof(platformResource));
4235 memset(&deviceResource, 0, sizeof(deviceResource));
4237 SRMDeInitSecureResources();
4239 #ifdef WITH_PRESENCE
4240 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4241 // presence notification attributed to their deletion to be processed.
4242 deleteResource((OCResource *) presenceResource.handle);
4243 memset(&presenceResource, 0, sizeof(presenceResource));
4244 #endif // WITH_PRESENCE
4247 OCStackResult deleteResource(OCResource *resource)
4249 OCResource *prev = NULL;
4250 OCResource *temp = NULL;
4253 OIC_LOG(DEBUG,TAG,"resource is NULL");
4254 return OC_STACK_INVALID_PARAM;
4257 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4259 temp = headResource;
4262 if (temp == resource)
4264 // Invalidate all Resource Properties.
4265 resource->resourceProperties = (OCResourceProperty) 0;
4266 #ifdef WITH_PRESENCE
4267 if(resource != (OCResource *) presenceResource.handle)
4269 #endif // WITH_PRESENCE
4270 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4271 #ifdef WITH_PRESENCE
4274 if(presenceResource.handle)
4276 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4277 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4280 // Only resource in list.
4281 if (temp == headResource && temp == tailResource)
4283 headResource = NULL;
4284 tailResource = NULL;
4287 else if (temp == headResource)
4289 headResource = temp->next;
4292 else if (temp == tailResource)
4294 tailResource = prev;
4295 tailResource->next = NULL;
4299 prev->next = temp->next;
4302 deleteResourceElements(temp);
4313 return OC_STACK_ERROR;
4316 void deleteResourceElements(OCResource *resource)
4323 OICFree(resource->uri);
4324 deleteResourceType(resource->rsrcType);
4325 deleteResourceInterface(resource->rsrcInterface);
4328 void deleteResourceType(OCResourceType *resourceType)
4330 OCResourceType *pointer = resourceType;
4331 OCResourceType *next = NULL;
4335 next = pointer->next;
4336 OICFree(pointer->resourcetypename);
4342 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4344 OCResourceInterface *pointer = resourceInterface;
4345 OCResourceInterface *next = NULL;
4349 next = pointer->next;
4350 OICFree(pointer->name);
4356 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4358 OCResourceType *pointer = NULL;
4359 OCResourceType *previous = NULL;
4360 if (!resource || !resourceType)
4364 // resource type list is empty.
4365 else if (!resource->rsrcType)
4367 resource->rsrcType = resourceType;
4371 pointer = resource->rsrcType;
4375 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4377 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4378 OICFree(resourceType->resourcetypename);
4379 OICFree(resourceType);
4383 pointer = pointer->next;
4388 previous->next = resourceType;
4391 resourceType->next = NULL;
4393 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4396 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4398 OCResource *resource = NULL;
4399 OCResourceType *pointer = NULL;
4401 // Find the specified resource
4402 resource = findResource((OCResource *) handle);
4408 // Make sure a resource has a resourcetype
4409 if (!resource->rsrcType)
4414 // Iterate through the list
4415 pointer = resource->rsrcType;
4416 for(uint8_t i = 0; i< index && pointer; ++i)
4418 pointer = pointer->next;
4423 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4425 if(resourceTypeList && resourceTypeName)
4427 OCResourceType * rtPointer = resourceTypeList;
4428 while(resourceTypeName && rtPointer)
4430 if(rtPointer->resourcetypename &&
4431 strcmp(resourceTypeName, (const char *)
4432 (rtPointer->resourcetypename)) == 0)
4436 rtPointer = rtPointer->next;
4444 * Insert a new interface into interface linked list only if not already present.
4445 * If alredy present, 2nd arg is free'd.
4446 * Default interface will always be first if present.
4448 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4450 OCResourceInterface *pointer = NULL;
4451 OCResourceInterface *previous = NULL;
4453 newInterface->next = NULL;
4455 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4457 if (!*firstInterface)
4459 // If first interface is not oic.if.baseline, by default add it as first interface type.
4460 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4462 *firstInterface = newInterface;
4466 OCStackResult result = BindResourceInterfaceToResource(resource, OC_RSRVD_INTERFACE_DEFAULT);
4467 if (result != OC_STACK_OK)
4469 OICFree(newInterface->name);
4470 OICFree(newInterface);
4473 if (*firstInterface)
4475 (*firstInterface)->next = newInterface;
4479 // If once add oic.if.baseline, later too below code take care of freeing memory.
4480 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4482 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4484 OICFree(newInterface->name);
4485 OICFree(newInterface);
4488 // This code will not hit anymore, keeping
4491 newInterface->next = *firstInterface;
4492 *firstInterface = newInterface;
4497 pointer = *firstInterface;
4500 if (strcmp(newInterface->name, pointer->name) == 0)
4502 OICFree(newInterface->name);
4503 OICFree(newInterface);
4507 pointer = pointer->next;
4512 previous->next = newInterface;
4517 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4520 OCResource *resource = NULL;
4521 OCResourceInterface *pointer = NULL;
4523 // Find the specified resource
4524 resource = findResource((OCResource *) handle);
4530 // Make sure a resource has a resourceinterface
4531 if (!resource->rsrcInterface)
4536 // Iterate through the list
4537 pointer = resource->rsrcInterface;
4539 for (uint8_t i = 0; i < index && pointer; ++i)
4541 pointer = pointer->next;
4547 * This function splits the uri using the '?' delimiter.
4548 * "uriWithoutQuery" is the block of characters between the beginning
4549 * till the delimiter or '\0' which ever comes first.
4550 * "query" is whatever is to the right of the delimiter if present.
4551 * No delimiter sets the query to NULL.
4552 * If either are present, they will be malloc'ed into the params 2, 3.
4553 * The first param, *uri is left untouched.
4555 * NOTE: This function does not account for whitespace at the end of the uri NOR
4556 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4557 * part of the query.
4559 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4563 return OC_STACK_INVALID_URI;
4565 if(!query || !uriWithoutQuery)
4567 return OC_STACK_INVALID_PARAM;
4571 *uriWithoutQuery = NULL;
4573 size_t uriWithoutQueryLen = 0;
4574 size_t queryLen = 0;
4575 size_t uriLen = strlen(uri);
4577 char *pointerToDelimiter = strstr(uri, "?");
4579 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4580 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4582 if (uriWithoutQueryLen)
4584 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4585 if (!*uriWithoutQuery)
4589 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4593 *query = (char *) OICCalloc(queryLen + 1, 1);
4596 OICFree(*uriWithoutQuery);
4597 *uriWithoutQuery = NULL;
4600 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4606 return OC_STACK_NO_MEMORY;
4609 static const OicUuid_t* OCGetServerInstanceID(void)
4611 static bool generated = false;
4612 static OicUuid_t sid;
4618 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4620 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4627 const char* OCGetServerInstanceIDString(void)
4629 static bool generated = false;
4630 static char sidStr[UUID_STRING_SIZE];
4637 const OicUuid_t *sid = OCGetServerInstanceID();
4638 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4640 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4648 CAResult_t OCSelectNetwork()
4650 CAResult_t retResult = CA_STATUS_FAILED;
4651 CAResult_t caResult = CA_STATUS_OK;
4653 CATransportAdapter_t connTypes[] = {
4655 CA_ADAPTER_RFCOMM_BTEDR,
4656 CA_ADAPTER_GATT_BTLE,
4659 ,CA_ADAPTER_REMOTE_ACCESS
4666 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4668 for(int i = 0; i<numConnTypes; i++)
4670 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4671 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4673 caResult = CASelectNetwork(connTypes[i]);
4674 if(caResult == CA_STATUS_OK)
4676 retResult = CA_STATUS_OK;
4681 if(retResult != CA_STATUS_OK)
4683 return caResult; // Returns error of appropriate transport that failed fatally.
4689 OCStackResult CAResultToOCResult(CAResult_t caResult)
4695 case CA_STATUS_INVALID_PARAM:
4696 return OC_STACK_INVALID_PARAM;
4697 case CA_ADAPTER_NOT_ENABLED:
4698 return OC_STACK_ADAPTER_NOT_ENABLED;
4699 case CA_SERVER_STARTED_ALREADY:
4701 case CA_SERVER_NOT_STARTED:
4702 return OC_STACK_ERROR;
4703 case CA_DESTINATION_NOT_REACHABLE:
4704 return OC_STACK_COMM_ERROR;
4705 case CA_SOCKET_OPERATION_FAILED:
4706 return OC_STACK_COMM_ERROR;
4707 case CA_SEND_FAILED:
4708 return OC_STACK_COMM_ERROR;
4709 case CA_RECEIVE_FAILED:
4710 return OC_STACK_COMM_ERROR;
4711 case CA_MEMORY_ALLOC_FAILED:
4712 return OC_STACK_NO_MEMORY;
4713 case CA_REQUEST_TIMEOUT:
4714 return OC_STACK_TIMEOUT;
4715 case CA_DESTINATION_DISCONNECTED:
4716 return OC_STACK_COMM_ERROR;
4717 case CA_STATUS_FAILED:
4718 return OC_STACK_ERROR;
4719 case CA_NOT_SUPPORTED:
4720 return OC_STACK_NOTIMPL;
4722 return OC_STACK_ERROR;
4726 bool OCResultToSuccess(OCStackResult ocResult)
4731 case OC_STACK_RESOURCE_CREATED:
4732 case OC_STACK_RESOURCE_DELETED:
4733 case OC_STACK_CONTINUE:
4734 case OC_STACK_RESOURCE_CHANGED: