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"
68 #include "coap_time.h"
73 #include <arpa/inet.h>
77 #define UINT32_MAX (0xFFFFFFFFUL)
80 //-----------------------------------------------------------------------------
82 //-----------------------------------------------------------------------------
85 OC_STACK_UNINITIALIZED = 0,
87 OC_STACK_UNINIT_IN_PROGRESS
93 OC_PRESENCE_UNINITIALIZED = 0,
94 OC_PRESENCE_INITIALIZED
98 //-----------------------------------------------------------------------------
100 //-----------------------------------------------------------------------------
101 static OCStackState stackState = OC_STACK_UNINITIALIZED;
103 OCResource *headResource = NULL;
104 static OCResource *tailResource = NULL;
105 static OCResourceHandle platformResource = {0};
106 static OCResourceHandle deviceResource = {0};
108 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
109 static PresenceResource presenceResource;
110 static uint8_t PresenceTimeOutSize = 0;
111 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
114 static OCMode myStackMode;
116 //TODO: revisit this design
117 static bool gRASetInfo = false;
119 OCDeviceEntityHandler defaultDeviceHandler;
120 void* defaultDeviceHandlerCallbackParameter = NULL;
121 static const char COAP_TCP[] = "coap+tcp:";
123 //-----------------------------------------------------------------------------
125 //-----------------------------------------------------------------------------
126 #define TAG "OIC_RI_STACK"
127 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
128 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
129 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
130 TAG, #arg " is NULL"); return (retVal); } }
131 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
132 TAG, #arg " is NULL"); return; } }
133 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
136 //TODO: we should allow the server to define this
137 #define MAX_OBSERVE_AGE (0x2FFFFUL)
139 #define MILLISECONDS_PER_SECOND (1000)
141 //-----------------------------------------------------------------------------
142 // Private internal function prototypes
143 //-----------------------------------------------------------------------------
146 * Generate handle of OCDoResource invocation for callback management.
148 * @return Generated OCDoResource handle.
150 static OCDoHandle GenerateInvocationHandle();
153 * Initialize resource data structures, variables, etc.
155 * @return ::OC_STACK_OK on success, some other value upon failure.
157 static OCStackResult initResources();
160 * Add a resource to the end of the linked list of resources.
162 * @param resource Resource to be added
164 static void insertResource(OCResource *resource);
167 * Find a resource in the linked list of resources.
169 * @param resource Resource to be found.
170 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
173 static OCResource *findResource(OCResource *resource);
176 * Insert a resource type into a resource's resource type linked list.
177 * If resource type already exists, it will not be inserted and the
178 * resourceType will be free'd.
179 * resourceType->next should be null to avoid memory leaks.
180 * Function returns silently for null args.
182 * @param resource Resource where resource type is to be inserted.
183 * @param resourceType Resource type to be inserted.
185 static void insertResourceType(OCResource *resource,
186 OCResourceType *resourceType);
189 * Get a resource type at the specified index within a resource.
191 * @param handle Handle of resource.
192 * @param index Index of resource type.
194 * @return Pointer to resource type if found, NULL otherwise.
196 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
200 * Insert a resource interface into a resource's resource interface linked list.
201 * If resource interface already exists, it will not be inserted and the
202 * resourceInterface will be free'd.
203 * resourceInterface->next should be null to avoid memory leaks.
205 * @param resource Resource where resource interface is to be inserted.
206 * @param resourceInterface Resource interface to be inserted.
208 static void insertResourceInterface(OCResource *resource,
209 OCResourceInterface *resourceInterface);
212 * Get a resource interface at the specified index within a resource.
214 * @param handle Handle of resource.
215 * @param index Index of resource interface.
217 * @return Pointer to resource interface if found, NULL otherwise.
219 static OCResourceInterface *findResourceInterfaceAtIndex(
220 OCResourceHandle handle, uint8_t index);
223 * Delete all of the dynamically allocated elements that were created for the resource type.
225 * @param resourceType Specified resource type.
227 static void deleteResourceType(OCResourceType *resourceType);
230 * Delete all of the dynamically allocated elements that were created for the resource interface.
232 * @param resourceInterface Specified resource interface.
234 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
237 * Delete all of the dynamically allocated elements that were created for the resource.
239 * @param resource Specified resource.
241 static void deleteResourceElements(OCResource *resource);
244 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
247 * @param handle Handle of resource to be deleted.
249 * @return ::OC_STACK_OK on success, some other value upon failure.
251 static OCStackResult deleteResource(OCResource *resource);
254 * Delete all of the resources in the resource list.
256 static void deleteAllResources();
259 * Increment resource sequence number. Handles rollover.
261 * @param resPtr Pointer to resource.
263 static void incrementSequenceNumber(OCResource * resPtr);
266 * Verify the lengths of the URI and the query separately.
268 * @param inputUri Input URI and query.
269 * @param uriLen The length of the initial URI with query.
270 * @return ::OC_STACK_OK on success, some other value upon failure.
272 static OCStackResult verifyUriQueryLength(const char * inputUri,
276 * Attempts to initialize every network interface that the CA Layer might have compiled in.
278 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
279 * return something other than @ref CA_STATUS_OK, then this function fails.
281 * @return ::CA_STATUS_OK on success, some other value upon failure.
283 static CAResult_t OCSelectNetwork();
286 * Get the CoAP ticks after the specified number of milli-seconds.
288 * @param afterMilliSeconds Milli-seconds.
292 static uint32_t GetTicks(uint32_t afterMilliSeconds);
295 * Convert CAResponseResult_t to OCStackResult.
297 * @param caCode CAResponseResult_t code.
298 * @return ::OC_STACK_OK on success, some other value upon failure.
300 static OCStackResult CAToOCStackResult(CAResponseResult_t caCode);
303 * Convert OCStackResult to CAResponseResult_t.
305 * @param caCode OCStackResult code.
306 * @param method OCMethod method the return code replies to.
307 * @return ::CA_CONTENT on OK, some other value upon failure.
309 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
312 * Convert OCTransportFlags_t to CATransportModifiers_t.
314 * @param ocConType OCTransportFlags_t input.
315 * @return CATransportFlags
317 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
320 * Convert CATransportFlags_t to OCTransportModifiers_t.
322 * @param caConType CATransportFlags_t input.
323 * @return OCTransportFlags
325 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
328 * Handle response from presence request.
330 * @param endPoint CA remote endpoint.
331 * @param responseInfo CA response info.
332 * @return ::OC_STACK_OK on success, some other value upon failure.
334 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
335 const CAResponseInfo_t *responseInfo);
338 * This function will be called back by CA layer when a response is received.
340 * @param endPoint CA remote endpoint.
341 * @param responseInfo CA response info.
343 static void HandleCAResponses(const CAEndpoint_t* endPoint,
344 const CAResponseInfo_t* responseInfo);
347 * This function will be called back by CA layer when a request is received.
349 * @param endPoint CA remote endpoint.
350 * @param requestInfo CA request info.
352 static void HandleCARequests(const CAEndpoint_t* endPoint,
353 const CARequestInfo_t* requestInfo);
356 * Extract query from a URI.
358 * @param uri Full URI with query.
359 * @param query Pointer to string that will contain query.
360 * @param newURI Pointer to string that will contain URI.
361 * @return ::OC_STACK_OK on success, some other value upon failure.
363 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
366 * Finds a resource type in an OCResourceType link-list.
368 * @param resourceTypeList The link-list to be searched through.
369 * @param resourceTypeName The key to search for.
371 * @return Resource type that matches the key (ie. resourceTypeName) or
372 * NULL if there is either an invalid parameter or this function was unable to find the key.
374 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
375 const char * resourceTypeName);
378 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
379 * TTL will be set to maxAge.
381 * @param cbNode Callback Node for which presence ttl is to be reset.
382 * @param maxAge New value of ttl in seconds.
384 * @return ::OC_STACK_OK on success, some other value upon failure.
386 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
389 * Ensure the accept header option is set appropriatly before sending the requests and routing
390 * header option is updated with destination.
392 * @param object CA remote endpoint.
393 * @param requestInfo CA request info.
395 * @return ::OC_STACK_OK on success, some other value upon failure.
397 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
399 //-----------------------------------------------------------------------------
400 // Internal functions
401 //-----------------------------------------------------------------------------
403 uint32_t GetTicks(uint32_t afterMilliSeconds)
408 // Guard against overflow of uint32_t
409 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
410 COAP_TICKS_PER_SECOND)
412 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
420 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
422 VERIFY_NON_NULL_NR(in, FATAL);
423 VERIFY_NON_NULL_NR(out, FATAL);
425 out->adapter = (OCTransportAdapter)in->adapter;
426 out->flags = CAToOCTransportFlags(in->flags);
427 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
428 out->port = in->port;
429 out->interface = in->interface;
430 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
431 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
435 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
437 VERIFY_NON_NULL_NR(in, FATAL);
438 VERIFY_NON_NULL_NR(out, FATAL);
440 out->adapter = (CATransportAdapter_t)in->adapter;
441 out->flags = OCToCATransportFlags(in->flags);
442 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
443 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
444 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
446 out->port = in->port;
447 out->interface = in->interface;
450 void FixUpClientResponse(OCClientResponse *cr)
452 VERIFY_NON_NULL_NR(cr, FATAL);
454 cr->addr = &cr->devAddr;
455 cr->connType = (OCConnectivityType)
456 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
459 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
461 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
462 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
464 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
465 OCStackResult rmResult = RMAddInfo(object->routeData, &(requestInfo->info.options),
466 &(requestInfo->info.numOptions));
467 if (OC_STACK_OK != rmResult)
469 OIC_LOG(ERROR, TAG, "Add destination option failed");
474 // OC stack prefer CBOR encoded payloads.
475 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
476 CAResult_t result = CASendRequest(object, requestInfo);
477 if(CA_STATUS_OK != result)
479 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
480 return CAResultToOCResult(result);
484 //-----------------------------------------------------------------------------
485 // Internal API function
486 //-----------------------------------------------------------------------------
488 // This internal function is called to update the stack with the status of
489 // observers and communication failures
490 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
492 OCStackResult result = OC_STACK_ERROR;
493 ResourceObserver * observer = NULL;
494 OCEntityHandlerRequest ehRequest = {0};
498 case OC_OBSERVER_NOT_INTERESTED:
499 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
500 observer = GetObserverUsingToken (token, tokenLength);
503 result = FormOCEntityHandlerRequest(&ehRequest,
504 (OCRequestHandle)NULL,
507 (OCResourceHandle)NULL,
508 NULL, PAYLOAD_TYPE_REPRESENTATION,
510 OC_OBSERVE_DEREGISTER,
511 observer->observeId);
512 if(result != OC_STACK_OK)
516 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
517 observer->resource->entityHandlerCallbackParam);
520 result = DeleteObserverUsingToken (token, tokenLength);
521 if(result == OC_STACK_OK)
523 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
527 result = OC_STACK_OK;
528 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
532 case OC_OBSERVER_STILL_INTERESTED:
533 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
534 observer = GetObserverUsingToken (token, tokenLength);
537 observer->forceHighQos = 0;
538 observer->failedCommCount = 0;
539 result = OC_STACK_OK;
543 result = OC_STACK_OBSERVER_NOT_FOUND;
547 case OC_OBSERVER_FAILED_COMM:
548 OIC_LOG(DEBUG, TAG, "observer is unreachable");
549 observer = GetObserverUsingToken (token, tokenLength);
552 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
554 result = FormOCEntityHandlerRequest(&ehRequest,
555 (OCRequestHandle)NULL,
558 (OCResourceHandle)NULL,
559 NULL, PAYLOAD_TYPE_REPRESENTATION,
561 OC_OBSERVE_DEREGISTER,
562 observer->observeId);
563 if(result != OC_STACK_OK)
565 return OC_STACK_ERROR;
567 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
568 observer->resource->entityHandlerCallbackParam);
570 result = DeleteObserverUsingToken (token, tokenLength);
571 if(result == OC_STACK_OK)
573 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
577 result = OC_STACK_OK;
578 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
583 observer->failedCommCount++;
584 result = OC_STACK_CONTINUE;
586 observer->forceHighQos = 1;
587 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
591 OIC_LOG(ERROR, TAG, "Unknown status");
592 result = OC_STACK_ERROR;
597 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
599 OCStackResult ret = OC_STACK_ERROR;
604 ret = OC_STACK_RESOURCE_CREATED;
607 ret = OC_STACK_RESOURCE_DELETED;
614 ret = OC_STACK_INVALID_QUERY;
616 case CA_UNAUTHORIZED_REQ:
617 ret = OC_STACK_UNAUTHORIZED_REQ;
620 ret = OC_STACK_INVALID_OPTION;
623 ret = OC_STACK_NO_RESOURCE;
625 case CA_RETRANSMIT_TIMEOUT:
626 ret = OC_STACK_COMM_ERROR;
634 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
636 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
645 // This Response Code is like HTTP 204 "No Content" but only used in
646 // response to POST and PUT requests.
650 // This Response Code is like HTTP 200 "OK" but only used in response to
655 // This should not happen but,
656 // give it a value just in case but output an error
658 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
661 case OC_STACK_RESOURCE_CREATED:
664 case OC_STACK_RESOURCE_DELETED:
667 case OC_STACK_INVALID_QUERY:
670 case OC_STACK_INVALID_OPTION:
673 case OC_STACK_NO_RESOURCE:
676 case OC_STACK_COMM_ERROR:
677 ret = CA_RETRANSMIT_TIMEOUT;
679 case OC_STACK_UNAUTHORIZED_REQ:
680 ret = CA_UNAUTHORIZED_REQ;
688 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
690 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
692 // supply default behavior.
693 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
695 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
697 if ((caFlags & OC_MASK_SCOPE) == 0)
699 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
704 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
706 return (OCTransportFlags)caFlags;
709 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
711 uint32_t lowerBound = 0;
712 uint32_t higherBound = 0;
714 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
716 return OC_STACK_INVALID_PARAM;
719 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
721 cbNode->presence->TTL = maxAgeSeconds;
723 for (int index = 0; index < PresenceTimeOutSize; index++)
725 // Guard against overflow
726 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
729 lowerBound = GetTicks((PresenceTimeOut[index] *
730 cbNode->presence->TTL *
731 MILLISECONDS_PER_SECOND)/100);
735 lowerBound = GetTicks(UINT32_MAX);
738 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
741 higherBound = GetTicks((PresenceTimeOut[index + 1] *
742 cbNode->presence->TTL *
743 MILLISECONDS_PER_SECOND)/100);
747 higherBound = GetTicks(UINT32_MAX);
750 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
752 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
753 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
754 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
757 cbNode->presence->TTLlevel = 0;
759 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
763 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
765 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
767 return OC_RSRVD_TRIGGER_CREATE;
769 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
771 return OC_RSRVD_TRIGGER_CHANGE;
775 return OC_RSRVD_TRIGGER_DELETE;
779 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
783 return OC_PRESENCE_TRIGGER_CREATE;
785 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
787 return OC_PRESENCE_TRIGGER_CREATE;
789 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
791 return OC_PRESENCE_TRIGGER_CHANGE;
795 return OC_PRESENCE_TRIGGER_DELETE;
800 * The cononical presence allows constructed URIs to be string compared.
802 * requestUri must be a char array of size CA_MAX_URI_LENGTH
804 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
807 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
808 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
809 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
811 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
813 if (ep->adapter == CA_ADAPTER_IP)
815 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
817 if ('\0' == ep->addr[0]) // multicast
819 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
823 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
824 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
829 if ('\0' == ep->addr[0]) // multicast
831 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
832 ep->port = OC_MULTICAST_PORT;
834 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
835 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
839 // might work for other adapters (untested, but better than nothing)
840 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
841 OC_RSRVD_PRESENCE_URI);
845 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
846 const CAResponseInfo_t *responseInfo)
848 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
849 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
851 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
852 ClientCB * cbNode = NULL;
853 char *resourceTypeName = NULL;
854 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
855 OCStackResult result = OC_STACK_ERROR;
858 char presenceUri[CA_MAX_URI_LENGTH];
860 int presenceSubscribe = 0;
861 int multicastPresenceSubscribe = 0;
863 if (responseInfo->result != CA_CONTENT)
865 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
866 return OC_STACK_ERROR;
869 // check for unicast presence
870 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
871 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
873 return OC_STACK_INVALID_URI;
876 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
879 presenceSubscribe = 1;
883 // check for multiicast presence
884 CAEndpoint_t ep = { .adapter = endpoint->adapter,
885 .flags = endpoint->flags };
887 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
889 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
892 multicastPresenceSubscribe = 1;
896 if (!presenceSubscribe && !multicastPresenceSubscribe)
898 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
902 response.payload = NULL;
903 response.result = OC_STACK_OK;
905 CopyEndpointToDevAddr(endpoint, &response.devAddr);
906 FixUpClientResponse(&response);
908 if (responseInfo->info.payload)
910 result = OCParsePayload(&response.payload,
911 PAYLOAD_TYPE_PRESENCE,
912 responseInfo->info.payload,
913 responseInfo->info.payloadSize);
915 if(result != OC_STACK_OK)
917 OIC_LOG(ERROR, TAG, "Presence parse failed");
920 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
922 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
923 result = OC_STACK_ERROR;
926 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
927 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
928 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
931 if (presenceSubscribe)
933 if(cbNode->sequenceNumber == response.sequenceNumber)
935 OIC_LOG(INFO, TAG, "No presence change");
936 ResetPresenceTTL(cbNode, maxAge);
937 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
943 OIC_LOG(INFO, TAG, "Stopping presence");
944 response.result = OC_STACK_PRESENCE_STOPPED;
947 OICFree(cbNode->presence->timeOut);
948 OICFree(cbNode->presence);
949 cbNode->presence = NULL;
954 if(!cbNode->presence)
956 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
958 if(!(cbNode->presence))
960 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
961 result = OC_STACK_NO_MEMORY;
965 VERIFY_NON_NULL_V(cbNode->presence);
966 cbNode->presence->timeOut = NULL;
967 cbNode->presence->timeOut = (uint32_t *)
968 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
969 if(!(cbNode->presence->timeOut)){
971 "Could not allocate memory for cbNode->presence->timeOut");
972 OICFree(cbNode->presence);
973 result = OC_STACK_NO_MEMORY;
978 ResetPresenceTTL(cbNode, maxAge);
980 cbNode->sequenceNumber = response.sequenceNumber;
982 // Ensure that a filter is actually applied.
983 if( resourceTypeName && cbNode->filterResourceType)
985 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
994 // This is the multicast case
995 OCMulticastNode* mcNode = NULL;
996 mcNode = GetMCPresenceNode(presenceUri);
1000 if(mcNode->nonce == response.sequenceNumber)
1002 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1005 mcNode->nonce = response.sequenceNumber;
1009 OIC_LOG(INFO, TAG, "Stopping presence");
1010 response.result = OC_STACK_PRESENCE_STOPPED;
1015 char* uri = OICStrdup(presenceUri);
1019 "No Memory for URI to store in the presence node");
1020 result = OC_STACK_NO_MEMORY;
1024 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1025 if(result == OC_STACK_NO_MEMORY)
1028 "No Memory for Multicast Presence Node");
1032 // presence node now owns uri
1035 // Ensure that a filter is actually applied.
1036 if(resourceTypeName && cbNode->filterResourceType)
1038 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1045 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1047 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1049 FindAndDeleteClientCB(cbNode);
1053 OCPayloadDestroy(response.payload);
1057 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1059 VERIFY_NON_NULL_NR(endPoint, FATAL);
1060 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1062 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1064 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1065 #ifdef ROUTING_GATEWAY
1066 bool needRIHandling = false;
1068 * Routing manager is going to update either of endpoint or response or both.
1069 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1070 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1073 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1075 if(ret != OC_STACK_OK || !needRIHandling)
1077 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1083 * Put source in sender endpoint so that the next packet from application can be routed to
1084 * proper destination and remove "RM" coap header option before passing request / response to
1085 * RI as this option will make no sense to either RI or application.
1087 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1088 (uint8_t *) &(responseInfo->info.numOptions),
1089 (CAEndpoint_t *) endPoint);
1092 if(responseInfo->info.resourceUri &&
1093 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1095 HandlePresenceResponse(endPoint, responseInfo);
1099 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1100 responseInfo->info.tokenLength, NULL, NULL);
1102 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1103 responseInfo->info.tokenLength);
1107 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1108 if(responseInfo->result == CA_EMPTY)
1110 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1111 // We do not have a case for the client to receive a RESET
1112 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1114 //This is the case of receiving an ACK on a request to a slow resource!
1115 OIC_LOG(INFO, TAG, "This is a pure ACK");
1116 //TODO: should we inform the client
1117 // app that at least the request was received at the server?
1120 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1122 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1123 OIC_LOG(INFO, TAG, "Calling into application address space");
1125 OCClientResponse response =
1126 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1127 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1128 FixUpClientResponse(&response);
1129 response.resourceUri = responseInfo->info.resourceUri;
1130 memcpy(response.identity.id, responseInfo->info.identity.id,
1131 sizeof (response.identity.id));
1132 response.identity.id_length = responseInfo->info.identity.id_length;
1134 response.result = CAToOCStackResult(responseInfo->result);
1135 cbNode->callBack(cbNode->context,
1136 cbNode->handle, &response);
1137 FindAndDeleteClientCB(cbNode);
1141 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1142 OIC_LOG(INFO, TAG, "Calling into application address space");
1144 OCClientResponse response =
1145 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1146 response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1147 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1148 FixUpClientResponse(&response);
1149 response.resourceUri = responseInfo->info.resourceUri;
1150 memcpy(response.identity.id, responseInfo->info.identity.id,
1151 sizeof (response.identity.id));
1152 response.identity.id_length = responseInfo->info.identity.id_length;
1154 response.result = CAToOCStackResult(responseInfo->result);
1156 if(responseInfo->info.payload &&
1157 responseInfo->info.payloadSize)
1159 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1160 // check the security resource
1161 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1163 type = PAYLOAD_TYPE_SECURITY;
1165 else if (cbNode->method == OC_REST_DISCOVER)
1167 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1168 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1170 type = PAYLOAD_TYPE_DISCOVERY;
1172 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1174 type = PAYLOAD_TYPE_DEVICE;
1176 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1178 type = PAYLOAD_TYPE_PLATFORM;
1180 #ifdef ROUTING_GATEWAY
1181 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1183 type = PAYLOAD_TYPE_REPRESENTATION;
1186 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1188 type = PAYLOAD_TYPE_RD;
1192 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1193 cbNode->method, cbNode->requestUri);
1197 else if (cbNode->method == OC_REST_GET ||
1198 cbNode->method == OC_REST_PUT ||
1199 cbNode->method == OC_REST_POST ||
1200 cbNode->method == OC_REST_OBSERVE ||
1201 cbNode->method == OC_REST_OBSERVE_ALL ||
1202 cbNode->method == OC_REST_DELETE)
1204 char targetUri[MAX_URI_LENGTH];
1205 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s",
1206 OC_RSRVD_RD_URI, OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1207 if (strcmp(targetUri, cbNode->requestUri) == 0)
1209 type = PAYLOAD_TYPE_RD;
1211 if (type == PAYLOAD_TYPE_INVALID)
1213 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1214 cbNode->method, cbNode->requestUri);
1215 type = PAYLOAD_TYPE_REPRESENTATION;
1220 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1221 cbNode->method, cbNode->requestUri);
1225 if(OC_STACK_OK != OCParsePayload(&response.payload,
1227 responseInfo->info.payload,
1228 responseInfo->info.payloadSize))
1230 OIC_LOG(ERROR, TAG, "Error converting payload");
1231 OCPayloadDestroy(response.payload);
1236 response.numRcvdVendorSpecificHeaderOptions = 0;
1237 if(responseInfo->info.numOptions > 0)
1240 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1241 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1244 uint32_t observationOption;
1245 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1246 for (observationOption=0, i=0;
1247 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1251 (observationOption << 8) | optionData[i];
1253 response.sequenceNumber = observationOption;
1255 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1260 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1263 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1265 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1266 OCPayloadDestroy(response.payload);
1270 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1272 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1273 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1277 if (cbNode->method == OC_REST_OBSERVE &&
1278 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1279 response.sequenceNumber <= cbNode->sequenceNumber)
1281 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1282 response.sequenceNumber);
1286 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1289 cbNode->sequenceNumber = response.sequenceNumber;
1291 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1293 FindAndDeleteClientCB(cbNode);
1297 // To keep discovery callbacks active.
1298 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1299 MILLISECONDS_PER_SECOND);
1303 //Need to send ACK when the response is CON
1304 if(responseInfo->info.type == CA_MSG_CONFIRM)
1306 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1307 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1310 OCPayloadDestroy(response.payload);
1317 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1318 if(responseInfo->result == CA_EMPTY)
1320 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1321 if(responseInfo->info.type == CA_MSG_RESET)
1323 OIC_LOG(INFO, TAG, "This is a RESET");
1324 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1325 OC_OBSERVER_NOT_INTERESTED);
1327 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1329 OIC_LOG(INFO, TAG, "This is a pure ACK");
1330 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1331 OC_OBSERVER_STILL_INTERESTED);
1334 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1336 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1337 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1338 OC_OBSERVER_FAILED_COMM);
1343 if(!cbNode && !observer)
1345 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1346 || myStackMode == OC_GATEWAY)
1348 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1349 if(responseInfo->result == CA_EMPTY)
1351 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1355 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1356 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1357 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1361 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1362 || myStackMode == OC_GATEWAY)
1364 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1365 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1367 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1368 responseInfo->info.messageId);
1370 if (responseInfo->info.type == CA_MSG_RESET)
1372 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1373 responseInfo->info.messageId);
1380 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1384 * This function handles error response from CA
1385 * code shall be added to handle the errors
1387 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1389 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1391 if(NULL == endPoint)
1393 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1397 if(NULL == errrorInfo)
1399 OIC_LOG(ERROR, TAG, "errrorInfo is NULL");
1402 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1406 * This function sends out Direct Stack Responses. These are responses that are not coming
1407 * from the application entity handler. These responses have no payload and are usually ACKs,
1408 * RESETs or some error conditions that were caught by the stack.
1410 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1411 const CAResponseResult_t responseResult, const CAMessageType_t type,
1412 const uint8_t numOptions, const CAHeaderOption_t *options,
1413 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1415 CAResponseInfo_t respInfo = {
1416 .result = responseResult
1418 respInfo.info.messageId = coapID;
1419 respInfo.info.numOptions = numOptions;
1421 if (respInfo.info.numOptions)
1423 respInfo.info.options =
1424 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1425 memcpy (respInfo.info.options, options,
1426 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1430 respInfo.info.payload = NULL;
1431 respInfo.info.token = token;
1432 respInfo.info.tokenLength = tokenLength;
1433 respInfo.info.type = type;
1434 respInfo.info.resourceUri = OICStrdup (resourceUri);
1435 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1437 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1438 // Add the destination to route option from the endpoint->routeData.
1439 OCStackResult result = RMAddInfo(endPoint->routeData,
1440 &(respInfo.info.options),
1441 &(respInfo.info.numOptions));
1442 if(OC_STACK_OK != result)
1444 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1449 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1451 // resourceUri in the info field is cloned in the CA layer and
1452 // thus ownership is still here.
1453 OICFree (respInfo.info.resourceUri);
1454 OICFree (respInfo.info.options);
1455 if(CA_STATUS_OK != caResult)
1457 OIC_LOG(ERROR, TAG, "CASendResponse error");
1458 return CAResultToOCResult(caResult);
1463 //This function will be called back by CA layer when a request is received
1464 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1466 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1469 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1475 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
1479 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1480 #ifdef ROUTING_GATEWAY
1481 bool needRIHandling = false;
1483 * Routing manager is going to update either of endpoint or request or both.
1484 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1485 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1486 * destination. It can also remove "RM" coap header option before passing request / response to
1487 * RI as this option will make no sense to either RI or application.
1489 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1491 if(OC_STACK_OK != ret || !needRIHandling)
1493 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1499 * Put source in sender endpoint so that the next packet from application can be routed to
1500 * proper destination and remove RM header option.
1502 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
1503 (uint8_t *) &(requestInfo->info.numOptions),
1504 (CAEndpoint_t *) endPoint);
1507 OCStackResult requestResult = OC_STACK_ERROR;
1509 if(myStackMode == OC_CLIENT)
1511 //TODO: should the client be responding to requests?
1515 OCServerProtocolRequest serverRequest = {0};
1517 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1519 char * uriWithoutQuery = NULL;
1520 char * query = NULL;
1522 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1524 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1526 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1529 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1530 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1532 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1534 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1535 OICFree(uriWithoutQuery);
1539 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1540 OICFree(uriWithoutQuery);
1547 if(strlen(query) < MAX_QUERY_LENGTH)
1549 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1554 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1560 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1562 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1563 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1564 memcpy (serverRequest.payload, requestInfo->info.payload,
1565 requestInfo->info.payloadSize);
1569 serverRequest.reqTotalSize = 0;
1572 switch (requestInfo->method)
1575 serverRequest.method = OC_REST_GET;
1578 serverRequest.method = OC_REST_PUT;
1581 serverRequest.method = OC_REST_POST;
1584 serverRequest.method = OC_REST_DELETE;
1587 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1588 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1589 requestInfo->info.type, requestInfo->info.numOptions,
1590 requestInfo->info.options, requestInfo->info.token,
1591 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1592 OICFree(serverRequest.payload);
1596 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1597 requestInfo->info.tokenLength);
1599 serverRequest.tokenLength = requestInfo->info.tokenLength;
1600 if (serverRequest.tokenLength) {
1602 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1604 if (!serverRequest.requestToken)
1606 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1607 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1608 requestInfo->info.type, requestInfo->info.numOptions,
1609 requestInfo->info.options, requestInfo->info.token,
1610 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1611 OICFree(serverRequest.payload);
1614 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1617 switch (requestInfo->info.acceptFormat)
1619 case CA_FORMAT_APPLICATION_CBOR:
1620 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1622 case CA_FORMAT_UNDEFINED:
1623 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1626 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1629 if (requestInfo->info.type == CA_MSG_CONFIRM)
1631 serverRequest.qos = OC_HIGH_QOS;
1635 serverRequest.qos = OC_LOW_QOS;
1637 // CA does not need the following field
1638 // Are we sure CA does not need them? how is it responding to multicast
1639 serverRequest.delayedResNeeded = 0;
1641 serverRequest.coapID = requestInfo->info.messageId;
1643 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1645 // copy vendor specific header options
1646 uint8_t tempNum = (requestInfo->info.numOptions);
1648 // Assume no observation requested and it is a pure GET.
1649 // If obs registration/de-registration requested it'll be fetched from the
1650 // options in GetObserveHeaderOption()
1651 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1653 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1654 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1657 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1658 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1659 requestInfo->info.type, requestInfo->info.numOptions,
1660 requestInfo->info.options, requestInfo->info.token,
1661 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1662 OICFree(serverRequest.payload);
1663 OICFree(serverRequest.requestToken);
1666 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1667 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1669 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1670 sizeof(CAHeaderOption_t)*tempNum);
1673 requestResult = HandleStackRequests (&serverRequest);
1675 // Send ACK to client as precursor to slow response
1676 if(requestResult == OC_STACK_SLOW_RESOURCE)
1678 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1679 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1681 else if(requestResult != OC_STACK_OK)
1683 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1685 CAResponseResult_t stackResponse =
1686 OCToCAStackResult(requestResult, serverRequest.method);
1688 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1689 requestInfo->info.type, requestInfo->info.numOptions,
1690 requestInfo->info.options, requestInfo->info.token,
1691 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1693 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1694 // The token is copied in there, and is thus still owned by this function.
1695 OICFree(serverRequest.payload);
1696 OICFree(serverRequest.requestToken);
1697 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
1700 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1702 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1703 OCStackResult result = OC_STACK_ERROR;
1704 ResourceHandling resHandling;
1705 OCResource *resource;
1706 if(!protocolRequest)
1708 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1709 return OC_STACK_INVALID_PARAM;
1712 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1713 protocolRequest->tokenLength);
1716 OIC_LOG(INFO, TAG, "This is a new Server Request");
1717 result = AddServerRequest(&request, protocolRequest->coapID,
1718 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1719 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1720 protocolRequest->observationOption, protocolRequest->qos,
1721 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1722 protocolRequest->payload, protocolRequest->requestToken,
1723 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1724 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1725 &protocolRequest->devAddr);
1726 if (OC_STACK_OK != result)
1728 OIC_LOG(ERROR, TAG, "Error adding server request");
1734 OIC_LOG(ERROR, TAG, "Out of Memory");
1735 return OC_STACK_NO_MEMORY;
1738 if(!protocolRequest->reqMorePacket)
1740 request->requestComplete = 1;
1745 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1748 if(request->requestComplete)
1750 OIC_LOG(INFO, TAG, "This Server Request is complete");
1751 result = DetermineResourceHandling (request, &resHandling, &resource);
1752 if (result == OC_STACK_OK)
1754 result = ProcessRequest(resHandling, resource, request);
1759 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1760 result = OC_STACK_CONTINUE;
1765 bool validatePlatformInfo(OCPlatformInfo info)
1768 if (!info.platformID)
1770 OIC_LOG(ERROR, TAG, "No platform ID found.");
1774 if (info.manufacturerName)
1776 size_t lenManufacturerName = strlen(info.manufacturerName);
1778 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1780 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
1786 OIC_LOG(ERROR, TAG, "No manufacturer name present");
1790 if (info.manufacturerUrl)
1792 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1794 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
1801 //-----------------------------------------------------------------------------
1803 //-----------------------------------------------------------------------------
1805 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1808 !raInfo->username ||
1809 !raInfo->hostname ||
1810 !raInfo->xmpp_domain)
1813 return OC_STACK_INVALID_PARAM;
1815 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1816 gRASetInfo = (result == OC_STACK_OK)? true : false;
1822 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1826 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1829 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1831 if(stackState == OC_STACK_INITIALIZED)
1833 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
1834 OCStop() between them are ignored.");
1838 #ifndef ROUTING_GATEWAY
1839 if (OC_GATEWAY == mode)
1841 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
1842 return OC_STACK_INVALID_PARAM;
1849 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
1850 return OC_STACK_ERROR;
1854 OCStackResult result = OC_STACK_ERROR;
1855 OIC_LOG(INFO, TAG, "Entering OCInit");
1858 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
1859 || (mode == OC_GATEWAY)))
1861 OIC_LOG(ERROR, TAG, "Invalid mode");
1862 return OC_STACK_ERROR;
1866 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1868 caglobals.client = true;
1870 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1872 caglobals.server = true;
1875 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1876 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
1878 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
1880 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
1881 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
1883 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
1886 defaultDeviceHandler = NULL;
1887 defaultDeviceHandlerCallbackParameter = NULL;
1889 result = CAResultToOCResult(CAInitialize());
1890 VERIFY_SUCCESS(result, OC_STACK_OK);
1892 result = CAResultToOCResult(OCSelectNetwork());
1893 VERIFY_SUCCESS(result, OC_STACK_OK);
1895 switch (myStackMode)
1898 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1899 result = CAResultToOCResult(CAStartDiscoveryServer());
1900 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
1903 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1904 result = CAResultToOCResult(CAStartListeningServer());
1905 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
1907 case OC_CLIENT_SERVER:
1909 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1910 result = CAResultToOCResult(CAStartListeningServer());
1911 if(result == OC_STACK_OK)
1913 result = CAResultToOCResult(CAStartDiscoveryServer());
1917 VERIFY_SUCCESS(result, OC_STACK_OK);
1919 #ifdef WITH_PRESENCE
1920 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
1921 #endif // WITH_PRESENCE
1923 //Update Stack state to initialized
1924 stackState = OC_STACK_INITIALIZED;
1926 // Initialize resource
1927 if(myStackMode != OC_CLIENT)
1929 result = initResources();
1932 // Initialize the SRM Policy Engine
1933 if(result == OC_STACK_OK)
1935 result = SRMInitPolicyEngine();
1936 // TODO after BeachHead delivery: consolidate into single SRMInit()
1939 #ifdef ROUTING_GATEWAY
1940 if (OC_GATEWAY == myStackMode)
1942 result = RMInitialize();
1947 if(result != OC_STACK_OK)
1949 OIC_LOG(ERROR, TAG, "Stack initialization error");
1950 deleteAllResources();
1952 stackState = OC_STACK_UNINITIALIZED;
1957 OCStackResult OCStop()
1959 OIC_LOG(INFO, TAG, "Entering OCStop");
1961 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1963 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
1966 else if (stackState != OC_STACK_INITIALIZED)
1968 OIC_LOG(ERROR, TAG, "Stack not initialized");
1969 return OC_STACK_ERROR;
1972 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1974 #ifdef WITH_PRESENCE
1975 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1976 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1977 presenceResource.presenceTTL = 0;
1978 #endif // WITH_PRESENCE
1980 #ifdef ROUTING_GATEWAY
1981 if (OC_GATEWAY == myStackMode)
1987 // Free memory dynamically allocated for resources
1988 deleteAllResources();
1990 DeletePlatformInfo();
1992 // Remove all observers
1993 DeleteObserverList();
1994 // Remove all the client callbacks
1995 DeleteClientCBList();
1997 // De-init the SRM Policy Engine
1998 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
1999 SRMDeInitPolicyEngine();
2002 stackState = OC_STACK_UNINITIALIZED;
2006 OCStackResult OCStartMulticastServer()
2008 if(stackState != OC_STACK_INITIALIZED)
2010 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2011 return OC_STACK_ERROR;
2013 CAResult_t ret = CAStartListeningServer();
2014 if (CA_STATUS_OK != ret)
2016 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2017 return OC_STACK_ERROR;
2022 OCStackResult OCStopMulticastServer()
2024 CAResult_t ret = CAStopListeningServer();
2025 if (CA_STATUS_OK != ret)
2027 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2028 return OC_STACK_ERROR;
2033 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2038 return CA_MSG_CONFIRM;
2043 return CA_MSG_NONCONFIRM;
2047 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
2051 query = strchr (inputUri, '?');
2055 if((query - inputUri) > MAX_URI_LENGTH)
2057 return OC_STACK_INVALID_URI;
2060 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
2062 return OC_STACK_INVALID_QUERY;
2065 else if(uriLen > MAX_URI_LENGTH)
2067 return OC_STACK_INVALID_URI;
2073 * A request uri consists of the following components in order:
2076 * CoAP over UDP prefix "coap://"
2077 * CoAP over TCP prefix "coap+tcp://"
2079 * IPv6 address "[1234::5678]"
2080 * IPv4 address "192.168.1.1"
2081 * optional port ":5683"
2082 * resource uri "/oc/core..."
2084 * for PRESENCE requests, extract resource type.
2086 static OCStackResult ParseRequestUri(const char *fullUri,
2087 OCTransportAdapter adapter,
2088 OCTransportFlags flags,
2089 OCDevAddr **devAddr,
2091 char **resourceType)
2093 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2095 OCStackResult result = OC_STACK_OK;
2096 OCDevAddr *da = NULL;
2100 // provide defaults for all returned values
2107 *resourceUri = NULL;
2111 *resourceType = NULL;
2114 // delimit url prefix, if any
2115 const char *start = fullUri;
2116 char *slash2 = strstr(start, "//");
2121 char *slash = strchr(start, '/');
2124 return OC_STACK_INVALID_URI;
2127 // process url scheme
2128 size_t prefixLen = slash2 - fullUri;
2132 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2138 // TODO: this logic should come in with unit tests exercising the various strings
2139 // processs url prefix, if any
2140 size_t urlLen = slash - start;
2144 if (urlLen && devAddr)
2145 { // construct OCDevAddr
2146 if (start[0] == '[')
2148 char *close = strchr(++start, ']');
2149 if (!close || close > slash)
2151 return OC_STACK_INVALID_URI;
2154 if (close[1] == ':')
2158 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2159 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2163 char *dot = strchr(start, '.');
2164 if (dot && dot < slash)
2166 colon = strchr(start, ':');
2167 end = (colon && colon < slash) ? colon : slash;
2171 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2175 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2176 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2185 if (len >= sizeof(da->addr))
2187 return OC_STACK_INVALID_URI;
2189 // collect port, if any
2190 if (colon && colon < slash)
2192 for (colon++; colon < slash; colon++)
2195 if (c < '0' || c > '9')
2197 return OC_STACK_INVALID_URI;
2199 port = 10 * port + c - '0';
2204 if (len >= sizeof(da->addr))
2206 return OC_STACK_INVALID_URI;
2209 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2212 return OC_STACK_NO_MEMORY;
2214 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2216 da->adapter = adapter;
2218 if (!strncmp(fullUri, "coaps:", 6))
2220 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2225 // process resource uri, if any
2227 { // request uri and query
2228 size_t ulen = strlen(slash); // resource uri length
2229 size_t tlen = 0; // resource type length
2232 static const char strPresence[] = "/oic/ad?rt=";
2233 static const size_t lenPresence = sizeof(strPresence) - 1;
2234 if (!strncmp(slash, strPresence, lenPresence))
2236 type = slash + lenPresence;
2237 tlen = ulen - lenPresence;
2242 *resourceUri = (char *)OICMalloc(ulen + 1);
2245 result = OC_STACK_NO_MEMORY;
2248 strcpy(*resourceUri, slash);
2251 if (type && resourceType)
2253 *resourceType = (char *)OICMalloc(tlen + 1);
2256 result = OC_STACK_NO_MEMORY;
2260 OICStrcpy(*resourceType, (tlen+1), type);
2267 // free all returned values
2274 OICFree(*resourceUri);
2278 OICFree(*resourceType);
2283 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2284 char *resourceUri, char **requestUri)
2286 char uri[CA_MAX_URI_LENGTH];
2288 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2290 *requestUri = OICStrdup(uri);
2293 return OC_STACK_NO_MEMORY;
2300 * Discover or Perform requests on a specified resource
2302 OCStackResult OCDoResource(OCDoHandle *handle,
2304 const char *requestUri,
2305 const OCDevAddr *destination,
2307 OCConnectivityType connectivityType,
2308 OCQualityOfService qos,
2309 OCCallbackData *cbData,
2310 OCHeaderOption *options,
2313 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2315 // Validate input parameters
2316 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2317 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2318 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2320 OCStackResult result = OC_STACK_ERROR;
2321 CAResult_t caResult;
2322 CAToken_t token = NULL;
2323 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2324 ClientCB *clientCB = NULL;
2325 OCDoHandle resHandle = NULL;
2326 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2327 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2329 OCTransportAdapter adapter;
2330 OCTransportFlags flags;
2331 // the request contents are put here
2332 CARequestInfo_t requestInfo = {.method = CA_GET};
2333 // requestUri will be parsed into the following three variables
2334 OCDevAddr *devAddr = NULL;
2335 char *resourceUri = NULL;
2336 char *resourceType = NULL;
2338 // This validation is broken, but doesn't cause harm
2339 size_t uriLen = strlen(requestUri );
2340 if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
2346 * Support original behavior with address on resourceUri argument.
2348 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2349 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2351 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2353 if (result != OC_STACK_OK)
2355 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2362 case OC_REST_OBSERVE:
2363 case OC_REST_OBSERVE_ALL:
2364 case OC_REST_CANCEL_OBSERVE:
2365 requestInfo.method = CA_GET;
2368 requestInfo.method = CA_PUT;
2371 requestInfo.method = CA_POST;
2373 case OC_REST_DELETE:
2374 requestInfo.method = CA_DELETE;
2376 case OC_REST_DISCOVER:
2378 if (destination || devAddr)
2380 requestInfo.isMulticast = false;
2384 tmpDevAddr.adapter = adapter;
2385 tmpDevAddr.flags = flags;
2386 destination = &tmpDevAddr;
2387 requestInfo.isMulticast = true;
2389 // CA_DISCOVER will become GET and isMulticast
2390 requestInfo.method = CA_GET;
2392 #ifdef WITH_PRESENCE
2393 case OC_REST_PRESENCE:
2394 // Replacing method type with GET because "presence"
2395 // is a stack layer only implementation.
2396 requestInfo.method = CA_GET;
2400 result = OC_STACK_INVALID_METHOD;
2404 if (!devAddr && !destination)
2406 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2407 result = OC_STACK_INVALID_PARAM;
2411 /* If not original behavior, use destination argument */
2412 if (destination && !devAddr)
2414 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2417 result = OC_STACK_NO_MEMORY;
2420 *devAddr = *destination;
2423 resHandle = GenerateInvocationHandle();
2426 result = OC_STACK_NO_MEMORY;
2430 caResult = CAGenerateToken(&token, tokenLength);
2431 if (caResult != CA_STATUS_OK)
2433 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2434 result= OC_STACK_ERROR;
2438 // fill in request data
2439 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2440 requestInfo.info.token = token;
2441 requestInfo.info.tokenLength = tokenLength;
2442 requestInfo.info.resourceUri = resourceUri;
2444 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2446 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2447 options, numOptions, OC_OBSERVE_REGISTER);
2448 if (result != OC_STACK_OK)
2452 requestInfo.info.numOptions = numOptions + 1;
2456 requestInfo.info.numOptions = numOptions;
2457 requestInfo.info.options =
2458 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2459 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2460 numOptions * sizeof(CAHeaderOption_t));
2463 CopyDevAddrToEndpoint(devAddr, &endpoint);
2468 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2471 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2474 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2478 requestInfo.info.payload = NULL;
2479 requestInfo.info.payloadSize = 0;
2480 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2483 if (result != OC_STACK_OK)
2485 OIC_LOG(ERROR, TAG, "CACreateEndpoint error");
2489 // prepare for response
2490 #ifdef WITH_PRESENCE
2491 if (method == OC_REST_PRESENCE)
2493 char *presenceUri = NULL;
2494 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2495 if (OC_STACK_OK != result)
2500 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2501 // Presence notification will form a canonical uri to
2502 // look for callbacks into the application.
2503 resourceUri = presenceUri;
2507 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2508 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2509 method, devAddr, resourceUri, resourceType, ttl);
2510 if (OC_STACK_OK != result)
2515 devAddr = NULL; // Client CB list entry now owns it
2516 resourceUri = NULL; // Client CB list entry now owns it
2517 resourceType = NULL; // Client CB list entry now owns it
2520 result = OCSendRequest(&endpoint, &requestInfo);
2521 if (OC_STACK_OK != result)
2528 *handle = resHandle;
2532 if (result != OC_STACK_OK)
2534 OIC_LOG(ERROR, TAG, "OCDoResource error");
2535 FindAndDeleteClientCB(clientCB);
2536 CADestroyToken(token);
2544 // This is the owner of the payload object, so we free it
2545 OCPayloadDestroy(payload);
2546 OICFree(requestInfo.info.payload);
2548 OICFree(resourceUri);
2549 OICFree(resourceType);
2550 OICFree(requestInfo.info.options);
2554 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2558 * This ftn is implemented one of two ways in the case of observation:
2560 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2561 * Remove the callback associated on client side.
2562 * When the next notification comes in from server,
2563 * reply with RESET message to server.
2564 * Keep in mind that the server will react to RESET only
2565 * if the last notification was sent as CON
2567 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2568 * and it is associated with an observe request
2569 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2570 * Send CON Observe request to server with
2571 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2572 * Remove the callback associated on client side.
2574 OCStackResult ret = OC_STACK_OK;
2575 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2576 CARequestInfo_t requestInfo = {.method = CA_GET};
2580 return OC_STACK_INVALID_PARAM;
2583 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2586 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2587 return OC_STACK_ERROR;
2590 switch (clientCB->method)
2592 case OC_REST_OBSERVE:
2593 case OC_REST_OBSERVE_ALL:
2595 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
2596 clientCB->requestUri);
2597 if (qos != OC_HIGH_QOS)
2599 FindAndDeleteClientCB(clientCB);
2603 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2605 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2606 requestInfo.info.token = clientCB->token;
2607 requestInfo.info.tokenLength = clientCB->tokenLength;
2609 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2610 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2612 return OC_STACK_ERROR;
2614 requestInfo.info.numOptions = numOptions + 1;
2615 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2617 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2619 ret = OCSendRequest(&endpoint, &requestInfo);
2621 if (requestInfo.info.options)
2623 OICFree (requestInfo.info.options);
2625 if (requestInfo.info.resourceUri)
2627 OICFree (requestInfo.info.resourceUri);
2632 case OC_REST_DISCOVER:
2633 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2634 clientCB->requestUri);
2635 FindAndDeleteClientCB(clientCB);
2638 #ifdef WITH_PRESENCE
2639 case OC_REST_PRESENCE:
2640 FindAndDeleteClientCB(clientCB);
2645 ret = OC_STACK_INVALID_METHOD;
2653 * @brief Register Persistent storage callback.
2654 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2656 * OC_STACK_OK - No errors; Success
2657 * OC_STACK_INVALID_PARAM - Invalid parameter
2659 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2661 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2662 if(!persistentStorageHandler)
2664 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2665 return OC_STACK_INVALID_PARAM;
2669 if( !persistentStorageHandler->open ||
2670 !persistentStorageHandler->close ||
2671 !persistentStorageHandler->read ||
2672 !persistentStorageHandler->unlink ||
2673 !persistentStorageHandler->write)
2675 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2676 return OC_STACK_INVALID_PARAM;
2679 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2682 #ifdef WITH_PRESENCE
2684 OCStackResult OCProcessPresence()
2686 OCStackResult result = OC_STACK_OK;
2688 // the following line floods the log with messages that are irrelevant
2689 // to most purposes. Uncomment as needed.
2690 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2691 ClientCB* cbNode = NULL;
2692 OCClientResponse clientResponse;
2693 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2695 LL_FOREACH(cbList, cbNode)
2697 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2702 uint32_t now = GetTicks(0);
2703 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2704 cbNode->presence->TTLlevel);
2705 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2707 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2712 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2714 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2715 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2717 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2719 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2721 clientResponse.sequenceNumber = 0;
2722 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2723 clientResponse.devAddr = *cbNode->devAddr;
2724 FixUpClientResponse(&clientResponse);
2725 clientResponse.payload = NULL;
2727 // Increment the TTLLevel (going to a next state), so we don't keep
2728 // sending presence notification to client.
2729 cbNode->presence->TTLlevel++;
2730 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2731 cbNode->presence->TTLlevel);
2733 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2734 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2736 FindAndDeleteClientCB(cbNode);
2740 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2745 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2746 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2747 CARequestInfo_t requestInfo = {.method = CA_GET};
2749 OIC_LOG(DEBUG, TAG, "time to test server presence");
2751 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2753 requestData.type = CA_MSG_NONCONFIRM;
2754 requestData.token = cbNode->token;
2755 requestData.tokenLength = cbNode->tokenLength;
2756 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2757 requestInfo.method = CA_GET;
2758 requestInfo.info = requestData;
2760 result = OCSendRequest(&endpoint, &requestInfo);
2761 if (OC_STACK_OK != result)
2766 cbNode->presence->TTLlevel++;
2767 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2770 if (result != OC_STACK_OK)
2772 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
2777 #endif // WITH_PRESENCE
2779 OCStackResult OCProcess()
2781 #ifdef WITH_PRESENCE
2782 OCProcessPresence();
2784 CAHandleRequestResponse();
2786 #ifdef ROUTING_GATEWAY
2792 #ifdef WITH_PRESENCE
2793 OCStackResult OCStartPresence(const uint32_t ttl)
2795 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2796 OCChangeResourceProperty(
2797 &(((OCResource *)presenceResource.handle)->resourceProperties),
2800 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2802 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2803 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
2807 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2808 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
2812 presenceResource.presenceTTL = ttl;
2814 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
2816 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2818 presenceState = OC_PRESENCE_INITIALIZED;
2820 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2822 CAToken_t caToken = NULL;
2823 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2824 if (caResult != CA_STATUS_OK)
2826 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2827 CADestroyToken(caToken);
2828 return OC_STACK_ERROR;
2831 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2832 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
2833 CADestroyToken(caToken);
2836 // Each time OCStartPresence is called
2837 // a different random 32-bit integer number is used
2838 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2840 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2841 OC_PRESENCE_TRIGGER_CREATE);
2844 OCStackResult OCStopPresence()
2846 OCStackResult result = OC_STACK_ERROR;
2848 if(presenceResource.handle)
2850 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2852 // make resource inactive
2853 result = OCChangeResourceProperty(
2854 &(((OCResource *) presenceResource.handle)->resourceProperties),
2858 if(result != OC_STACK_OK)
2861 "Changing the presence resource properties to ACTIVE not successful");
2865 return SendStopNotification();
2869 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
2870 void* callbackParameter)
2872 defaultDeviceHandler = entityHandler;
2873 defaultDeviceHandlerCallbackParameter = callbackParameter;
2878 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
2880 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
2882 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
2884 if (validatePlatformInfo(platformInfo))
2886 return SavePlatformInfo(platformInfo);
2890 return OC_STACK_INVALID_PARAM;
2895 return OC_STACK_ERROR;
2899 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2901 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
2903 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
2905 OIC_LOG(ERROR, TAG, "Null or empty device name.");
2906 return OC_STACK_INVALID_PARAM;
2909 return SaveDeviceInfo(deviceInfo);
2912 OCStackResult OCCreateResource(OCResourceHandle *handle,
2913 const char *resourceTypeName,
2914 const char *resourceInterfaceName,
2915 const char *uri, OCEntityHandler entityHandler,
2916 void* callbackParam,
2917 uint8_t resourceProperties)
2920 OCResource *pointer = NULL;
2921 OCStackResult result = OC_STACK_ERROR;
2923 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
2925 if(myStackMode == OC_CLIENT)
2927 return OC_STACK_INVALID_PARAM;
2929 // Validate parameters
2930 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2932 OIC_LOG(ERROR, TAG, "URI is empty or too long");
2933 return OC_STACK_INVALID_URI;
2935 // Is it presented during resource discovery?
2936 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
2938 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
2939 return OC_STACK_INVALID_PARAM;
2942 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2944 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2947 // Make sure resourceProperties bitmask has allowed properties specified
2948 if (resourceProperties
2949 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
2950 OC_EXPLICIT_DISCOVERABLE))
2952 OIC_LOG(ERROR, TAG, "Invalid property");
2953 return OC_STACK_INVALID_PARAM;
2956 // If the headResource is NULL, then no resources have been created...
2957 pointer = headResource;
2960 // At least one resources is in the resource list, so we need to search for
2961 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2964 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
2966 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
2967 return OC_STACK_INVALID_PARAM;
2969 pointer = pointer->next;
2972 // Create the pointer and insert it into the resource list
2973 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
2976 result = OC_STACK_NO_MEMORY;
2979 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2981 insertResource(pointer);
2984 pointer->uri = OICStrdup(uri);
2987 result = OC_STACK_NO_MEMORY;
2991 // Set properties. Set OC_ACTIVE
2992 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2995 // Add the resourcetype to the resource
2996 result = BindResourceTypeToResource(pointer, resourceTypeName);
2997 if (result != OC_STACK_OK)
2999 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3003 // Add the resourceinterface to the resource
3004 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3005 if (result != OC_STACK_OK)
3007 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3011 // If an entity handler has been passed, attach it to the newly created
3012 // resource. Otherwise, set the default entity handler.
3015 pointer->entityHandler = entityHandler;
3016 pointer->entityHandlerCallbackParam = callbackParam;
3020 pointer->entityHandler = defaultResourceEHandler;
3021 pointer->entityHandlerCallbackParam = NULL;
3025 result = OC_STACK_OK;
3027 #ifdef WITH_PRESENCE
3028 if (presenceResource.handle)
3030 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3031 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3035 if (result != OC_STACK_OK)
3037 // Deep delete of resource and other dynamic elements that it contains
3038 deleteResource(pointer);
3044 OCStackResult OCBindResource(
3045 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3047 OCResource *resource = NULL;
3050 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3052 // Validate parameters
3053 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3054 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3055 // Container cannot contain itself
3056 if (collectionHandle == resourceHandle)
3058 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3059 return OC_STACK_INVALID_PARAM;
3062 // Use the handle to find the resource in the resource linked list
3063 resource = findResource((OCResource *) collectionHandle);
3066 OIC_LOG(ERROR, TAG, "Collection handle not found");
3067 return OC_STACK_INVALID_PARAM;
3070 // Look for an open slot to add add the child resource.
3071 // If found, add it and return success
3072 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
3074 if (!resource->rsrcResources[i])
3076 resource->rsrcResources[i] = (OCResource *) resourceHandle;
3077 OIC_LOG(INFO, TAG, "resource bound");
3079 #ifdef WITH_PRESENCE
3080 if (presenceResource.handle)
3082 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3083 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3084 OC_PRESENCE_TRIGGER_CHANGE);
3092 // Unable to add resourceHandle, so return error
3093 return OC_STACK_ERROR;
3096 OCStackResult OCUnBindResource(
3097 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3099 OCResource *resource = NULL;
3102 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3104 // Validate parameters
3105 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3106 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3107 // Container cannot contain itself
3108 if (collectionHandle == resourceHandle)
3110 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3111 return OC_STACK_INVALID_PARAM;
3114 // Use the handle to find the resource in the resource linked list
3115 resource = findResource((OCResource *) collectionHandle);
3118 OIC_LOG(ERROR, TAG, "Collection handle not found");
3119 return OC_STACK_INVALID_PARAM;
3122 // Look for an open slot to add add the child resource.
3123 // If found, add it and return success
3124 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
3126 if (resourceHandle == resource->rsrcResources[i])
3128 resource->rsrcResources[i] = (OCResource *) NULL;
3129 OIC_LOG(INFO, TAG, "resource unbound");
3131 // Send notification when resource is unbounded successfully.
3132 #ifdef WITH_PRESENCE
3133 if (presenceResource.handle)
3135 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3136 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3137 OC_PRESENCE_TRIGGER_CHANGE);
3144 OIC_LOG(INFO, TAG, "resource not found in collection");
3146 // Unable to add resourceHandle, so return error
3147 return OC_STACK_ERROR;
3150 // Precondition is that the parameter has been checked to not equal NULL.
3151 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3153 if (resourceItemName[0] < 'a' || resourceItemName[0] > 'z')
3159 while (resourceItemName[index] != '\0')
3161 if (resourceItemName[index] != '.' &&
3162 resourceItemName[index] != '-' &&
3163 (resourceItemName[index] < 'a' || resourceItemName[index] > 'z') &&
3164 (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3173 OCStackResult BindResourceTypeToResource(OCResource* resource,
3174 const char *resourceTypeName)
3176 OCResourceType *pointer = NULL;
3178 OCStackResult result = OC_STACK_ERROR;
3180 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3182 if (!ValidateResourceTypeInterface(resourceTypeName))
3184 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3185 return OC_STACK_INVALID_PARAM;
3188 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3191 result = OC_STACK_NO_MEMORY;
3195 str = OICStrdup(resourceTypeName);
3198 result = OC_STACK_NO_MEMORY;
3201 pointer->resourcetypename = str;
3203 insertResourceType(resource, pointer);
3204 result = OC_STACK_OK;
3207 if (result != OC_STACK_OK)
3216 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3217 const char *resourceInterfaceName)
3219 OCResourceInterface *pointer = NULL;
3221 OCStackResult result = OC_STACK_ERROR;
3223 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3225 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3227 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3228 return OC_STACK_INVALID_PARAM;
3231 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3233 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3236 result = OC_STACK_NO_MEMORY;
3240 str = OICStrdup(resourceInterfaceName);
3243 result = OC_STACK_NO_MEMORY;
3246 pointer->name = str;
3248 // Bind the resourceinterface to the resource
3249 insertResourceInterface(resource, pointer);
3251 result = OC_STACK_OK;
3254 if (result != OC_STACK_OK)
3263 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3264 const char *resourceTypeName)
3267 OCStackResult result = OC_STACK_ERROR;
3268 OCResource *resource = NULL;
3270 resource = findResource((OCResource *) handle);
3273 OIC_LOG(ERROR, TAG, "Resource not found");
3274 return OC_STACK_ERROR;
3277 result = BindResourceTypeToResource(resource, resourceTypeName);
3279 #ifdef WITH_PRESENCE
3280 if(presenceResource.handle)
3282 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3283 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3290 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3291 const char *resourceInterfaceName)
3294 OCStackResult result = OC_STACK_ERROR;
3295 OCResource *resource = NULL;
3297 resource = findResource((OCResource *) handle);
3300 OIC_LOG(ERROR, TAG, "Resource not found");
3301 return OC_STACK_ERROR;
3304 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3306 #ifdef WITH_PRESENCE
3307 if (presenceResource.handle)
3309 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3310 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3317 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3319 OCResource *pointer = headResource;
3321 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3325 *numResources = *numResources + 1;
3326 pointer = pointer->next;
3331 OCResourceHandle OCGetResourceHandle(uint8_t index)
3333 OCResource *pointer = headResource;
3335 for( uint8_t i = 0; i < index && pointer; ++i)
3337 pointer = pointer->next;
3339 return (OCResourceHandle) pointer;
3342 OCStackResult OCDeleteResource(OCResourceHandle handle)
3346 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3347 return OC_STACK_INVALID_PARAM;
3350 OCResource *resource = findResource((OCResource *) handle);
3351 if (resource == NULL)
3353 OIC_LOG(ERROR, TAG, "Resource not found");
3354 return OC_STACK_NO_RESOURCE;
3357 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3359 OIC_LOG(ERROR, TAG, "Error deleting resource");
3360 return OC_STACK_ERROR;
3366 const char *OCGetResourceUri(OCResourceHandle handle)
3368 OCResource *resource = NULL;
3370 resource = findResource((OCResource *) handle);
3373 return resource->uri;
3375 return (const char *) NULL;
3378 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3380 OCResource *resource = NULL;
3382 resource = findResource((OCResource *) handle);
3385 return resource->resourceProperties;
3387 return (OCResourceProperty)-1;
3390 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3391 uint8_t *numResourceTypes)
3393 OCResource *resource = NULL;
3394 OCResourceType *pointer = NULL;
3396 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3397 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3399 *numResourceTypes = 0;
3401 resource = findResource((OCResource *) handle);
3404 pointer = resource->rsrcType;
3407 *numResourceTypes = *numResourceTypes + 1;
3408 pointer = pointer->next;
3414 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3416 OCResourceType *resourceType = NULL;
3418 resourceType = findResourceTypeAtIndex(handle, index);
3421 return resourceType->resourcetypename;
3423 return (const char *) NULL;
3426 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3427 uint8_t *numResourceInterfaces)
3429 OCResourceInterface *pointer = NULL;
3430 OCResource *resource = NULL;
3432 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3433 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3435 *numResourceInterfaces = 0;
3436 resource = findResource((OCResource *) handle);
3439 pointer = resource->rsrcInterface;
3442 *numResourceInterfaces = *numResourceInterfaces + 1;
3443 pointer = pointer->next;
3449 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3451 OCResourceInterface *resourceInterface = NULL;
3453 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3454 if (resourceInterface)
3456 return resourceInterface->name;
3458 return (const char *) NULL;
3461 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3464 OCResource *resource = NULL;
3466 if (index >= MAX_CONTAINED_RESOURCES)
3471 resource = findResource((OCResource *) collectionHandle);
3477 return resource->rsrcResources[index];
3480 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3481 OCEntityHandler entityHandler,
3482 void* callbackParam)
3484 OCResource *resource = NULL;
3486 // Validate parameters
3487 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3489 // Use the handle to find the resource in the resource linked list
3490 resource = findResource((OCResource *)handle);
3493 OIC_LOG(ERROR, TAG, "Resource not found");
3494 return OC_STACK_ERROR;
3498 resource->entityHandler = entityHandler;
3499 resource->entityHandlerCallbackParam = callbackParam;
3501 #ifdef WITH_PRESENCE
3502 if (presenceResource.handle)
3504 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3505 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3512 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3514 OCResource *resource = NULL;
3516 resource = findResource((OCResource *)handle);
3519 OIC_LOG(ERROR, TAG, "Resource not found");
3524 return resource->entityHandler;
3527 void incrementSequenceNumber(OCResource * resPtr)
3529 // Increment the sequence number
3530 resPtr->sequenceNum += 1;
3531 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3533 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3538 #ifdef WITH_PRESENCE
3539 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3540 OCPresenceTrigger trigger)
3542 OCResource *resPtr = NULL;
3543 OCStackResult result = OC_STACK_ERROR;
3544 OCMethod method = OC_REST_PRESENCE;
3545 uint32_t maxAge = 0;
3546 resPtr = findResource((OCResource *) presenceResource.handle);
3549 return OC_STACK_NO_RESOURCE;
3552 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3554 maxAge = presenceResource.presenceTTL;
3556 result = SendAllObserverNotification(method, resPtr, maxAge,
3557 trigger, resourceType, OC_LOW_QOS);
3563 OCStackResult SendStopNotification()
3565 OCResource *resPtr = NULL;
3566 OCStackResult result = OC_STACK_ERROR;
3567 OCMethod method = OC_REST_PRESENCE;
3568 resPtr = findResource((OCResource *) presenceResource.handle);
3571 return OC_STACK_NO_RESOURCE;
3574 // maxAge is 0. ResourceType is NULL.
3575 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3581 #endif // WITH_PRESENCE
3582 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3584 OCResource *resPtr = NULL;
3585 OCStackResult result = OC_STACK_ERROR;
3586 OCMethod method = OC_REST_NOMETHOD;
3587 uint32_t maxAge = 0;
3589 OIC_LOG(INFO, TAG, "Notifying all observers");
3590 #ifdef WITH_PRESENCE
3591 if(handle == presenceResource.handle)
3595 #endif // WITH_PRESENCE
3596 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3598 // Verify that the resource exists
3599 resPtr = findResource ((OCResource *) handle);
3602 return OC_STACK_NO_RESOURCE;
3606 //only increment in the case of regular observing (not presence)
3607 incrementSequenceNumber(resPtr);
3608 method = OC_REST_OBSERVE;
3609 maxAge = MAX_OBSERVE_AGE;
3610 #ifdef WITH_PRESENCE
3611 result = SendAllObserverNotification (method, resPtr, maxAge,
3612 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3614 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3621 OCNotifyListOfObservers (OCResourceHandle handle,
3622 OCObservationId *obsIdList,
3623 uint8_t numberOfIds,
3624 const OCRepPayload *payload,
3625 OCQualityOfService qos)
3627 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3629 OCResource *resPtr = NULL;
3630 //TODO: we should allow the server to define this
3631 uint32_t maxAge = MAX_OBSERVE_AGE;
3633 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3634 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3635 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3637 resPtr = findResource ((OCResource *) handle);
3638 if (NULL == resPtr || myStackMode == OC_CLIENT)
3640 return OC_STACK_NO_RESOURCE;
3644 incrementSequenceNumber(resPtr);
3646 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3647 payload, maxAge, qos));
3650 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3652 OCStackResult result = OC_STACK_ERROR;
3653 OCServerRequest *serverRequest = NULL;
3655 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
3657 // Validate input parameters
3658 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3659 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3662 // Get pointer to request info
3663 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3666 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3667 result = serverRequest->ehResponseHandler(ehResponse);
3673 //-----------------------------------------------------------------------------
3674 // Private internal function definitions
3675 //-----------------------------------------------------------------------------
3676 static OCDoHandle GenerateInvocationHandle()
3678 OCDoHandle handle = NULL;
3679 // Generate token here, it will be deleted when the transaction is deleted
3680 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3683 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3689 #ifdef WITH_PRESENCE
3690 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3691 OCResourceProperty resourceProperties, uint8_t enable)
3695 return OC_STACK_INVALID_PARAM;
3697 if (resourceProperties
3698 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3700 OIC_LOG(ERROR, TAG, "Invalid property");
3701 return OC_STACK_INVALID_PARAM;
3705 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3709 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3715 OCStackResult initResources()
3717 OCStackResult result = OC_STACK_OK;
3719 headResource = NULL;
3720 tailResource = NULL;
3721 // Init Virtual Resources
3722 #ifdef WITH_PRESENCE
3723 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3725 result = OCCreateResource(&presenceResource.handle,
3726 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3728 OC_RSRVD_PRESENCE_URI,
3732 //make resource inactive
3733 result = OCChangeResourceProperty(
3734 &(((OCResource *) presenceResource.handle)->resourceProperties),
3737 #ifndef WITH_ARDUINO
3738 if (result == OC_STACK_OK)
3740 result = SRMInitSecureResources();
3744 if(result == OC_STACK_OK)
3746 result = OCCreateResource(&deviceResource,
3747 OC_RSRVD_RESOURCE_TYPE_DEVICE,
3748 OC_RSRVD_INTERFACE_DEFAULT,
3749 OC_RSRVD_DEVICE_URI,
3753 if(result == OC_STACK_OK)
3755 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
3756 OC_RSRVD_INTERFACE_READ);
3760 if(result == OC_STACK_OK)
3762 result = OCCreateResource(&platformResource,
3763 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
3764 OC_RSRVD_INTERFACE_DEFAULT,
3765 OC_RSRVD_PLATFORM_URI,
3769 if(result == OC_STACK_OK)
3771 result = BindResourceInterfaceToResource((OCResource *)platformResource,
3772 OC_RSRVD_INTERFACE_READ);
3779 void insertResource(OCResource *resource)
3783 headResource = resource;
3784 tailResource = resource;
3788 tailResource->next = resource;
3789 tailResource = resource;
3791 resource->next = NULL;
3794 OCResource *findResource(OCResource *resource)
3796 OCResource *pointer = headResource;
3800 if (pointer == resource)
3804 pointer = pointer->next;
3809 void deleteAllResources()
3811 OCResource *pointer = headResource;
3812 OCResource *temp = NULL;
3816 temp = pointer->next;
3817 #ifdef WITH_PRESENCE
3818 if (pointer != (OCResource *) presenceResource.handle)
3820 #endif // WITH_PRESENCE
3821 deleteResource(pointer);
3822 #ifdef WITH_PRESENCE
3824 #endif // WITH_PRESENCE
3828 SRMDeInitSecureResources();
3830 #ifdef WITH_PRESENCE
3831 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3832 // presence notification attributed to their deletion to be processed.
3833 deleteResource((OCResource *) presenceResource.handle);
3834 #endif // WITH_PRESENCE
3837 OCStackResult deleteResource(OCResource *resource)
3839 OCResource *prev = NULL;
3840 OCResource *temp = NULL;
3843 OIC_LOG(DEBUG,TAG,"resource is NULL");
3844 return OC_STACK_INVALID_PARAM;
3847 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
3849 temp = headResource;
3852 if (temp == resource)
3854 // Invalidate all Resource Properties.
3855 resource->resourceProperties = (OCResourceProperty) 0;
3856 #ifdef WITH_PRESENCE
3857 if(resource != (OCResource *) presenceResource.handle)
3859 #endif // WITH_PRESENCE
3860 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3861 #ifdef WITH_PRESENCE
3864 if(presenceResource.handle)
3866 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3867 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
3870 // Only resource in list.
3871 if (temp == headResource && temp == tailResource)
3873 headResource = NULL;
3874 tailResource = NULL;
3877 else if (temp == headResource)
3879 headResource = temp->next;
3882 else if (temp == tailResource)
3884 tailResource = prev;
3885 tailResource->next = NULL;
3889 prev->next = temp->next;
3892 deleteResourceElements(temp);
3903 return OC_STACK_ERROR;
3906 void deleteResourceElements(OCResource *resource)
3913 OICFree(resource->uri);
3914 deleteResourceType(resource->rsrcType);
3915 deleteResourceInterface(resource->rsrcInterface);
3918 void deleteResourceType(OCResourceType *resourceType)
3920 OCResourceType *pointer = resourceType;
3921 OCResourceType *next = NULL;
3925 next = pointer->next;
3926 OICFree(pointer->resourcetypename);
3932 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3934 OCResourceInterface *pointer = resourceInterface;
3935 OCResourceInterface *next = NULL;
3939 next = pointer->next;
3940 OICFree(pointer->name);
3946 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3948 OCResourceType *pointer = NULL;
3949 OCResourceType *previous = NULL;
3950 if (!resource || !resourceType)
3954 // resource type list is empty.
3955 else if (!resource->rsrcType)
3957 resource->rsrcType = resourceType;
3961 pointer = resource->rsrcType;
3965 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
3967 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
3968 OICFree(resourceType->resourcetypename);
3969 OICFree(resourceType);
3973 pointer = pointer->next;
3975 previous->next = resourceType;
3977 resourceType->next = NULL;
3979 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
3982 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3984 OCResource *resource = NULL;
3985 OCResourceType *pointer = NULL;
3987 // Find the specified resource
3988 resource = findResource((OCResource *) handle);
3994 // Make sure a resource has a resourcetype
3995 if (!resource->rsrcType)
4000 // Iterate through the list
4001 pointer = resource->rsrcType;
4002 for(uint8_t i = 0; i< index && pointer; ++i)
4004 pointer = pointer->next;
4009 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4011 if(resourceTypeList && resourceTypeName)
4013 OCResourceType * rtPointer = resourceTypeList;
4014 while(resourceTypeName && rtPointer)
4016 if(rtPointer->resourcetypename &&
4017 strcmp(resourceTypeName, (const char *)
4018 (rtPointer->resourcetypename)) == 0)
4022 rtPointer = rtPointer->next;
4030 * Insert a new interface into interface linked list only if not already present.
4031 * If alredy present, 2nd arg is free'd.
4032 * Default interface will always be first if present.
4034 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4036 OCResourceInterface *pointer = NULL;
4037 OCResourceInterface *previous = NULL;
4039 newInterface->next = NULL;
4041 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4043 if (!*firstInterface)
4045 *firstInterface = newInterface;
4047 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4049 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4051 OICFree(newInterface->name);
4052 OICFree(newInterface);
4057 newInterface->next = *firstInterface;
4058 *firstInterface = newInterface;
4063 pointer = *firstInterface;
4066 if (strcmp(newInterface->name, pointer->name) == 0)
4068 OICFree(newInterface->name);
4069 OICFree(newInterface);
4073 pointer = pointer->next;
4075 previous->next = newInterface;
4079 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4082 OCResource *resource = NULL;
4083 OCResourceInterface *pointer = NULL;
4085 // Find the specified resource
4086 resource = findResource((OCResource *) handle);
4092 // Make sure a resource has a resourceinterface
4093 if (!resource->rsrcInterface)
4098 // Iterate through the list
4099 pointer = resource->rsrcInterface;
4101 for (uint8_t i = 0; i < index && pointer; ++i)
4103 pointer = pointer->next;
4109 * This function splits the uri using the '?' delimiter.
4110 * "uriWithoutQuery" is the block of characters between the beginning
4111 * till the delimiter or '\0' which ever comes first.
4112 * "query" is whatever is to the right of the delimiter if present.
4113 * No delimiter sets the query to NULL.
4114 * If either are present, they will be malloc'ed into the params 2, 3.
4115 * The first param, *uri is left untouched.
4117 * NOTE: This function does not account for whitespace at the end of the uri NOR
4118 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4119 * part of the query.
4121 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4125 return OC_STACK_INVALID_URI;
4127 if(!query || !uriWithoutQuery)
4129 return OC_STACK_INVALID_PARAM;
4133 *uriWithoutQuery = NULL;
4135 size_t uriWithoutQueryLen = 0;
4136 size_t queryLen = 0;
4137 size_t uriLen = strlen(uri);
4139 char *pointerToDelimiter = strstr(uri, "?");
4141 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4142 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4144 if (uriWithoutQueryLen)
4146 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4147 if (!*uriWithoutQuery)
4151 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4155 *query = (char *) OICCalloc(queryLen + 1, 1);
4158 OICFree(*uriWithoutQuery);
4159 *uriWithoutQuery = NULL;
4162 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4168 return OC_STACK_NO_MEMORY;
4171 const OicUuid_t* OCGetServerInstanceID(void)
4173 static bool generated = false;
4174 static OicUuid_t sid;
4180 if (GetDoxmDeviceID(&sid) != OC_STACK_OK)
4182 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4189 const char* OCGetServerInstanceIDString(void)
4191 static bool generated = false;
4192 static char sidStr[UUID_STRING_SIZE];
4199 const OicUuid_t* sid = OCGetServerInstanceID();
4201 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4203 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4211 CAResult_t OCSelectNetwork()
4213 CAResult_t retResult = CA_STATUS_FAILED;
4214 CAResult_t caResult = CA_STATUS_OK;
4216 CATransportAdapter_t connTypes[] = {
4218 CA_ADAPTER_RFCOMM_BTEDR,
4219 CA_ADAPTER_GATT_BTLE
4222 ,CA_ADAPTER_REMOTE_ACCESS
4229 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4231 for(int i = 0; i<numConnTypes; i++)
4233 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4234 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4236 caResult = CASelectNetwork(connTypes[i]);
4237 if(caResult == CA_STATUS_OK)
4239 retResult = CA_STATUS_OK;
4244 if(retResult != CA_STATUS_OK)
4246 return caResult; // Returns error of appropriate transport that failed fatally.
4252 OCStackResult CAResultToOCResult(CAResult_t caResult)
4258 case CA_STATUS_INVALID_PARAM:
4259 return OC_STACK_INVALID_PARAM;
4260 case CA_ADAPTER_NOT_ENABLED:
4261 return OC_STACK_ADAPTER_NOT_ENABLED;
4262 case CA_SERVER_STARTED_ALREADY:
4264 case CA_SERVER_NOT_STARTED:
4265 return OC_STACK_ERROR;
4266 case CA_DESTINATION_NOT_REACHABLE:
4267 return OC_STACK_COMM_ERROR;
4268 case CA_SOCKET_OPERATION_FAILED:
4269 return OC_STACK_COMM_ERROR;
4270 case CA_SEND_FAILED:
4271 return OC_STACK_COMM_ERROR;
4272 case CA_RECEIVE_FAILED:
4273 return OC_STACK_COMM_ERROR;
4274 case CA_MEMORY_ALLOC_FAILED:
4275 return OC_STACK_NO_MEMORY;
4276 case CA_REQUEST_TIMEOUT:
4277 return OC_STACK_TIMEOUT;
4278 case CA_DESTINATION_DISCONNECTED:
4279 return OC_STACK_COMM_ERROR;
4280 case CA_STATUS_FAILED:
4281 return OC_STACK_ERROR;
4282 case CA_NOT_SUPPORTED:
4283 return OC_STACK_NOTIMPL;
4285 return OC_STACK_ERROR;