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 #define __STDC_FORMAT_MACROS
34 #define __STDC_LIMIT_MACROS
40 #include "ocstackinternal.h"
41 #include "ocresourcehandler.h"
42 #include "occlientcb.h"
43 #include "ocobserve.h"
45 #include "oic_malloc.h"
46 #include "oic_string.h"
48 #include "ocserverrequest.h"
49 #include "secureresourcemanager.h"
50 #include "doxmresource.h"
52 #include "cainterface.h"
53 #include "ocpayload.h"
54 #include "ocpayloadcbor.h"
56 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
57 #include "routingutility.h"
58 #ifdef ROUTING_GATEWAY
59 #include "routingmanager.h"
64 #include "oickeepalive.h"
72 #include "coap_time.h"
77 #include <arpa/inet.h>
81 #define UINT32_MAX (0xFFFFFFFFUL)
84 //-----------------------------------------------------------------------------
86 //-----------------------------------------------------------------------------
89 OC_STACK_UNINITIALIZED = 0,
91 OC_STACK_UNINIT_IN_PROGRESS
97 OC_PRESENCE_UNINITIALIZED = 0,
98 OC_PRESENCE_INITIALIZED
102 //-----------------------------------------------------------------------------
104 //-----------------------------------------------------------------------------
105 static OCStackState stackState = OC_STACK_UNINITIALIZED;
107 OCResource *headResource = NULL;
108 static OCResource *tailResource = NULL;
109 static OCResourceHandle platformResource = {0};
110 static OCResourceHandle deviceResource = {0};
112 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
113 static PresenceResource presenceResource;
114 static uint8_t PresenceTimeOutSize = 0;
115 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
118 static OCMode myStackMode;
120 //TODO: revisit this design
121 static bool gRASetInfo = false;
123 OCDeviceEntityHandler defaultDeviceHandler;
124 void* defaultDeviceHandlerCallbackParameter = NULL;
125 static const char COAP_TCP[] = "coap+tcp:";
127 //-----------------------------------------------------------------------------
129 //-----------------------------------------------------------------------------
130 #define TAG "OIC_RI_STACK"
131 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
132 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
133 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
134 TAG, #arg " is NULL"); return (retVal); } }
135 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
136 TAG, #arg " is NULL"); return; } }
137 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
140 //TODO: we should allow the server to define this
141 #define MAX_OBSERVE_AGE (0x2FFFFUL)
143 #define MILLISECONDS_PER_SECOND (1000)
145 //-----------------------------------------------------------------------------
146 // Private internal function prototypes
147 //-----------------------------------------------------------------------------
150 * Generate handle of OCDoResource invocation for callback management.
152 * @return Generated OCDoResource handle.
154 static OCDoHandle GenerateInvocationHandle();
157 * Initialize resource data structures, variables, etc.
159 * @return ::OC_STACK_OK on success, some other value upon failure.
161 static OCStackResult initResources();
164 * Add a resource to the end of the linked list of resources.
166 * @param resource Resource to be added
168 static void insertResource(OCResource *resource);
171 * Find a resource in the linked list of resources.
173 * @param resource Resource to be found.
174 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
177 static OCResource *findResource(OCResource *resource);
180 * Insert a resource type into a resource's resource type linked list.
181 * If resource type already exists, it will not be inserted and the
182 * resourceType will be free'd.
183 * resourceType->next should be null to avoid memory leaks.
184 * Function returns silently for null args.
186 * @param resource Resource where resource type is to be inserted.
187 * @param resourceType Resource type to be inserted.
189 static void insertResourceType(OCResource *resource,
190 OCResourceType *resourceType);
193 * Get a resource type at the specified index within a resource.
195 * @param handle Handle of resource.
196 * @param index Index of resource type.
198 * @return Pointer to resource type if found, NULL otherwise.
200 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
204 * Insert a resource interface into a resource's resource interface linked list.
205 * If resource interface already exists, it will not be inserted and the
206 * resourceInterface will be free'd.
207 * resourceInterface->next should be null to avoid memory leaks.
209 * @param resource Resource where resource interface is to be inserted.
210 * @param resourceInterface Resource interface to be inserted.
212 static void insertResourceInterface(OCResource *resource,
213 OCResourceInterface *resourceInterface);
216 * Get a resource interface at the specified index within a resource.
218 * @param handle Handle of resource.
219 * @param index Index of resource interface.
221 * @return Pointer to resource interface if found, NULL otherwise.
223 static OCResourceInterface *findResourceInterfaceAtIndex(
224 OCResourceHandle handle, uint8_t index);
227 * Delete all of the dynamically allocated elements that were created for the resource type.
229 * @param resourceType Specified resource type.
231 static void deleteResourceType(OCResourceType *resourceType);
234 * Delete all of the dynamically allocated elements that were created for the resource interface.
236 * @param resourceInterface Specified resource interface.
238 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
241 * Delete all of the dynamically allocated elements that were created for the resource.
243 * @param resource Specified resource.
245 static void deleteResourceElements(OCResource *resource);
248 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
251 * @param handle Handle of resource to be deleted.
253 * @return ::OC_STACK_OK on success, some other value upon failure.
255 static OCStackResult deleteResource(OCResource *resource);
258 * Delete all of the resources in the resource list.
260 static void deleteAllResources();
263 * Increment resource sequence number. Handles rollover.
265 * @param resPtr Pointer to resource.
267 static void incrementSequenceNumber(OCResource * resPtr);
270 * Verify the lengths of the URI and the query separately.
272 * @param inputUri Input URI and query.
273 * @param uriLen The length of the initial URI with query.
274 * @return ::OC_STACK_OK on success, some other value upon failure.
276 static OCStackResult verifyUriQueryLength(const char * inputUri,
280 * Attempts to initialize every network interface that the CA Layer might have compiled in.
282 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
283 * return something other than @ref CA_STATUS_OK, then this function fails.
285 * @return ::CA_STATUS_OK on success, some other value upon failure.
287 static CAResult_t OCSelectNetwork();
290 * Get the CoAP ticks after the specified number of milli-seconds.
292 * @param afterMilliSeconds Milli-seconds.
296 static uint32_t GetTicks(uint32_t afterMilliSeconds);
299 * Convert CAResponseResult_t to OCStackResult.
301 * @param caCode CAResponseResult_t code.
302 * @return ::OC_STACK_OK on success, some other value upon failure.
304 static OCStackResult CAToOCStackResult(CAResponseResult_t caCode);
307 * Convert OCStackResult to CAResponseResult_t.
309 * @param caCode OCStackResult code.
310 * @param method OCMethod method the return code replies to.
311 * @return ::CA_CONTENT on OK, some other value upon failure.
313 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
316 * Convert OCTransportFlags_t to CATransportModifiers_t.
318 * @param ocConType OCTransportFlags_t input.
319 * @return CATransportFlags
321 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
324 * Convert CATransportFlags_t to OCTransportModifiers_t.
326 * @param caConType CATransportFlags_t input.
327 * @return OCTransportFlags
329 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
332 * Handle response from presence request.
334 * @param endPoint CA remote endpoint.
335 * @param responseInfo CA response info.
336 * @return ::OC_STACK_OK on success, some other value upon failure.
338 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
339 const CAResponseInfo_t *responseInfo);
342 * This function will be called back by CA layer when a response is received.
344 * @param endPoint CA remote endpoint.
345 * @param responseInfo CA response info.
347 static void HandleCAResponses(const CAEndpoint_t* endPoint,
348 const CAResponseInfo_t* responseInfo);
351 * This function will be called back by CA layer when a request is received.
353 * @param endPoint CA remote endpoint.
354 * @param requestInfo CA request info.
356 static void HandleCARequests(const CAEndpoint_t* endPoint,
357 const CARequestInfo_t* requestInfo);
360 * Extract query from a URI.
362 * @param uri Full URI with query.
363 * @param query Pointer to string that will contain query.
364 * @param newURI Pointer to string that will contain URI.
365 * @return ::OC_STACK_OK on success, some other value upon failure.
367 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
370 * Finds a resource type in an OCResourceType link-list.
372 * @param resourceTypeList The link-list to be searched through.
373 * @param resourceTypeName The key to search for.
375 * @return Resource type that matches the key (ie. resourceTypeName) or
376 * NULL if there is either an invalid parameter or this function was unable to find the key.
378 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
379 const char * resourceTypeName);
382 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
383 * TTL will be set to maxAge.
385 * @param cbNode Callback Node for which presence ttl is to be reset.
386 * @param maxAge New value of ttl in seconds.
388 * @return ::OC_STACK_OK on success, some other value upon failure.
390 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
393 * Ensure the accept header option is set appropriatly before sending the requests and routing
394 * header option is updated with destination.
396 * @param object CA remote endpoint.
397 * @param requestInfo CA request info.
399 * @return ::OC_STACK_OK on success, some other value upon failure.
401 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
403 //-----------------------------------------------------------------------------
404 // Internal functions
405 //-----------------------------------------------------------------------------
407 uint32_t GetTicks(uint32_t afterMilliSeconds)
412 // Guard against overflow of uint32_t
413 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
414 COAP_TICKS_PER_SECOND)
416 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
424 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
426 VERIFY_NON_NULL_NR(in, FATAL);
427 VERIFY_NON_NULL_NR(out, FATAL);
429 out->adapter = (OCTransportAdapter)in->adapter;
430 out->flags = CAToOCTransportFlags(in->flags);
431 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
432 out->port = in->port;
433 out->interface = in->interface;
434 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
435 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
439 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
441 VERIFY_NON_NULL_NR(in, FATAL);
442 VERIFY_NON_NULL_NR(out, FATAL);
444 out->adapter = (CATransportAdapter_t)in->adapter;
445 out->flags = OCToCATransportFlags(in->flags);
446 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
447 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
448 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
450 out->port = in->port;
451 out->interface = in->interface;
454 void FixUpClientResponse(OCClientResponse *cr)
456 VERIFY_NON_NULL_NR(cr, FATAL);
458 cr->addr = &cr->devAddr;
459 cr->connType = (OCConnectivityType)
460 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
463 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
465 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
466 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
468 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
469 OCStackResult rmResult = RMAddInfo(object->routeData, &(requestInfo->info.options),
470 &(requestInfo->info.numOptions));
471 if (OC_STACK_OK != rmResult)
473 OIC_LOG(ERROR, TAG, "Add destination option failed");
478 // OC stack prefer CBOR encoded payloads.
479 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
480 CAResult_t result = CASendRequest(object, requestInfo);
481 if(CA_STATUS_OK != result)
483 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
484 return CAResultToOCResult(result);
488 //-----------------------------------------------------------------------------
489 // Internal API function
490 //-----------------------------------------------------------------------------
492 // This internal function is called to update the stack with the status of
493 // observers and communication failures
494 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
496 OCStackResult result = OC_STACK_ERROR;
497 ResourceObserver * observer = NULL;
498 OCEntityHandlerRequest ehRequest = {0};
502 case OC_OBSERVER_NOT_INTERESTED:
503 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
504 observer = GetObserverUsingToken (token, tokenLength);
507 result = FormOCEntityHandlerRequest(&ehRequest,
508 (OCRequestHandle)NULL,
511 (OCResourceHandle)NULL,
512 NULL, PAYLOAD_TYPE_REPRESENTATION,
514 OC_OBSERVE_DEREGISTER,
515 observer->observeId);
516 if(result != OC_STACK_OK)
520 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
521 observer->resource->entityHandlerCallbackParam);
524 result = DeleteObserverUsingToken (token, tokenLength);
525 if(result == OC_STACK_OK)
527 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
531 result = OC_STACK_OK;
532 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
536 case OC_OBSERVER_STILL_INTERESTED:
537 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
538 observer = GetObserverUsingToken (token, tokenLength);
541 observer->forceHighQos = 0;
542 observer->failedCommCount = 0;
543 result = OC_STACK_OK;
547 result = OC_STACK_OBSERVER_NOT_FOUND;
551 case OC_OBSERVER_FAILED_COMM:
552 OIC_LOG(DEBUG, TAG, "observer is unreachable");
553 observer = GetObserverUsingToken (token, tokenLength);
556 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
558 result = FormOCEntityHandlerRequest(&ehRequest,
559 (OCRequestHandle)NULL,
562 (OCResourceHandle)NULL,
563 NULL, PAYLOAD_TYPE_REPRESENTATION,
565 OC_OBSERVE_DEREGISTER,
566 observer->observeId);
567 if(result != OC_STACK_OK)
569 return OC_STACK_ERROR;
571 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
572 observer->resource->entityHandlerCallbackParam);
574 result = DeleteObserverUsingToken (token, tokenLength);
575 if(result == OC_STACK_OK)
577 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
581 result = OC_STACK_OK;
582 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
587 observer->failedCommCount++;
588 result = OC_STACK_CONTINUE;
590 observer->forceHighQos = 1;
591 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
595 OIC_LOG(ERROR, TAG, "Unknown status");
596 result = OC_STACK_ERROR;
601 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
603 OCStackResult ret = OC_STACK_ERROR;
608 ret = OC_STACK_RESOURCE_CREATED;
611 ret = OC_STACK_RESOURCE_DELETED;
619 ret = OC_STACK_INVALID_QUERY;
621 case CA_UNAUTHORIZED_REQ:
622 ret = OC_STACK_UNAUTHORIZED_REQ;
625 ret = OC_STACK_INVALID_OPTION;
628 ret = OC_STACK_NO_RESOURCE;
630 case CA_RETRANSMIT_TIMEOUT:
631 ret = OC_STACK_COMM_ERROR;
639 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
641 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
650 // This Response Code is like HTTP 204 "No Content" but only used in
651 // response to POST and PUT requests.
655 // This Response Code is like HTTP 200 "OK" but only used in response to
660 // This should not happen but,
661 // give it a value just in case but output an error
663 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
666 case OC_STACK_RESOURCE_CREATED:
669 case OC_STACK_RESOURCE_DELETED:
672 case OC_STACK_INVALID_QUERY:
675 case OC_STACK_INVALID_OPTION:
678 case OC_STACK_NO_RESOURCE:
681 case OC_STACK_COMM_ERROR:
682 ret = CA_RETRANSMIT_TIMEOUT;
684 case OC_STACK_UNAUTHORIZED_REQ:
685 ret = CA_UNAUTHORIZED_REQ;
693 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
695 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
697 // supply default behavior.
698 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
700 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
702 if ((caFlags & OC_MASK_SCOPE) == 0)
704 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
709 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
711 return (OCTransportFlags)caFlags;
714 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
716 uint32_t lowerBound = 0;
717 uint32_t higherBound = 0;
719 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
721 return OC_STACK_INVALID_PARAM;
724 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
726 cbNode->presence->TTL = maxAgeSeconds;
728 for (int index = 0; index < PresenceTimeOutSize; index++)
730 // Guard against overflow
731 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
734 lowerBound = GetTicks((PresenceTimeOut[index] *
735 cbNode->presence->TTL *
736 MILLISECONDS_PER_SECOND)/100);
740 lowerBound = GetTicks(UINT32_MAX);
743 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
746 higherBound = GetTicks((PresenceTimeOut[index + 1] *
747 cbNode->presence->TTL *
748 MILLISECONDS_PER_SECOND)/100);
752 higherBound = GetTicks(UINT32_MAX);
755 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
757 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
758 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
759 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
762 cbNode->presence->TTLlevel = 0;
764 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
768 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
770 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
772 return OC_RSRVD_TRIGGER_CREATE;
774 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
776 return OC_RSRVD_TRIGGER_CHANGE;
780 return OC_RSRVD_TRIGGER_DELETE;
784 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
788 return OC_PRESENCE_TRIGGER_CREATE;
790 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
792 return OC_PRESENCE_TRIGGER_CREATE;
794 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
796 return OC_PRESENCE_TRIGGER_CHANGE;
800 return OC_PRESENCE_TRIGGER_DELETE;
805 * The cononical presence allows constructed URIs to be string compared.
807 * requestUri must be a char array of size CA_MAX_URI_LENGTH
809 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
812 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
813 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
814 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
816 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
818 if (ep->adapter == CA_ADAPTER_IP)
820 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
822 if ('\0' == ep->addr[0]) // multicast
824 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
828 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
829 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
834 if ('\0' == ep->addr[0]) // multicast
836 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
837 ep->port = OC_MULTICAST_PORT;
839 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
840 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
844 // might work for other adapters (untested, but better than nothing)
845 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
846 OC_RSRVD_PRESENCE_URI);
850 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
851 const CAResponseInfo_t *responseInfo)
853 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
854 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
856 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
857 ClientCB * cbNode = NULL;
858 char *resourceTypeName = NULL;
859 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
860 OCStackResult result = OC_STACK_ERROR;
863 char presenceUri[CA_MAX_URI_LENGTH];
865 int presenceSubscribe = 0;
866 int multicastPresenceSubscribe = 0;
868 if (responseInfo->result != CA_CONTENT)
870 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
871 return OC_STACK_ERROR;
874 // check for unicast presence
875 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
876 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
878 return OC_STACK_INVALID_URI;
881 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
884 presenceSubscribe = 1;
888 // check for multiicast presence
889 CAEndpoint_t ep = { .adapter = endpoint->adapter,
890 .flags = endpoint->flags };
892 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
894 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
897 multicastPresenceSubscribe = 1;
901 if (!presenceSubscribe && !multicastPresenceSubscribe)
903 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
907 response.payload = NULL;
908 response.result = OC_STACK_OK;
910 CopyEndpointToDevAddr(endpoint, &response.devAddr);
911 FixUpClientResponse(&response);
913 if (responseInfo->info.payload)
915 result = OCParsePayload(&response.payload,
916 PAYLOAD_TYPE_PRESENCE,
917 responseInfo->info.payload,
918 responseInfo->info.payloadSize);
920 if(result != OC_STACK_OK)
922 OIC_LOG(ERROR, TAG, "Presence parse failed");
925 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
927 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
928 result = OC_STACK_ERROR;
931 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
932 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
933 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
936 if (presenceSubscribe)
938 if(cbNode->sequenceNumber == response.sequenceNumber)
940 OIC_LOG(INFO, TAG, "No presence change");
941 ResetPresenceTTL(cbNode, maxAge);
942 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
948 OIC_LOG(INFO, TAG, "Stopping presence");
949 response.result = OC_STACK_PRESENCE_STOPPED;
952 OICFree(cbNode->presence->timeOut);
953 OICFree(cbNode->presence);
954 cbNode->presence = NULL;
959 if(!cbNode->presence)
961 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
963 if(!(cbNode->presence))
965 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
966 result = OC_STACK_NO_MEMORY;
970 VERIFY_NON_NULL_V(cbNode->presence);
971 cbNode->presence->timeOut = NULL;
972 cbNode->presence->timeOut = (uint32_t *)
973 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
974 if(!(cbNode->presence->timeOut)){
976 "Could not allocate memory for cbNode->presence->timeOut");
977 OICFree(cbNode->presence);
978 result = OC_STACK_NO_MEMORY;
983 ResetPresenceTTL(cbNode, maxAge);
985 cbNode->sequenceNumber = response.sequenceNumber;
987 // Ensure that a filter is actually applied.
988 if( resourceTypeName && cbNode->filterResourceType)
990 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
999 // This is the multicast case
1000 OCMulticastNode* mcNode = NULL;
1001 mcNode = GetMCPresenceNode(presenceUri);
1005 if(mcNode->nonce == response.sequenceNumber)
1007 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1010 mcNode->nonce = response.sequenceNumber;
1014 OIC_LOG(INFO, TAG, "Stopping presence");
1015 response.result = OC_STACK_PRESENCE_STOPPED;
1020 char* uri = OICStrdup(presenceUri);
1024 "No Memory for URI to store in the presence node");
1025 result = OC_STACK_NO_MEMORY;
1029 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1030 if(result == OC_STACK_NO_MEMORY)
1033 "No Memory for Multicast Presence Node");
1037 // presence node now owns uri
1040 // Ensure that a filter is actually applied.
1041 if(resourceTypeName && cbNode->filterResourceType)
1043 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1050 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1052 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1054 FindAndDeleteClientCB(cbNode);
1058 OCPayloadDestroy(response.payload);
1062 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1064 VERIFY_NON_NULL_NR(endPoint, FATAL);
1065 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1067 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1069 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1070 #ifdef ROUTING_GATEWAY
1071 bool needRIHandling = false;
1073 * Routing manager is going to update either of endpoint or response or both.
1074 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1075 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1078 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1080 if(ret != OC_STACK_OK || !needRIHandling)
1082 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1088 * Put source in sender endpoint so that the next packet from application can be routed to
1089 * proper destination and remove "RM" coap header option before passing request / response to
1090 * RI as this option will make no sense to either RI or application.
1092 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1093 (uint8_t *) &(responseInfo->info.numOptions),
1094 (CAEndpoint_t *) endPoint);
1097 if(responseInfo->info.resourceUri &&
1098 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1100 HandlePresenceResponse(endPoint, responseInfo);
1104 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1105 responseInfo->info.tokenLength, NULL, NULL);
1107 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1108 responseInfo->info.tokenLength);
1112 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1113 if(responseInfo->result == CA_EMPTY)
1115 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1116 // We do not have a case for the client to receive a RESET
1117 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1119 //This is the case of receiving an ACK on a request to a slow resource!
1120 OIC_LOG(INFO, TAG, "This is a pure ACK");
1121 //TODO: should we inform the client
1122 // app that at least the request was received at the server?
1125 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1127 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1128 OIC_LOG(INFO, TAG, "Calling into application address space");
1130 OCClientResponse response =
1131 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1132 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1133 FixUpClientResponse(&response);
1134 response.resourceUri = responseInfo->info.resourceUri;
1135 memcpy(response.identity.id, responseInfo->info.identity.id,
1136 sizeof (response.identity.id));
1137 response.identity.id_length = responseInfo->info.identity.id_length;
1139 response.result = CAToOCStackResult(responseInfo->result);
1140 cbNode->callBack(cbNode->context,
1141 cbNode->handle, &response);
1142 FindAndDeleteClientCB(cbNode);
1146 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1147 OIC_LOG(INFO, TAG, "Calling into application address space");
1149 OCClientResponse response =
1150 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1151 response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1152 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1153 FixUpClientResponse(&response);
1154 response.resourceUri = responseInfo->info.resourceUri;
1155 memcpy(response.identity.id, responseInfo->info.identity.id,
1156 sizeof (response.identity.id));
1157 response.identity.id_length = responseInfo->info.identity.id_length;
1159 response.result = CAToOCStackResult(responseInfo->result);
1161 if(responseInfo->info.payload &&
1162 responseInfo->info.payloadSize)
1164 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1165 // check the security resource
1166 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1168 type = PAYLOAD_TYPE_SECURITY;
1170 else if (cbNode->method == OC_REST_DISCOVER)
1172 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1173 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1175 type = PAYLOAD_TYPE_DISCOVERY;
1177 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1179 type = PAYLOAD_TYPE_DEVICE;
1181 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1183 type = PAYLOAD_TYPE_PLATFORM;
1185 #ifdef ROUTING_GATEWAY
1186 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1188 type = PAYLOAD_TYPE_REPRESENTATION;
1191 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1193 type = PAYLOAD_TYPE_RD;
1196 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1198 type = PAYLOAD_TYPE_REPRESENTATION;
1203 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1204 cbNode->method, cbNode->requestUri);
1208 else if (cbNode->method == OC_REST_GET ||
1209 cbNode->method == OC_REST_PUT ||
1210 cbNode->method == OC_REST_POST ||
1211 cbNode->method == OC_REST_OBSERVE ||
1212 cbNode->method == OC_REST_OBSERVE_ALL ||
1213 cbNode->method == OC_REST_DELETE)
1215 char targetUri[MAX_URI_LENGTH];
1216 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s",
1217 OC_RSRVD_RD_URI, OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1218 if (strcmp(targetUri, cbNode->requestUri) == 0)
1220 type = PAYLOAD_TYPE_RD;
1222 if (type == PAYLOAD_TYPE_INVALID)
1224 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1225 cbNode->method, cbNode->requestUri);
1226 type = PAYLOAD_TYPE_REPRESENTATION;
1231 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1232 cbNode->method, cbNode->requestUri);
1236 if(OC_STACK_OK != OCParsePayload(&response.payload,
1238 responseInfo->info.payload,
1239 responseInfo->info.payloadSize))
1241 OIC_LOG(ERROR, TAG, "Error converting payload");
1242 OCPayloadDestroy(response.payload);
1247 response.numRcvdVendorSpecificHeaderOptions = 0;
1248 if(responseInfo->info.numOptions > 0)
1251 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1252 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1255 uint32_t observationOption;
1256 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1257 for (observationOption=0, i=0;
1258 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1262 (observationOption << 8) | optionData[i];
1264 response.sequenceNumber = observationOption;
1266 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1271 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1274 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1276 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1277 OCPayloadDestroy(response.payload);
1281 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1283 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1284 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1288 if (cbNode->method == OC_REST_OBSERVE &&
1289 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1290 response.sequenceNumber <= cbNode->sequenceNumber)
1292 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1293 response.sequenceNumber);
1297 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1300 cbNode->sequenceNumber = response.sequenceNumber;
1302 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1304 FindAndDeleteClientCB(cbNode);
1308 // To keep discovery callbacks active.
1309 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1310 MILLISECONDS_PER_SECOND);
1314 //Need to send ACK when the response is CON
1315 if(responseInfo->info.type == CA_MSG_CONFIRM)
1317 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1318 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1321 OCPayloadDestroy(response.payload);
1328 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1329 if(responseInfo->result == CA_EMPTY)
1331 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1332 if(responseInfo->info.type == CA_MSG_RESET)
1334 OIC_LOG(INFO, TAG, "This is a RESET");
1335 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1336 OC_OBSERVER_NOT_INTERESTED);
1338 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1340 OIC_LOG(INFO, TAG, "This is a pure ACK");
1341 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1342 OC_OBSERVER_STILL_INTERESTED);
1345 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1347 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1348 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1349 OC_OBSERVER_FAILED_COMM);
1354 if(!cbNode && !observer)
1356 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1357 || myStackMode == OC_GATEWAY)
1359 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1360 if(responseInfo->result == CA_EMPTY)
1362 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1366 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1367 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1368 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1372 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1373 || myStackMode == OC_GATEWAY)
1375 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1376 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1378 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1379 responseInfo->info.messageId);
1381 if (responseInfo->info.type == CA_MSG_RESET)
1383 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1384 responseInfo->info.messageId);
1391 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1395 * This function handles error response from CA
1396 * code shall be added to handle the errors
1398 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1400 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1402 if(NULL == endPoint)
1404 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1408 if(NULL == errrorInfo)
1410 OIC_LOG(ERROR, TAG, "errrorInfo is NULL");
1413 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1417 * This function sends out Direct Stack Responses. These are responses that are not coming
1418 * from the application entity handler. These responses have no payload and are usually ACKs,
1419 * RESETs or some error conditions that were caught by the stack.
1421 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1422 const CAResponseResult_t responseResult, const CAMessageType_t type,
1423 const uint8_t numOptions, const CAHeaderOption_t *options,
1424 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1426 CAResponseInfo_t respInfo = {
1427 .result = responseResult
1429 respInfo.info.messageId = coapID;
1430 respInfo.info.numOptions = numOptions;
1432 if (respInfo.info.numOptions)
1434 respInfo.info.options =
1435 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1436 memcpy (respInfo.info.options, options,
1437 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1441 respInfo.info.payload = NULL;
1442 respInfo.info.token = token;
1443 respInfo.info.tokenLength = tokenLength;
1444 respInfo.info.type = type;
1445 respInfo.info.resourceUri = OICStrdup (resourceUri);
1446 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1448 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1449 // Add the destination to route option from the endpoint->routeData.
1450 OCStackResult result = RMAddInfo(endPoint->routeData,
1451 &(respInfo.info.options),
1452 &(respInfo.info.numOptions));
1453 if(OC_STACK_OK != result)
1455 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1460 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1462 // resourceUri in the info field is cloned in the CA layer and
1463 // thus ownership is still here.
1464 OICFree (respInfo.info.resourceUri);
1465 OICFree (respInfo.info.options);
1466 if(CA_STATUS_OK != caResult)
1468 OIC_LOG(ERROR, TAG, "CASendResponse error");
1469 return CAResultToOCResult(caResult);
1474 //This function will be called back by CA layer when a request is received
1475 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1477 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1480 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1486 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
1490 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1491 #ifdef ROUTING_GATEWAY
1492 bool needRIHandling = false;
1494 * Routing manager is going to update either of endpoint or request or both.
1495 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1496 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1497 * destination. It can also remove "RM" coap header option before passing request / response to
1498 * RI as this option will make no sense to either RI or application.
1500 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1502 if(OC_STACK_OK != ret || !needRIHandling)
1504 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1510 * Put source in sender endpoint so that the next packet from application can be routed to
1511 * proper destination and remove RM header option.
1513 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
1514 (uint8_t *) &(requestInfo->info.numOptions),
1515 (CAEndpoint_t *) endPoint);
1519 if (requestInfo->info.resourceUri &&
1520 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1522 HandleKeepAliveRequest(endPoint, requestInfo);
1527 OCStackResult requestResult = OC_STACK_ERROR;
1529 if(myStackMode == OC_CLIENT)
1531 //TODO: should the client be responding to requests?
1535 OCServerProtocolRequest serverRequest = {0};
1537 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1539 char * uriWithoutQuery = NULL;
1540 char * query = NULL;
1542 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1544 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1546 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1549 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1550 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1552 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1554 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1555 OICFree(uriWithoutQuery);
1559 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1560 OICFree(uriWithoutQuery);
1567 if(strlen(query) < MAX_QUERY_LENGTH)
1569 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1574 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1580 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1582 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1583 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1584 memcpy (serverRequest.payload, requestInfo->info.payload,
1585 requestInfo->info.payloadSize);
1589 serverRequest.reqTotalSize = 0;
1592 switch (requestInfo->method)
1595 serverRequest.method = OC_REST_GET;
1598 serverRequest.method = OC_REST_PUT;
1601 serverRequest.method = OC_REST_POST;
1604 serverRequest.method = OC_REST_DELETE;
1607 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1608 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1609 requestInfo->info.type, requestInfo->info.numOptions,
1610 requestInfo->info.options, requestInfo->info.token,
1611 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1612 OICFree(serverRequest.payload);
1616 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1617 requestInfo->info.tokenLength);
1619 serverRequest.tokenLength = requestInfo->info.tokenLength;
1620 if (serverRequest.tokenLength) {
1622 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1624 if (!serverRequest.requestToken)
1626 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1627 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1628 requestInfo->info.type, requestInfo->info.numOptions,
1629 requestInfo->info.options, requestInfo->info.token,
1630 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1631 OICFree(serverRequest.payload);
1634 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1637 switch (requestInfo->info.acceptFormat)
1639 case CA_FORMAT_APPLICATION_CBOR:
1640 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1642 case CA_FORMAT_UNDEFINED:
1643 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1646 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1649 if (requestInfo->info.type == CA_MSG_CONFIRM)
1651 serverRequest.qos = OC_HIGH_QOS;
1655 serverRequest.qos = OC_LOW_QOS;
1657 // CA does not need the following field
1658 // Are we sure CA does not need them? how is it responding to multicast
1659 serverRequest.delayedResNeeded = 0;
1661 serverRequest.coapID = requestInfo->info.messageId;
1663 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1665 // copy vendor specific header options
1666 uint8_t tempNum = (requestInfo->info.numOptions);
1668 // Assume no observation requested and it is a pure GET.
1669 // If obs registration/de-registration requested it'll be fetched from the
1670 // options in GetObserveHeaderOption()
1671 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1673 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1674 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1677 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1678 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1679 requestInfo->info.type, requestInfo->info.numOptions,
1680 requestInfo->info.options, requestInfo->info.token,
1681 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1682 OICFree(serverRequest.payload);
1683 OICFree(serverRequest.requestToken);
1686 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1687 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1689 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1690 sizeof(CAHeaderOption_t)*tempNum);
1693 requestResult = HandleStackRequests (&serverRequest);
1695 // Send ACK to client as precursor to slow response
1696 if(requestResult == OC_STACK_SLOW_RESOURCE)
1698 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1699 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1701 else if(requestResult != OC_STACK_OK)
1703 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1705 CAResponseResult_t stackResponse =
1706 OCToCAStackResult(requestResult, serverRequest.method);
1708 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1709 requestInfo->info.type, requestInfo->info.numOptions,
1710 requestInfo->info.options, requestInfo->info.token,
1711 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1713 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1714 // The token is copied in there, and is thus still owned by this function.
1715 OICFree(serverRequest.payload);
1716 OICFree(serverRequest.requestToken);
1717 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
1720 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1722 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1723 OCStackResult result = OC_STACK_ERROR;
1724 ResourceHandling resHandling;
1725 OCResource *resource;
1726 if(!protocolRequest)
1728 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1729 return OC_STACK_INVALID_PARAM;
1732 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1733 protocolRequest->tokenLength);
1736 OIC_LOG(INFO, TAG, "This is a new Server Request");
1737 result = AddServerRequest(&request, protocolRequest->coapID,
1738 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1739 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1740 protocolRequest->observationOption, protocolRequest->qos,
1741 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1742 protocolRequest->payload, protocolRequest->requestToken,
1743 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1744 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1745 &protocolRequest->devAddr);
1746 if (OC_STACK_OK != result)
1748 OIC_LOG(ERROR, TAG, "Error adding server request");
1754 OIC_LOG(ERROR, TAG, "Out of Memory");
1755 return OC_STACK_NO_MEMORY;
1758 if(!protocolRequest->reqMorePacket)
1760 request->requestComplete = 1;
1765 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1768 if(request->requestComplete)
1770 OIC_LOG(INFO, TAG, "This Server Request is complete");
1771 result = DetermineResourceHandling (request, &resHandling, &resource);
1772 if (result == OC_STACK_OK)
1774 result = ProcessRequest(resHandling, resource, request);
1779 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1780 result = OC_STACK_CONTINUE;
1785 bool validatePlatformInfo(OCPlatformInfo info)
1788 if (!info.platformID)
1790 OIC_LOG(ERROR, TAG, "No platform ID found.");
1794 if (info.manufacturerName)
1796 size_t lenManufacturerName = strlen(info.manufacturerName);
1798 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1800 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
1806 OIC_LOG(ERROR, TAG, "No manufacturer name present");
1810 if (info.manufacturerUrl)
1812 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1814 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
1821 //-----------------------------------------------------------------------------
1823 //-----------------------------------------------------------------------------
1825 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1828 !raInfo->username ||
1829 !raInfo->hostname ||
1830 !raInfo->xmpp_domain)
1833 return OC_STACK_INVALID_PARAM;
1835 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1836 gRASetInfo = (result == OC_STACK_OK)? true : false;
1842 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1846 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1849 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1851 if(stackState == OC_STACK_INITIALIZED)
1853 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
1854 OCStop() between them are ignored.");
1858 #ifndef ROUTING_GATEWAY
1859 if (OC_GATEWAY == mode)
1861 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
1862 return OC_STACK_INVALID_PARAM;
1869 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
1870 return OC_STACK_ERROR;
1874 OCStackResult result = OC_STACK_ERROR;
1875 OIC_LOG(INFO, TAG, "Entering OCInit");
1878 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
1879 || (mode == OC_GATEWAY)))
1881 OIC_LOG(ERROR, TAG, "Invalid mode");
1882 return OC_STACK_ERROR;
1886 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1888 caglobals.client = true;
1890 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1892 caglobals.server = true;
1895 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1896 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
1898 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
1900 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
1901 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
1903 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
1906 defaultDeviceHandler = NULL;
1907 defaultDeviceHandlerCallbackParameter = NULL;
1909 result = CAResultToOCResult(CAInitialize());
1910 VERIFY_SUCCESS(result, OC_STACK_OK);
1912 result = CAResultToOCResult(OCSelectNetwork());
1913 VERIFY_SUCCESS(result, OC_STACK_OK);
1915 switch (myStackMode)
1918 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1919 result = CAResultToOCResult(CAStartDiscoveryServer());
1920 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
1923 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1924 result = CAResultToOCResult(CAStartListeningServer());
1925 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
1927 case OC_CLIENT_SERVER:
1929 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1930 result = CAResultToOCResult(CAStartListeningServer());
1931 if(result == OC_STACK_OK)
1933 result = CAResultToOCResult(CAStartDiscoveryServer());
1937 VERIFY_SUCCESS(result, OC_STACK_OK);
1940 CARegisterKeepAliveHandler(HandleKeepAliveConnCB, HandleKeepAliveDisconnCB);
1943 #ifdef WITH_PRESENCE
1944 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
1945 #endif // WITH_PRESENCE
1947 //Update Stack state to initialized
1948 stackState = OC_STACK_INITIALIZED;
1950 // Initialize resource
1951 if(myStackMode != OC_CLIENT)
1953 result = initResources();
1956 // Initialize the SRM Policy Engine
1957 if(result == OC_STACK_OK)
1959 result = SRMInitPolicyEngine();
1960 // TODO after BeachHead delivery: consolidate into single SRMInit()
1963 #ifdef ROUTING_GATEWAY
1964 if (OC_GATEWAY == myStackMode)
1966 result = RMInitialize();
1971 if(result == OC_STACK_OK)
1973 result = InitializeKeepAlive();
1978 if(result != OC_STACK_OK)
1980 OIC_LOG(ERROR, TAG, "Stack initialization error");
1981 deleteAllResources();
1983 stackState = OC_STACK_UNINITIALIZED;
1988 OCStackResult OCStop()
1990 OIC_LOG(INFO, TAG, "Entering OCStop");
1992 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1994 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
1997 else if (stackState != OC_STACK_INITIALIZED)
1999 OIC_LOG(ERROR, TAG, "Stack not initialized");
2000 return OC_STACK_ERROR;
2003 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2005 #ifdef WITH_PRESENCE
2006 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2007 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2008 presenceResource.presenceTTL = 0;
2009 #endif // WITH_PRESENCE
2011 #ifdef ROUTING_GATEWAY
2012 if (OC_GATEWAY == myStackMode)
2019 TerminateKeepAlive();
2022 // Free memory dynamically allocated for resources
2023 deleteAllResources();
2025 DeletePlatformInfo();
2027 // Remove all observers
2028 DeleteObserverList();
2029 // Remove all the client callbacks
2030 DeleteClientCBList();
2032 // De-init the SRM Policy Engine
2033 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2034 SRMDeInitPolicyEngine();
2037 stackState = OC_STACK_UNINITIALIZED;
2041 OCStackResult OCStartMulticastServer()
2043 if(stackState != OC_STACK_INITIALIZED)
2045 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2046 return OC_STACK_ERROR;
2048 CAResult_t ret = CAStartListeningServer();
2049 if (CA_STATUS_OK != ret)
2051 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2052 return OC_STACK_ERROR;
2057 OCStackResult OCStopMulticastServer()
2059 CAResult_t ret = CAStopListeningServer();
2060 if (CA_STATUS_OK != ret)
2062 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2063 return OC_STACK_ERROR;
2068 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2073 return CA_MSG_CONFIRM;
2078 return CA_MSG_NONCONFIRM;
2082 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
2086 query = strchr (inputUri, '?');
2090 if((query - inputUri) > MAX_URI_LENGTH)
2092 return OC_STACK_INVALID_URI;
2095 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
2097 return OC_STACK_INVALID_QUERY;
2100 else if(uriLen > MAX_URI_LENGTH)
2102 return OC_STACK_INVALID_URI;
2108 * A request uri consists of the following components in order:
2111 * CoAP over UDP prefix "coap://"
2112 * CoAP over TCP prefix "coap+tcp://"
2114 * IPv6 address "[1234::5678]"
2115 * IPv4 address "192.168.1.1"
2116 * optional port ":5683"
2117 * resource uri "/oc/core..."
2119 * for PRESENCE requests, extract resource type.
2121 static OCStackResult ParseRequestUri(const char *fullUri,
2122 OCTransportAdapter adapter,
2123 OCTransportFlags flags,
2124 OCDevAddr **devAddr,
2126 char **resourceType)
2128 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2130 OCStackResult result = OC_STACK_OK;
2131 OCDevAddr *da = NULL;
2135 // provide defaults for all returned values
2142 *resourceUri = NULL;
2146 *resourceType = NULL;
2149 // delimit url prefix, if any
2150 const char *start = fullUri;
2151 char *slash2 = strstr(start, "//");
2156 char *slash = strchr(start, '/');
2159 return OC_STACK_INVALID_URI;
2162 // process url scheme
2163 size_t prefixLen = slash2 - fullUri;
2167 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2173 // TODO: this logic should come in with unit tests exercising the various strings
2174 // processs url prefix, if any
2175 size_t urlLen = slash - start;
2179 if (urlLen && devAddr)
2180 { // construct OCDevAddr
2181 if (start[0] == '[')
2183 char *close = strchr(++start, ']');
2184 if (!close || close > slash)
2186 return OC_STACK_INVALID_URI;
2189 if (close[1] == ':')
2193 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2194 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2198 char *dot = strchr(start, '.');
2199 if (dot && dot < slash)
2201 colon = strchr(start, ':');
2202 end = (colon && colon < slash) ? colon : slash;
2206 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2210 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2211 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2220 if (len >= sizeof(da->addr))
2222 return OC_STACK_INVALID_URI;
2224 // collect port, if any
2225 if (colon && colon < slash)
2227 for (colon++; colon < slash; colon++)
2230 if (c < '0' || c > '9')
2232 return OC_STACK_INVALID_URI;
2234 port = 10 * port + c - '0';
2239 if (len >= sizeof(da->addr))
2241 return OC_STACK_INVALID_URI;
2244 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2247 return OC_STACK_NO_MEMORY;
2249 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2251 da->adapter = adapter;
2253 if (!strncmp(fullUri, "coaps:", 6))
2255 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2260 // process resource uri, if any
2262 { // request uri and query
2263 size_t ulen = strlen(slash); // resource uri length
2264 size_t tlen = 0; // resource type length
2267 static const char strPresence[] = "/oic/ad?rt=";
2268 static const size_t lenPresence = sizeof(strPresence) - 1;
2269 if (!strncmp(slash, strPresence, lenPresence))
2271 type = slash + lenPresence;
2272 tlen = ulen - lenPresence;
2277 *resourceUri = (char *)OICMalloc(ulen + 1);
2280 result = OC_STACK_NO_MEMORY;
2283 strcpy(*resourceUri, slash);
2286 if (type && resourceType)
2288 *resourceType = (char *)OICMalloc(tlen + 1);
2291 result = OC_STACK_NO_MEMORY;
2295 OICStrcpy(*resourceType, (tlen+1), type);
2302 // free all returned values
2309 OICFree(*resourceUri);
2313 OICFree(*resourceType);
2318 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2319 char *resourceUri, char **requestUri)
2321 char uri[CA_MAX_URI_LENGTH];
2323 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2325 *requestUri = OICStrdup(uri);
2328 return OC_STACK_NO_MEMORY;
2335 * Discover or Perform requests on a specified resource
2337 OCStackResult OCDoResource(OCDoHandle *handle,
2339 const char *requestUri,
2340 const OCDevAddr *destination,
2342 OCConnectivityType connectivityType,
2343 OCQualityOfService qos,
2344 OCCallbackData *cbData,
2345 OCHeaderOption *options,
2348 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2350 // Validate input parameters
2351 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2352 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2353 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2355 OCStackResult result = OC_STACK_ERROR;
2356 CAResult_t caResult;
2357 CAToken_t token = NULL;
2358 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2359 ClientCB *clientCB = NULL;
2360 OCDoHandle resHandle = NULL;
2361 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2362 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2364 OCTransportAdapter adapter;
2365 OCTransportFlags flags;
2366 // the request contents are put here
2367 CARequestInfo_t requestInfo = {.method = CA_GET};
2368 // requestUri will be parsed into the following three variables
2369 OCDevAddr *devAddr = NULL;
2370 char *resourceUri = NULL;
2371 char *resourceType = NULL;
2373 // This validation is broken, but doesn't cause harm
2374 size_t uriLen = strlen(requestUri );
2375 if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
2381 * Support original behavior with address on resourceUri argument.
2383 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2384 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2386 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2388 if (result != OC_STACK_OK)
2390 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2397 case OC_REST_OBSERVE:
2398 case OC_REST_OBSERVE_ALL:
2399 case OC_REST_CANCEL_OBSERVE:
2400 requestInfo.method = CA_GET;
2403 requestInfo.method = CA_PUT;
2406 requestInfo.method = CA_POST;
2408 case OC_REST_DELETE:
2409 requestInfo.method = CA_DELETE;
2411 case OC_REST_DISCOVER:
2413 if (destination || devAddr)
2415 requestInfo.isMulticast = false;
2419 tmpDevAddr.adapter = adapter;
2420 tmpDevAddr.flags = flags;
2421 destination = &tmpDevAddr;
2422 requestInfo.isMulticast = true;
2424 // CA_DISCOVER will become GET and isMulticast
2425 requestInfo.method = CA_GET;
2427 #ifdef WITH_PRESENCE
2428 case OC_REST_PRESENCE:
2429 // Replacing method type with GET because "presence"
2430 // is a stack layer only implementation.
2431 requestInfo.method = CA_GET;
2435 result = OC_STACK_INVALID_METHOD;
2439 if (!devAddr && !destination)
2441 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2442 result = OC_STACK_INVALID_PARAM;
2446 /* If not original behavior, use destination argument */
2447 if (destination && !devAddr)
2449 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2452 result = OC_STACK_NO_MEMORY;
2455 *devAddr = *destination;
2458 resHandle = GenerateInvocationHandle();
2461 result = OC_STACK_NO_MEMORY;
2465 caResult = CAGenerateToken(&token, tokenLength);
2466 if (caResult != CA_STATUS_OK)
2468 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2469 result= OC_STACK_ERROR;
2473 // fill in request data
2474 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2475 requestInfo.info.token = token;
2476 requestInfo.info.tokenLength = tokenLength;
2477 requestInfo.info.resourceUri = resourceUri;
2479 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2481 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2482 options, numOptions, OC_OBSERVE_REGISTER);
2483 if (result != OC_STACK_OK)
2487 requestInfo.info.numOptions = numOptions + 1;
2491 requestInfo.info.numOptions = numOptions;
2492 requestInfo.info.options =
2493 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2494 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2495 numOptions * sizeof(CAHeaderOption_t));
2498 CopyDevAddrToEndpoint(devAddr, &endpoint);
2503 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2506 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2509 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2513 requestInfo.info.payload = NULL;
2514 requestInfo.info.payloadSize = 0;
2515 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2518 if (result != OC_STACK_OK)
2520 OIC_LOG(ERROR, TAG, "CACreateEndpoint error");
2524 // prepare for response
2525 #ifdef WITH_PRESENCE
2526 if (method == OC_REST_PRESENCE)
2528 char *presenceUri = NULL;
2529 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2530 if (OC_STACK_OK != result)
2535 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2536 // Presence notification will form a canonical uri to
2537 // look for callbacks into the application.
2538 resourceUri = presenceUri;
2542 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2543 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2544 method, devAddr, resourceUri, resourceType, ttl);
2545 if (OC_STACK_OK != result)
2550 devAddr = NULL; // Client CB list entry now owns it
2551 resourceUri = NULL; // Client CB list entry now owns it
2552 resourceType = NULL; // Client CB list entry now owns it
2555 result = OCSendRequest(&endpoint, &requestInfo);
2556 if (OC_STACK_OK != result)
2563 *handle = resHandle;
2567 if (result != OC_STACK_OK)
2569 OIC_LOG(ERROR, TAG, "OCDoResource error");
2570 FindAndDeleteClientCB(clientCB);
2571 CADestroyToken(token);
2579 // This is the owner of the payload object, so we free it
2580 OCPayloadDestroy(payload);
2581 OICFree(requestInfo.info.payload);
2583 OICFree(resourceUri);
2584 OICFree(resourceType);
2585 OICFree(requestInfo.info.options);
2589 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2593 * This ftn is implemented one of two ways in the case of observation:
2595 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2596 * Remove the callback associated on client side.
2597 * When the next notification comes in from server,
2598 * reply with RESET message to server.
2599 * Keep in mind that the server will react to RESET only
2600 * if the last notification was sent as CON
2602 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2603 * and it is associated with an observe request
2604 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2605 * Send CON Observe request to server with
2606 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2607 * Remove the callback associated on client side.
2609 OCStackResult ret = OC_STACK_OK;
2610 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2611 CARequestInfo_t requestInfo = {.method = CA_GET};
2615 return OC_STACK_INVALID_PARAM;
2618 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2621 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2622 return OC_STACK_ERROR;
2625 switch (clientCB->method)
2627 case OC_REST_OBSERVE:
2628 case OC_REST_OBSERVE_ALL:
2630 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
2631 clientCB->requestUri);
2632 if (qos != OC_HIGH_QOS)
2634 FindAndDeleteClientCB(clientCB);
2638 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2640 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2641 requestInfo.info.token = clientCB->token;
2642 requestInfo.info.tokenLength = clientCB->tokenLength;
2644 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2645 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2647 return OC_STACK_ERROR;
2649 requestInfo.info.numOptions = numOptions + 1;
2650 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2652 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2654 ret = OCSendRequest(&endpoint, &requestInfo);
2656 if (requestInfo.info.options)
2658 OICFree (requestInfo.info.options);
2660 if (requestInfo.info.resourceUri)
2662 OICFree (requestInfo.info.resourceUri);
2667 case OC_REST_DISCOVER:
2668 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2669 clientCB->requestUri);
2670 FindAndDeleteClientCB(clientCB);
2673 #ifdef WITH_PRESENCE
2674 case OC_REST_PRESENCE:
2675 FindAndDeleteClientCB(clientCB);
2680 ret = OC_STACK_INVALID_METHOD;
2688 * @brief Register Persistent storage callback.
2689 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2691 * OC_STACK_OK - No errors; Success
2692 * OC_STACK_INVALID_PARAM - Invalid parameter
2694 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2696 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2697 if(!persistentStorageHandler)
2699 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2700 return OC_STACK_INVALID_PARAM;
2704 if( !persistentStorageHandler->open ||
2705 !persistentStorageHandler->close ||
2706 !persistentStorageHandler->read ||
2707 !persistentStorageHandler->unlink ||
2708 !persistentStorageHandler->write)
2710 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2711 return OC_STACK_INVALID_PARAM;
2714 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2717 #ifdef WITH_PRESENCE
2719 OCStackResult OCProcessPresence()
2721 OCStackResult result = OC_STACK_OK;
2723 // the following line floods the log with messages that are irrelevant
2724 // to most purposes. Uncomment as needed.
2725 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2726 ClientCB* cbNode = NULL;
2727 OCClientResponse clientResponse;
2728 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2730 LL_FOREACH(cbList, cbNode)
2732 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2737 uint32_t now = GetTicks(0);
2738 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2739 cbNode->presence->TTLlevel);
2740 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2742 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2747 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2749 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2750 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2752 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2754 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2756 clientResponse.sequenceNumber = 0;
2757 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2758 clientResponse.devAddr = *cbNode->devAddr;
2759 FixUpClientResponse(&clientResponse);
2760 clientResponse.payload = NULL;
2762 // Increment the TTLLevel (going to a next state), so we don't keep
2763 // sending presence notification to client.
2764 cbNode->presence->TTLlevel++;
2765 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2766 cbNode->presence->TTLlevel);
2768 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2769 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2771 FindAndDeleteClientCB(cbNode);
2775 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2780 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2781 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2782 CARequestInfo_t requestInfo = {.method = CA_GET};
2784 OIC_LOG(DEBUG, TAG, "time to test server presence");
2786 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2788 requestData.type = CA_MSG_NONCONFIRM;
2789 requestData.token = cbNode->token;
2790 requestData.tokenLength = cbNode->tokenLength;
2791 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2792 requestInfo.method = CA_GET;
2793 requestInfo.info = requestData;
2795 result = OCSendRequest(&endpoint, &requestInfo);
2796 if (OC_STACK_OK != result)
2801 cbNode->presence->TTLlevel++;
2802 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2805 if (result != OC_STACK_OK)
2807 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
2812 #endif // WITH_PRESENCE
2814 OCStackResult OCProcess()
2816 #ifdef WITH_PRESENCE
2817 OCProcessPresence();
2819 CAHandleRequestResponse();
2821 #ifdef ROUTING_GATEWAY
2831 #ifdef WITH_PRESENCE
2832 OCStackResult OCStartPresence(const uint32_t ttl)
2834 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2835 OCChangeResourceProperty(
2836 &(((OCResource *)presenceResource.handle)->resourceProperties),
2839 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2841 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2842 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
2846 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2847 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
2851 presenceResource.presenceTTL = ttl;
2853 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
2855 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2857 presenceState = OC_PRESENCE_INITIALIZED;
2859 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2861 CAToken_t caToken = NULL;
2862 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2863 if (caResult != CA_STATUS_OK)
2865 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2866 CADestroyToken(caToken);
2867 return OC_STACK_ERROR;
2870 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2871 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
2872 CADestroyToken(caToken);
2875 // Each time OCStartPresence is called
2876 // a different random 32-bit integer number is used
2877 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2879 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2880 OC_PRESENCE_TRIGGER_CREATE);
2883 OCStackResult OCStopPresence()
2885 OCStackResult result = OC_STACK_ERROR;
2887 if(presenceResource.handle)
2889 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2891 // make resource inactive
2892 result = OCChangeResourceProperty(
2893 &(((OCResource *) presenceResource.handle)->resourceProperties),
2897 if(result != OC_STACK_OK)
2900 "Changing the presence resource properties to ACTIVE not successful");
2904 return SendStopNotification();
2908 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
2909 void* callbackParameter)
2911 defaultDeviceHandler = entityHandler;
2912 defaultDeviceHandlerCallbackParameter = callbackParameter;
2917 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
2919 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
2921 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
2923 if (validatePlatformInfo(platformInfo))
2925 return SavePlatformInfo(platformInfo);
2929 return OC_STACK_INVALID_PARAM;
2934 return OC_STACK_ERROR;
2938 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2940 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
2942 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
2944 OIC_LOG(ERROR, TAG, "Null or empty device name.");
2945 return OC_STACK_INVALID_PARAM;
2948 return SaveDeviceInfo(deviceInfo);
2951 OCStackResult OCCreateResource(OCResourceHandle *handle,
2952 const char *resourceTypeName,
2953 const char *resourceInterfaceName,
2954 const char *uri, OCEntityHandler entityHandler,
2955 void* callbackParam,
2956 uint8_t resourceProperties)
2959 OCResource *pointer = NULL;
2960 OCStackResult result = OC_STACK_ERROR;
2962 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
2964 if(myStackMode == OC_CLIENT)
2966 return OC_STACK_INVALID_PARAM;
2968 // Validate parameters
2969 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2971 OIC_LOG(ERROR, TAG, "URI is empty or too long");
2972 return OC_STACK_INVALID_URI;
2974 // Is it presented during resource discovery?
2975 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
2977 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
2978 return OC_STACK_INVALID_PARAM;
2981 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2983 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2986 // Make sure resourceProperties bitmask has allowed properties specified
2987 if (resourceProperties
2988 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
2989 OC_EXPLICIT_DISCOVERABLE))
2991 OIC_LOG(ERROR, TAG, "Invalid property");
2992 return OC_STACK_INVALID_PARAM;
2995 // If the headResource is NULL, then no resources have been created...
2996 pointer = headResource;
2999 // At least one resources is in the resource list, so we need to search for
3000 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3003 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3005 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3006 return OC_STACK_INVALID_PARAM;
3008 pointer = pointer->next;
3011 // Create the pointer and insert it into the resource list
3012 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3015 result = OC_STACK_NO_MEMORY;
3018 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3020 insertResource(pointer);
3023 pointer->uri = OICStrdup(uri);
3026 result = OC_STACK_NO_MEMORY;
3030 // Set properties. Set OC_ACTIVE
3031 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3034 // Add the resourcetype to the resource
3035 result = BindResourceTypeToResource(pointer, resourceTypeName);
3036 if (result != OC_STACK_OK)
3038 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3042 // Add the resourceinterface to the resource
3043 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3044 if (result != OC_STACK_OK)
3046 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3050 // If an entity handler has been passed, attach it to the newly created
3051 // resource. Otherwise, set the default entity handler.
3054 pointer->entityHandler = entityHandler;
3055 pointer->entityHandlerCallbackParam = callbackParam;
3059 pointer->entityHandler = defaultResourceEHandler;
3060 pointer->entityHandlerCallbackParam = NULL;
3064 result = OC_STACK_OK;
3066 #ifdef WITH_PRESENCE
3067 if (presenceResource.handle)
3069 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3070 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3074 if (result != OC_STACK_OK)
3076 // Deep delete of resource and other dynamic elements that it contains
3077 deleteResource(pointer);
3083 OCStackResult OCBindResource(
3084 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3086 OCResource *resource = NULL;
3089 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3091 // Validate parameters
3092 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3093 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3094 // Container cannot contain itself
3095 if (collectionHandle == resourceHandle)
3097 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3098 return OC_STACK_INVALID_PARAM;
3101 // Use the handle to find the resource in the resource linked list
3102 resource = findResource((OCResource *) collectionHandle);
3105 OIC_LOG(ERROR, TAG, "Collection handle not found");
3106 return OC_STACK_INVALID_PARAM;
3109 // Look for an open slot to add add the child resource.
3110 // If found, add it and return success
3111 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
3113 if (!resource->rsrcResources[i])
3115 resource->rsrcResources[i] = (OCResource *) resourceHandle;
3116 OIC_LOG(INFO, TAG, "resource bound");
3118 #ifdef WITH_PRESENCE
3119 if (presenceResource.handle)
3121 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3122 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3123 OC_PRESENCE_TRIGGER_CHANGE);
3131 // Unable to add resourceHandle, so return error
3132 return OC_STACK_ERROR;
3135 OCStackResult OCUnBindResource(
3136 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3138 OCResource *resource = NULL;
3141 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3143 // Validate parameters
3144 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3145 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3146 // Container cannot contain itself
3147 if (collectionHandle == resourceHandle)
3149 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3150 return OC_STACK_INVALID_PARAM;
3153 // Use the handle to find the resource in the resource linked list
3154 resource = findResource((OCResource *) collectionHandle);
3157 OIC_LOG(ERROR, TAG, "Collection handle not found");
3158 return OC_STACK_INVALID_PARAM;
3161 // Look for an open slot to add add the child resource.
3162 // If found, add it and return success
3163 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
3165 if (resourceHandle == resource->rsrcResources[i])
3167 resource->rsrcResources[i] = (OCResource *) NULL;
3168 OIC_LOG(INFO, TAG, "resource unbound");
3170 // Send notification when resource is unbounded successfully.
3171 #ifdef WITH_PRESENCE
3172 if (presenceResource.handle)
3174 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3175 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3176 OC_PRESENCE_TRIGGER_CHANGE);
3183 OIC_LOG(INFO, TAG, "resource not found in collection");
3185 // Unable to add resourceHandle, so return error
3186 return OC_STACK_ERROR;
3189 // Precondition is that the parameter has been checked to not equal NULL.
3190 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3192 if (resourceItemName[0] < 'a' || resourceItemName[0] > 'z')
3198 while (resourceItemName[index] != '\0')
3200 if (resourceItemName[index] != '.' &&
3201 resourceItemName[index] != '-' &&
3202 (resourceItemName[index] < 'a' || resourceItemName[index] > 'z') &&
3203 (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3212 OCStackResult BindResourceTypeToResource(OCResource* resource,
3213 const char *resourceTypeName)
3215 OCResourceType *pointer = NULL;
3217 OCStackResult result = OC_STACK_ERROR;
3219 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3221 if (!ValidateResourceTypeInterface(resourceTypeName))
3223 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3224 return OC_STACK_INVALID_PARAM;
3227 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3230 result = OC_STACK_NO_MEMORY;
3234 str = OICStrdup(resourceTypeName);
3237 result = OC_STACK_NO_MEMORY;
3240 pointer->resourcetypename = str;
3242 insertResourceType(resource, pointer);
3243 result = OC_STACK_OK;
3246 if (result != OC_STACK_OK)
3255 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3256 const char *resourceInterfaceName)
3258 OCResourceInterface *pointer = NULL;
3260 OCStackResult result = OC_STACK_ERROR;
3262 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3264 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3266 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3267 return OC_STACK_INVALID_PARAM;
3270 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3272 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3275 result = OC_STACK_NO_MEMORY;
3279 str = OICStrdup(resourceInterfaceName);
3282 result = OC_STACK_NO_MEMORY;
3285 pointer->name = str;
3287 // Bind the resourceinterface to the resource
3288 insertResourceInterface(resource, pointer);
3290 result = OC_STACK_OK;
3293 if (result != OC_STACK_OK)
3302 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3303 const char *resourceTypeName)
3306 OCStackResult result = OC_STACK_ERROR;
3307 OCResource *resource = NULL;
3309 resource = findResource((OCResource *) handle);
3312 OIC_LOG(ERROR, TAG, "Resource not found");
3313 return OC_STACK_ERROR;
3316 result = BindResourceTypeToResource(resource, resourceTypeName);
3318 #ifdef WITH_PRESENCE
3319 if(presenceResource.handle)
3321 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3322 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3329 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3330 const char *resourceInterfaceName)
3333 OCStackResult result = OC_STACK_ERROR;
3334 OCResource *resource = NULL;
3336 resource = findResource((OCResource *) handle);
3339 OIC_LOG(ERROR, TAG, "Resource not found");
3340 return OC_STACK_ERROR;
3343 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3345 #ifdef WITH_PRESENCE
3346 if (presenceResource.handle)
3348 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3349 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3356 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3358 OCResource *pointer = headResource;
3360 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3364 *numResources = *numResources + 1;
3365 pointer = pointer->next;
3370 OCResourceHandle OCGetResourceHandle(uint8_t index)
3372 OCResource *pointer = headResource;
3374 for( uint8_t i = 0; i < index && pointer; ++i)
3376 pointer = pointer->next;
3378 return (OCResourceHandle) pointer;
3381 OCStackResult OCDeleteResource(OCResourceHandle handle)
3385 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3386 return OC_STACK_INVALID_PARAM;
3389 OCResource *resource = findResource((OCResource *) handle);
3390 if (resource == NULL)
3392 OIC_LOG(ERROR, TAG, "Resource not found");
3393 return OC_STACK_NO_RESOURCE;
3396 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3398 OIC_LOG(ERROR, TAG, "Error deleting resource");
3399 return OC_STACK_ERROR;
3405 const char *OCGetResourceUri(OCResourceHandle handle)
3407 OCResource *resource = NULL;
3409 resource = findResource((OCResource *) handle);
3412 return resource->uri;
3414 return (const char *) NULL;
3417 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3419 OCResource *resource = NULL;
3421 resource = findResource((OCResource *) handle);
3424 return resource->resourceProperties;
3426 return (OCResourceProperty)-1;
3429 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3430 uint8_t *numResourceTypes)
3432 OCResource *resource = NULL;
3433 OCResourceType *pointer = NULL;
3435 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3436 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3438 *numResourceTypes = 0;
3440 resource = findResource((OCResource *) handle);
3443 pointer = resource->rsrcType;
3446 *numResourceTypes = *numResourceTypes + 1;
3447 pointer = pointer->next;
3453 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3455 OCResourceType *resourceType = NULL;
3457 resourceType = findResourceTypeAtIndex(handle, index);
3460 return resourceType->resourcetypename;
3462 return (const char *) NULL;
3465 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3466 uint8_t *numResourceInterfaces)
3468 OCResourceInterface *pointer = NULL;
3469 OCResource *resource = NULL;
3471 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3472 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3474 *numResourceInterfaces = 0;
3475 resource = findResource((OCResource *) handle);
3478 pointer = resource->rsrcInterface;
3481 *numResourceInterfaces = *numResourceInterfaces + 1;
3482 pointer = pointer->next;
3488 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3490 OCResourceInterface *resourceInterface = NULL;
3492 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3493 if (resourceInterface)
3495 return resourceInterface->name;
3497 return (const char *) NULL;
3500 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3503 OCResource *resource = NULL;
3505 if (index >= MAX_CONTAINED_RESOURCES)
3510 resource = findResource((OCResource *) collectionHandle);
3516 return resource->rsrcResources[index];
3519 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3520 OCEntityHandler entityHandler,
3521 void* callbackParam)
3523 OCResource *resource = NULL;
3525 // Validate parameters
3526 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3528 // Use the handle to find the resource in the resource linked list
3529 resource = findResource((OCResource *)handle);
3532 OIC_LOG(ERROR, TAG, "Resource not found");
3533 return OC_STACK_ERROR;
3537 resource->entityHandler = entityHandler;
3538 resource->entityHandlerCallbackParam = callbackParam;
3540 #ifdef WITH_PRESENCE
3541 if (presenceResource.handle)
3543 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3544 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3551 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3553 OCResource *resource = NULL;
3555 resource = findResource((OCResource *)handle);
3558 OIC_LOG(ERROR, TAG, "Resource not found");
3563 return resource->entityHandler;
3566 void incrementSequenceNumber(OCResource * resPtr)
3568 // Increment the sequence number
3569 resPtr->sequenceNum += 1;
3570 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3572 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3577 #ifdef WITH_PRESENCE
3578 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3579 OCPresenceTrigger trigger)
3581 OCResource *resPtr = NULL;
3582 OCStackResult result = OC_STACK_ERROR;
3583 OCMethod method = OC_REST_PRESENCE;
3584 uint32_t maxAge = 0;
3585 resPtr = findResource((OCResource *) presenceResource.handle);
3588 return OC_STACK_NO_RESOURCE;
3591 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3593 maxAge = presenceResource.presenceTTL;
3595 result = SendAllObserverNotification(method, resPtr, maxAge,
3596 trigger, resourceType, OC_LOW_QOS);
3602 OCStackResult SendStopNotification()
3604 OCResource *resPtr = NULL;
3605 OCStackResult result = OC_STACK_ERROR;
3606 OCMethod method = OC_REST_PRESENCE;
3607 resPtr = findResource((OCResource *) presenceResource.handle);
3610 return OC_STACK_NO_RESOURCE;
3613 // maxAge is 0. ResourceType is NULL.
3614 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3620 #endif // WITH_PRESENCE
3621 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3623 OCResource *resPtr = NULL;
3624 OCStackResult result = OC_STACK_ERROR;
3625 OCMethod method = OC_REST_NOMETHOD;
3626 uint32_t maxAge = 0;
3628 OIC_LOG(INFO, TAG, "Notifying all observers");
3629 #ifdef WITH_PRESENCE
3630 if(handle == presenceResource.handle)
3634 #endif // WITH_PRESENCE
3635 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3637 // Verify that the resource exists
3638 resPtr = findResource ((OCResource *) handle);
3641 return OC_STACK_NO_RESOURCE;
3645 //only increment in the case of regular observing (not presence)
3646 incrementSequenceNumber(resPtr);
3647 method = OC_REST_OBSERVE;
3648 maxAge = MAX_OBSERVE_AGE;
3649 #ifdef WITH_PRESENCE
3650 result = SendAllObserverNotification (method, resPtr, maxAge,
3651 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3653 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3660 OCNotifyListOfObservers (OCResourceHandle handle,
3661 OCObservationId *obsIdList,
3662 uint8_t numberOfIds,
3663 const OCRepPayload *payload,
3664 OCQualityOfService qos)
3666 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3668 OCResource *resPtr = NULL;
3669 //TODO: we should allow the server to define this
3670 uint32_t maxAge = MAX_OBSERVE_AGE;
3672 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3673 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3674 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3676 resPtr = findResource ((OCResource *) handle);
3677 if (NULL == resPtr || myStackMode == OC_CLIENT)
3679 return OC_STACK_NO_RESOURCE;
3683 incrementSequenceNumber(resPtr);
3685 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3686 payload, maxAge, qos));
3689 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3691 OCStackResult result = OC_STACK_ERROR;
3692 OCServerRequest *serverRequest = NULL;
3694 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
3696 // Validate input parameters
3697 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3698 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3701 // Get pointer to request info
3702 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3705 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3706 result = serverRequest->ehResponseHandler(ehResponse);
3712 //-----------------------------------------------------------------------------
3713 // Private internal function definitions
3714 //-----------------------------------------------------------------------------
3715 static OCDoHandle GenerateInvocationHandle()
3717 OCDoHandle handle = NULL;
3718 // Generate token here, it will be deleted when the transaction is deleted
3719 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3722 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3728 #ifdef WITH_PRESENCE
3729 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3730 OCResourceProperty resourceProperties, uint8_t enable)
3734 return OC_STACK_INVALID_PARAM;
3736 if (resourceProperties
3737 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3739 OIC_LOG(ERROR, TAG, "Invalid property");
3740 return OC_STACK_INVALID_PARAM;
3744 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3748 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3754 OCStackResult initResources()
3756 OCStackResult result = OC_STACK_OK;
3758 headResource = NULL;
3759 tailResource = NULL;
3760 // Init Virtual Resources
3761 #ifdef WITH_PRESENCE
3762 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3764 result = OCCreateResource(&presenceResource.handle,
3765 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3767 OC_RSRVD_PRESENCE_URI,
3771 //make resource inactive
3772 result = OCChangeResourceProperty(
3773 &(((OCResource *) presenceResource.handle)->resourceProperties),
3776 #ifndef WITH_ARDUINO
3777 if (result == OC_STACK_OK)
3779 result = SRMInitSecureResources();
3783 if(result == OC_STACK_OK)
3785 result = OCCreateResource(&deviceResource,
3786 OC_RSRVD_RESOURCE_TYPE_DEVICE,
3787 OC_RSRVD_INTERFACE_DEFAULT,
3788 OC_RSRVD_DEVICE_URI,
3792 if(result == OC_STACK_OK)
3794 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
3795 OC_RSRVD_INTERFACE_READ);
3799 if(result == OC_STACK_OK)
3801 result = OCCreateResource(&platformResource,
3802 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
3803 OC_RSRVD_INTERFACE_DEFAULT,
3804 OC_RSRVD_PLATFORM_URI,
3808 if(result == OC_STACK_OK)
3810 result = BindResourceInterfaceToResource((OCResource *)platformResource,
3811 OC_RSRVD_INTERFACE_READ);
3818 void insertResource(OCResource *resource)
3822 headResource = resource;
3823 tailResource = resource;
3827 tailResource->next = resource;
3828 tailResource = resource;
3830 resource->next = NULL;
3833 OCResource *findResource(OCResource *resource)
3835 OCResource *pointer = headResource;
3839 if (pointer == resource)
3843 pointer = pointer->next;
3848 void deleteAllResources()
3850 OCResource *pointer = headResource;
3851 OCResource *temp = NULL;
3855 temp = pointer->next;
3856 #ifdef WITH_PRESENCE
3857 if (pointer != (OCResource *) presenceResource.handle)
3859 #endif // WITH_PRESENCE
3860 deleteResource(pointer);
3861 #ifdef WITH_PRESENCE
3863 #endif // WITH_PRESENCE
3867 SRMDeInitSecureResources();
3869 #ifdef WITH_PRESENCE
3870 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3871 // presence notification attributed to their deletion to be processed.
3872 deleteResource((OCResource *) presenceResource.handle);
3873 #endif // WITH_PRESENCE
3876 OCStackResult deleteResource(OCResource *resource)
3878 OCResource *prev = NULL;
3879 OCResource *temp = NULL;
3882 OIC_LOG(DEBUG,TAG,"resource is NULL");
3883 return OC_STACK_INVALID_PARAM;
3886 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
3888 temp = headResource;
3891 if (temp == resource)
3893 // Invalidate all Resource Properties.
3894 resource->resourceProperties = (OCResourceProperty) 0;
3895 #ifdef WITH_PRESENCE
3896 if(resource != (OCResource *) presenceResource.handle)
3898 #endif // WITH_PRESENCE
3899 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3900 #ifdef WITH_PRESENCE
3903 if(presenceResource.handle)
3905 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3906 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
3909 // Only resource in list.
3910 if (temp == headResource && temp == tailResource)
3912 headResource = NULL;
3913 tailResource = NULL;
3916 else if (temp == headResource)
3918 headResource = temp->next;
3921 else if (temp == tailResource)
3923 tailResource = prev;
3924 tailResource->next = NULL;
3928 prev->next = temp->next;
3931 deleteResourceElements(temp);
3942 return OC_STACK_ERROR;
3945 void deleteResourceElements(OCResource *resource)
3952 OICFree(resource->uri);
3953 deleteResourceType(resource->rsrcType);
3954 deleteResourceInterface(resource->rsrcInterface);
3957 void deleteResourceType(OCResourceType *resourceType)
3959 OCResourceType *pointer = resourceType;
3960 OCResourceType *next = NULL;
3964 next = pointer->next;
3965 OICFree(pointer->resourcetypename);
3971 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3973 OCResourceInterface *pointer = resourceInterface;
3974 OCResourceInterface *next = NULL;
3978 next = pointer->next;
3979 OICFree(pointer->name);
3985 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3987 OCResourceType *pointer = NULL;
3988 OCResourceType *previous = NULL;
3989 if (!resource || !resourceType)
3993 // resource type list is empty.
3994 else if (!resource->rsrcType)
3996 resource->rsrcType = resourceType;
4000 pointer = resource->rsrcType;
4004 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4006 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4007 OICFree(resourceType->resourcetypename);
4008 OICFree(resourceType);
4012 pointer = pointer->next;
4014 previous->next = resourceType;
4016 resourceType->next = NULL;
4018 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4021 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4023 OCResource *resource = NULL;
4024 OCResourceType *pointer = NULL;
4026 // Find the specified resource
4027 resource = findResource((OCResource *) handle);
4033 // Make sure a resource has a resourcetype
4034 if (!resource->rsrcType)
4039 // Iterate through the list
4040 pointer = resource->rsrcType;
4041 for(uint8_t i = 0; i< index && pointer; ++i)
4043 pointer = pointer->next;
4048 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4050 if(resourceTypeList && resourceTypeName)
4052 OCResourceType * rtPointer = resourceTypeList;
4053 while(resourceTypeName && rtPointer)
4055 if(rtPointer->resourcetypename &&
4056 strcmp(resourceTypeName, (const char *)
4057 (rtPointer->resourcetypename)) == 0)
4061 rtPointer = rtPointer->next;
4069 * Insert a new interface into interface linked list only if not already present.
4070 * If alredy present, 2nd arg is free'd.
4071 * Default interface will always be first if present.
4073 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4075 OCResourceInterface *pointer = NULL;
4076 OCResourceInterface *previous = NULL;
4078 newInterface->next = NULL;
4080 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4082 if (!*firstInterface)
4084 *firstInterface = newInterface;
4086 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4088 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4090 OICFree(newInterface->name);
4091 OICFree(newInterface);
4096 newInterface->next = *firstInterface;
4097 *firstInterface = newInterface;
4102 pointer = *firstInterface;
4105 if (strcmp(newInterface->name, pointer->name) == 0)
4107 OICFree(newInterface->name);
4108 OICFree(newInterface);
4112 pointer = pointer->next;
4114 previous->next = newInterface;
4118 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4121 OCResource *resource = NULL;
4122 OCResourceInterface *pointer = NULL;
4124 // Find the specified resource
4125 resource = findResource((OCResource *) handle);
4131 // Make sure a resource has a resourceinterface
4132 if (!resource->rsrcInterface)
4137 // Iterate through the list
4138 pointer = resource->rsrcInterface;
4140 for (uint8_t i = 0; i < index && pointer; ++i)
4142 pointer = pointer->next;
4148 * This function splits the uri using the '?' delimiter.
4149 * "uriWithoutQuery" is the block of characters between the beginning
4150 * till the delimiter or '\0' which ever comes first.
4151 * "query" is whatever is to the right of the delimiter if present.
4152 * No delimiter sets the query to NULL.
4153 * If either are present, they will be malloc'ed into the params 2, 3.
4154 * The first param, *uri is left untouched.
4156 * NOTE: This function does not account for whitespace at the end of the uri NOR
4157 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4158 * part of the query.
4160 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4164 return OC_STACK_INVALID_URI;
4166 if(!query || !uriWithoutQuery)
4168 return OC_STACK_INVALID_PARAM;
4172 *uriWithoutQuery = NULL;
4174 size_t uriWithoutQueryLen = 0;
4175 size_t queryLen = 0;
4176 size_t uriLen = strlen(uri);
4178 char *pointerToDelimiter = strstr(uri, "?");
4180 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4181 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4183 if (uriWithoutQueryLen)
4185 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4186 if (!*uriWithoutQuery)
4190 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4194 *query = (char *) OICCalloc(queryLen + 1, 1);
4197 OICFree(*uriWithoutQuery);
4198 *uriWithoutQuery = NULL;
4201 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4207 return OC_STACK_NO_MEMORY;
4210 const OicUuid_t* OCGetServerInstanceID(void)
4212 static bool generated = false;
4213 static OicUuid_t sid;
4219 if (GetDoxmDeviceID(&sid) != OC_STACK_OK)
4221 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4228 const char* OCGetServerInstanceIDString(void)
4230 static bool generated = false;
4231 static char sidStr[UUID_STRING_SIZE];
4238 const OicUuid_t* sid = OCGetServerInstanceID();
4240 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4242 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4250 CAResult_t OCSelectNetwork()
4252 CAResult_t retResult = CA_STATUS_FAILED;
4253 CAResult_t caResult = CA_STATUS_OK;
4255 CATransportAdapter_t connTypes[] = {
4257 CA_ADAPTER_RFCOMM_BTEDR,
4258 CA_ADAPTER_GATT_BTLE,
4261 ,CA_ADAPTER_REMOTE_ACCESS
4268 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4270 for(int i = 0; i<numConnTypes; i++)
4272 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4273 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4275 caResult = CASelectNetwork(connTypes[i]);
4276 if(caResult == CA_STATUS_OK)
4278 retResult = CA_STATUS_OK;
4283 if(retResult != CA_STATUS_OK)
4285 return caResult; // Returns error of appropriate transport that failed fatally.
4291 OCStackResult CAResultToOCResult(CAResult_t caResult)
4297 case CA_STATUS_INVALID_PARAM:
4298 return OC_STACK_INVALID_PARAM;
4299 case CA_ADAPTER_NOT_ENABLED:
4300 return OC_STACK_ADAPTER_NOT_ENABLED;
4301 case CA_SERVER_STARTED_ALREADY:
4303 case CA_SERVER_NOT_STARTED:
4304 return OC_STACK_ERROR;
4305 case CA_DESTINATION_NOT_REACHABLE:
4306 return OC_STACK_COMM_ERROR;
4307 case CA_SOCKET_OPERATION_FAILED:
4308 return OC_STACK_COMM_ERROR;
4309 case CA_SEND_FAILED:
4310 return OC_STACK_COMM_ERROR;
4311 case CA_RECEIVE_FAILED:
4312 return OC_STACK_COMM_ERROR;
4313 case CA_MEMORY_ALLOC_FAILED:
4314 return OC_STACK_NO_MEMORY;
4315 case CA_REQUEST_TIMEOUT:
4316 return OC_STACK_TIMEOUT;
4317 case CA_DESTINATION_DISCONNECTED:
4318 return OC_STACK_COMM_ERROR;
4319 case CA_STATUS_FAILED:
4320 return OC_STACK_ERROR;
4321 case CA_NOT_SUPPORTED:
4322 return OC_STACK_NOTIMPL;
4324 return OC_STACK_ERROR;