1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //-----------------------------------------------------------------------------
24 //-----------------------------------------------------------------------------
26 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
27 // causes header files to expose definitions
28 // corresponding to the POSIX.1-2001 base
29 // specification (excluding the XSI extension).
30 // For POSIX.1-2001 base specification,
31 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
32 #define _POSIX_C_SOURCE 200112L
33 #ifndef __STDC_FORMAT_MACROS
34 #define __STDC_FORMAT_MACROS
36 #ifndef __STDC_LIMIT_MACROS
37 #define __STDC_LIMIT_MACROS
44 #include "ocstackinternal.h"
45 #include "ocresourcehandler.h"
46 #include "occlientcb.h"
47 #include "ocobserve.h"
49 #include "oic_malloc.h"
50 #include "oic_string.h"
52 #include "ocserverrequest.h"
53 #include "secureresourcemanager.h"
54 #include "doxmresource.h"
56 #include "cainterface.h"
57 #include "ocpayload.h"
58 #include "ocpayloadcbor.h"
60 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
61 #include "routingutility.h"
62 #ifdef ROUTING_GATEWAY
63 #include "routingmanager.h"
68 #include "oickeepalive.h"
71 //#ifdef DIRECT_PAIRING
72 #include "directpairing.h"
80 #include "coap_time.h"
85 #include <arpa/inet.h>
89 #define UINT32_MAX (0xFFFFFFFFUL)
92 //-----------------------------------------------------------------------------
94 //-----------------------------------------------------------------------------
97 OC_STACK_UNINITIALIZED = 0,
99 OC_STACK_UNINIT_IN_PROGRESS
105 OC_PRESENCE_UNINITIALIZED = 0,
106 OC_PRESENCE_INITIALIZED
110 //-----------------------------------------------------------------------------
112 //-----------------------------------------------------------------------------
113 static OCStackState stackState = OC_STACK_UNINITIALIZED;
115 OCResource *headResource = NULL;
116 static OCResource *tailResource = NULL;
117 static OCResourceHandle platformResource = {0};
118 static OCResourceHandle deviceResource = {0};
120 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
121 static PresenceResource presenceResource;
122 static uint8_t PresenceTimeOutSize = 0;
123 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
126 static OCMode myStackMode;
128 //TODO: revisit this design
129 static bool gRASetInfo = false;
131 OCDeviceEntityHandler defaultDeviceHandler;
132 void* defaultDeviceHandlerCallbackParameter = NULL;
133 static const char COAP_TCP[] = "coap+tcp:";
134 static const char CORESPEC[] = "core";
136 //-----------------------------------------------------------------------------
138 //-----------------------------------------------------------------------------
139 #define TAG "OIC_RI_STACK"
140 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
141 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
142 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
143 TAG, #arg " is NULL"); return (retVal); } }
144 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
145 TAG, #arg " is NULL"); return; } }
146 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
149 //TODO: we should allow the server to define this
150 #define MAX_OBSERVE_AGE (0x2FFFFUL)
152 #define MILLISECONDS_PER_SECOND (1000)
154 //-----------------------------------------------------------------------------
155 // Private internal function prototypes
156 //-----------------------------------------------------------------------------
159 * Generate handle of OCDoResource invocation for callback management.
161 * @return Generated OCDoResource handle.
163 static OCDoHandle GenerateInvocationHandle();
166 * Initialize resource data structures, variables, etc.
168 * @return ::OC_STACK_OK on success, some other value upon failure.
170 static OCStackResult initResources();
173 * Add a resource to the end of the linked list of resources.
175 * @param resource Resource to be added
177 static void insertResource(OCResource *resource);
180 * Find a resource in the linked list of resources.
182 * @param resource Resource to be found.
183 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
186 static OCResource *findResource(OCResource *resource);
189 * Insert a resource type into a resource's resource type linked list.
190 * If resource type already exists, it will not be inserted and the
191 * resourceType will be free'd.
192 * resourceType->next should be null to avoid memory leaks.
193 * Function returns silently for null args.
195 * @param resource Resource where resource type is to be inserted.
196 * @param resourceType Resource type to be inserted.
198 static void insertResourceType(OCResource *resource,
199 OCResourceType *resourceType);
202 * Get a resource type at the specified index within a resource.
204 * @param handle Handle of resource.
205 * @param index Index of resource type.
207 * @return Pointer to resource type if found, NULL otherwise.
209 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
213 * Insert a resource interface into a resource's resource interface linked list.
214 * If resource interface already exists, it will not be inserted and the
215 * resourceInterface will be free'd.
216 * resourceInterface->next should be null to avoid memory leaks.
218 * @param resource Resource where resource interface is to be inserted.
219 * @param resourceInterface Resource interface to be inserted.
221 static void insertResourceInterface(OCResource *resource,
222 OCResourceInterface *resourceInterface);
225 * Get a resource interface at the specified index within a resource.
227 * @param handle Handle of resource.
228 * @param index Index of resource interface.
230 * @return Pointer to resource interface if found, NULL otherwise.
232 static OCResourceInterface *findResourceInterfaceAtIndex(
233 OCResourceHandle handle, uint8_t index);
236 * Delete all of the dynamically allocated elements that were created for the resource type.
238 * @param resourceType Specified resource type.
240 static void deleteResourceType(OCResourceType *resourceType);
243 * Delete all of the dynamically allocated elements that were created for the resource interface.
245 * @param resourceInterface Specified resource interface.
247 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
250 * Delete all of the dynamically allocated elements that were created for the resource.
252 * @param resource Specified resource.
254 static void deleteResourceElements(OCResource *resource);
257 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
260 * @param handle Handle of resource to be deleted.
262 * @return ::OC_STACK_OK on success, some other value upon failure.
264 static OCStackResult deleteResource(OCResource *resource);
267 * Delete all of the resources in the resource list.
269 static void deleteAllResources();
272 * Increment resource sequence number. Handles rollover.
274 * @param resPtr Pointer to resource.
276 static void incrementSequenceNumber(OCResource * resPtr);
279 * Attempts to initialize every network interface that the CA Layer might have compiled in.
281 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
282 * return something other than @ref CA_STATUS_OK, then this function fails.
284 * @return ::CA_STATUS_OK on success, some other value upon failure.
286 static CAResult_t OCSelectNetwork();
289 * Get the CoAP ticks after the specified number of milli-seconds.
291 * @param afterMilliSeconds Milli-seconds.
295 static uint32_t GetTicks(uint32_t afterMilliSeconds);
298 * Convert CAResult_t to OCStackResult.
300 * @param caResult CAResult_t code.
301 * @return ::OC_STACK_OK on success, some other value upon failure.
303 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
306 * Convert CAResponseResult_t to OCStackResult.
308 * @param caCode CAResponseResult_t code.
309 * @return ::OC_STACK_OK on success, some other value upon failure.
311 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
314 * Convert OCStackResult to CAResponseResult_t.
316 * @param caCode OCStackResult code.
317 * @param method OCMethod method the return code replies to.
318 * @return ::CA_CONTENT on OK, some other value upon failure.
320 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
323 * Convert OCTransportFlags_t to CATransportModifiers_t.
325 * @param ocConType OCTransportFlags_t input.
326 * @return CATransportFlags
328 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
331 * Convert CATransportFlags_t to OCTransportModifiers_t.
333 * @param caConType CATransportFlags_t input.
334 * @return OCTransportFlags
336 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
339 * Handle response from presence request.
341 * @param endPoint CA remote endpoint.
342 * @param responseInfo CA response info.
343 * @return ::OC_STACK_OK on success, some other value upon failure.
345 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
346 const CAResponseInfo_t *responseInfo);
349 * This function will be called back by CA layer when a response is received.
351 * @param endPoint CA remote endpoint.
352 * @param responseInfo CA response info.
354 static void HandleCAResponses(const CAEndpoint_t* endPoint,
355 const CAResponseInfo_t* responseInfo);
358 * This function will be called back by CA layer when a request is received.
360 * @param endPoint CA remote endpoint.
361 * @param requestInfo CA request info.
363 static void HandleCARequests(const CAEndpoint_t* endPoint,
364 const CARequestInfo_t* requestInfo);
367 * Extract query from a URI.
369 * @param uri Full URI with query.
370 * @param query Pointer to string that will contain query.
371 * @param newURI Pointer to string that will contain URI.
372 * @return ::OC_STACK_OK on success, some other value upon failure.
374 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
377 * Finds a resource type in an OCResourceType link-list.
379 * @param resourceTypeList The link-list to be searched through.
380 * @param resourceTypeName The key to search for.
382 * @return Resource type that matches the key (ie. resourceTypeName) or
383 * NULL if there is either an invalid parameter or this function was unable to find the key.
385 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
386 const char * resourceTypeName);
389 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
390 * TTL will be set to maxAge.
392 * @param cbNode Callback Node for which presence ttl is to be reset.
393 * @param maxAge New value of ttl in seconds.
395 * @return ::OC_STACK_OK on success, some other value upon failure.
397 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
400 * Ensure the accept header option is set appropriatly before sending the requests and routing
401 * header option is updated with destination.
403 * @param object CA remote endpoint.
404 * @param requestInfo CA request info.
406 * @return ::OC_STACK_OK on success, some other value upon failure.
408 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
410 //-----------------------------------------------------------------------------
411 // Internal functions
412 //-----------------------------------------------------------------------------
414 uint32_t GetTicks(uint32_t afterMilliSeconds)
419 // Guard against overflow of uint32_t
420 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
421 COAP_TICKS_PER_SECOND)
423 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
431 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
433 VERIFY_NON_NULL_NR(in, FATAL);
434 VERIFY_NON_NULL_NR(out, FATAL);
436 out->adapter = (OCTransportAdapter)in->adapter;
437 out->flags = CAToOCTransportFlags(in->flags);
438 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
439 out->port = in->port;
440 out->interface = in->interface;
441 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
442 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
446 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
448 VERIFY_NON_NULL_NR(in, FATAL);
449 VERIFY_NON_NULL_NR(out, FATAL);
451 out->adapter = (CATransportAdapter_t)in->adapter;
452 out->flags = OCToCATransportFlags(in->flags);
453 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
454 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
455 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
457 out->port = in->port;
458 out->interface = in->interface;
461 void FixUpClientResponse(OCClientResponse *cr)
463 VERIFY_NON_NULL_NR(cr, FATAL);
465 cr->addr = &cr->devAddr;
466 cr->connType = (OCConnectivityType)
467 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
470 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
472 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
473 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
475 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
476 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
477 if (OC_STACK_OK != rmResult)
479 OIC_LOG(ERROR, TAG, "Add destination option failed");
484 // OC stack prefer CBOR encoded payloads.
485 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
486 CAResult_t result = CASendRequest(object, requestInfo);
487 if(CA_STATUS_OK != result)
489 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
490 return CAResultToOCResult(result);
494 //-----------------------------------------------------------------------------
495 // Internal API function
496 //-----------------------------------------------------------------------------
498 // This internal function is called to update the stack with the status of
499 // observers and communication failures
500 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
502 OCStackResult result = OC_STACK_ERROR;
503 ResourceObserver * observer = NULL;
504 OCEntityHandlerRequest ehRequest = {0};
508 case OC_OBSERVER_NOT_INTERESTED:
509 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
510 observer = GetObserverUsingToken (token, tokenLength);
513 result = FormOCEntityHandlerRequest(&ehRequest,
514 (OCRequestHandle)NULL,
517 (OCResourceHandle)NULL,
518 NULL, PAYLOAD_TYPE_REPRESENTATION,
520 OC_OBSERVE_DEREGISTER,
523 if(result != OC_STACK_OK)
527 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
528 observer->resource->entityHandlerCallbackParam);
531 result = DeleteObserverUsingToken (token, tokenLength);
532 if(result == OC_STACK_OK)
534 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
538 result = OC_STACK_OK;
539 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
543 case OC_OBSERVER_STILL_INTERESTED:
544 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
545 observer = GetObserverUsingToken (token, tokenLength);
548 observer->forceHighQos = 0;
549 observer->failedCommCount = 0;
550 result = OC_STACK_OK;
554 result = OC_STACK_OBSERVER_NOT_FOUND;
558 case OC_OBSERVER_FAILED_COMM:
559 OIC_LOG(DEBUG, TAG, "observer is unreachable");
560 observer = GetObserverUsingToken (token, tokenLength);
563 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
565 result = FormOCEntityHandlerRequest(&ehRequest,
566 (OCRequestHandle)NULL,
569 (OCResourceHandle)NULL,
570 NULL, PAYLOAD_TYPE_REPRESENTATION,
572 OC_OBSERVE_DEREGISTER,
575 if(result != OC_STACK_OK)
577 return OC_STACK_ERROR;
579 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
580 observer->resource->entityHandlerCallbackParam);
582 result = DeleteObserverUsingToken (token, tokenLength);
583 if(result == OC_STACK_OK)
585 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
589 result = OC_STACK_OK;
590 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
595 observer->failedCommCount++;
596 result = OC_STACK_CONTINUE;
598 observer->forceHighQos = 1;
599 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
603 OIC_LOG(ERROR, TAG, "Unknown status");
604 result = OC_STACK_ERROR;
610 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
612 OCStackResult ret = OC_STACK_ERROR;
616 case CA_ADAPTER_NOT_ENABLED:
617 case CA_SERVER_NOT_STARTED:
618 ret = OC_STACK_ADAPTER_NOT_ENABLED;
620 case CA_MEMORY_ALLOC_FAILED:
621 ret = OC_STACK_NO_MEMORY;
623 case CA_STATUS_INVALID_PARAM:
624 ret = OC_STACK_INVALID_PARAM;
632 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
634 OCStackResult ret = OC_STACK_ERROR;
639 ret = OC_STACK_RESOURCE_CREATED;
642 ret = OC_STACK_RESOURCE_DELETED;
650 ret = OC_STACK_INVALID_QUERY;
652 case CA_UNAUTHORIZED_REQ:
653 ret = OC_STACK_UNAUTHORIZED_REQ;
656 ret = OC_STACK_INVALID_OPTION;
659 ret = OC_STACK_NO_RESOURCE;
661 case CA_RETRANSMIT_TIMEOUT:
662 ret = OC_STACK_COMM_ERROR;
664 case CA_REQUEST_ENTITY_TOO_LARGE:
665 ret = OC_STACK_TOO_LARGE_REQ;
673 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
675 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
684 // This Response Code is like HTTP 204 "No Content" but only used in
685 // response to POST and PUT requests.
689 // This Response Code is like HTTP 200 "OK" but only used in response to
694 // This should not happen but,
695 // give it a value just in case but output an error
697 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
700 case OC_STACK_RESOURCE_CREATED:
703 case OC_STACK_RESOURCE_DELETED:
706 case OC_STACK_INVALID_QUERY:
709 case OC_STACK_INVALID_OPTION:
712 case OC_STACK_NO_RESOURCE:
715 case OC_STACK_COMM_ERROR:
716 ret = CA_RETRANSMIT_TIMEOUT;
718 case OC_STACK_UNAUTHORIZED_REQ:
719 ret = CA_UNAUTHORIZED_REQ;
727 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
729 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
731 // supply default behavior.
732 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
734 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
736 if ((caFlags & OC_MASK_SCOPE) == 0)
738 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
743 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
745 return (OCTransportFlags)caFlags;
748 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
750 uint32_t lowerBound = 0;
751 uint32_t higherBound = 0;
753 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
755 return OC_STACK_INVALID_PARAM;
758 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
760 cbNode->presence->TTL = maxAgeSeconds;
762 for (int index = 0; index < PresenceTimeOutSize; index++)
764 // Guard against overflow
765 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
768 lowerBound = GetTicks((PresenceTimeOut[index] *
769 cbNode->presence->TTL *
770 MILLISECONDS_PER_SECOND)/100);
774 lowerBound = GetTicks(UINT32_MAX);
777 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
780 higherBound = GetTicks((PresenceTimeOut[index + 1] *
781 cbNode->presence->TTL *
782 MILLISECONDS_PER_SECOND)/100);
786 higherBound = GetTicks(UINT32_MAX);
789 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
791 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
792 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
793 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
796 cbNode->presence->TTLlevel = 0;
798 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
802 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
804 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
806 return OC_RSRVD_TRIGGER_CREATE;
808 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
810 return OC_RSRVD_TRIGGER_CHANGE;
814 return OC_RSRVD_TRIGGER_DELETE;
818 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
822 return OC_PRESENCE_TRIGGER_CREATE;
824 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
826 return OC_PRESENCE_TRIGGER_CREATE;
828 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
830 return OC_PRESENCE_TRIGGER_CHANGE;
834 return OC_PRESENCE_TRIGGER_DELETE;
839 * The cononical presence allows constructed URIs to be string compared.
841 * requestUri must be a char array of size CA_MAX_URI_LENGTH
843 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
846 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
847 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
848 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
850 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
852 if (ep->adapter == CA_ADAPTER_IP)
854 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
856 if ('\0' == ep->addr[0]) // multicast
858 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
862 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
863 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
868 if ('\0' == ep->addr[0]) // multicast
870 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
871 ep->port = OC_MULTICAST_PORT;
873 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
874 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
878 // might work for other adapters (untested, but better than nothing)
879 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
880 OC_RSRVD_PRESENCE_URI);
884 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
885 const CAResponseInfo_t *responseInfo)
887 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
888 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
890 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
891 ClientCB * cbNode = NULL;
892 char *resourceTypeName = NULL;
893 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
894 OCStackResult result = OC_STACK_ERROR;
897 char presenceUri[CA_MAX_URI_LENGTH];
899 int presenceSubscribe = 0;
900 int multicastPresenceSubscribe = 0;
902 if (responseInfo->result != CA_CONTENT)
904 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
905 return OC_STACK_ERROR;
908 // check for unicast presence
909 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
910 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
912 return OC_STACK_INVALID_URI;
915 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
918 presenceSubscribe = 1;
922 // check for multiicast presence
923 CAEndpoint_t ep = { .adapter = endpoint->adapter,
924 .flags = endpoint->flags };
926 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
928 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
931 multicastPresenceSubscribe = 1;
935 if (!presenceSubscribe && !multicastPresenceSubscribe)
937 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
941 response.payload = NULL;
942 response.result = OC_STACK_OK;
944 CopyEndpointToDevAddr(endpoint, &response.devAddr);
945 FixUpClientResponse(&response);
947 if (responseInfo->info.payload)
949 result = OCParsePayload(&response.payload,
950 PAYLOAD_TYPE_PRESENCE,
951 responseInfo->info.payload,
952 responseInfo->info.payloadSize);
954 if(result != OC_STACK_OK)
956 OIC_LOG(ERROR, TAG, "Presence parse failed");
959 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
961 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
962 result = OC_STACK_ERROR;
965 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
966 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
967 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
970 if (presenceSubscribe)
972 if(cbNode->sequenceNumber == response.sequenceNumber)
974 OIC_LOG(INFO, TAG, "No presence change");
975 ResetPresenceTTL(cbNode, maxAge);
976 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
982 OIC_LOG(INFO, TAG, "Stopping presence");
983 response.result = OC_STACK_PRESENCE_STOPPED;
986 OICFree(cbNode->presence->timeOut);
987 OICFree(cbNode->presence);
988 cbNode->presence = NULL;
993 if(!cbNode->presence)
995 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
997 if(!(cbNode->presence))
999 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1000 result = OC_STACK_NO_MEMORY;
1004 VERIFY_NON_NULL_V(cbNode->presence);
1005 cbNode->presence->timeOut = NULL;
1006 cbNode->presence->timeOut = (uint32_t *)
1007 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1008 if(!(cbNode->presence->timeOut)){
1010 "Could not allocate memory for cbNode->presence->timeOut");
1011 OICFree(cbNode->presence);
1012 result = OC_STACK_NO_MEMORY;
1017 ResetPresenceTTL(cbNode, maxAge);
1019 cbNode->sequenceNumber = response.sequenceNumber;
1021 // Ensure that a filter is actually applied.
1022 if( resourceTypeName && cbNode->filterResourceType)
1024 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1033 // This is the multicast case
1034 OCMulticastNode* mcNode = NULL;
1035 mcNode = GetMCPresenceNode(presenceUri);
1039 if(mcNode->nonce == response.sequenceNumber)
1041 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1044 mcNode->nonce = response.sequenceNumber;
1048 OIC_LOG(INFO, TAG, "Stopping presence");
1049 response.result = OC_STACK_PRESENCE_STOPPED;
1054 char* uri = OICStrdup(presenceUri);
1058 "No Memory for URI to store in the presence node");
1059 result = OC_STACK_NO_MEMORY;
1063 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1064 if(result == OC_STACK_NO_MEMORY)
1067 "No Memory for Multicast Presence Node");
1071 // presence node now owns uri
1074 // Ensure that a filter is actually applied.
1075 if(resourceTypeName && cbNode->filterResourceType)
1077 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1084 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1086 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1088 FindAndDeleteClientCB(cbNode);
1092 OCPayloadDestroy(response.payload);
1096 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1098 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1100 if(responseInfo->info.resourceUri &&
1101 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1103 HandlePresenceResponse(endPoint, responseInfo);
1107 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1108 responseInfo->info.tokenLength, NULL, NULL);
1110 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1111 responseInfo->info.tokenLength);
1115 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1116 if(responseInfo->result == CA_EMPTY)
1118 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1119 // We do not have a case for the client to receive a RESET
1120 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1122 //This is the case of receiving an ACK on a request to a slow resource!
1123 OIC_LOG(INFO, TAG, "This is a pure ACK");
1124 //TODO: should we inform the client
1125 // app that at least the request was received at the server?
1128 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1130 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1131 OIC_LOG(INFO, TAG, "Calling into application address space");
1133 OCClientResponse response =
1134 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1135 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1136 FixUpClientResponse(&response);
1137 response.resourceUri = responseInfo->info.resourceUri;
1138 memcpy(response.identity.id, responseInfo->info.identity.id,
1139 sizeof (response.identity.id));
1140 response.identity.id_length = responseInfo->info.identity.id_length;
1142 response.result = CAResponseToOCStackResult(responseInfo->result);
1143 cbNode->callBack(cbNode->context,
1144 cbNode->handle, &response);
1145 FindAndDeleteClientCB(cbNode);
1149 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1150 OIC_LOG(INFO, TAG, "Calling into application address space");
1152 OCClientResponse response =
1153 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1154 response.sequenceNumber = -1;
1155 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1156 FixUpClientResponse(&response);
1157 response.resourceUri = responseInfo->info.resourceUri;
1158 memcpy(response.identity.id, responseInfo->info.identity.id,
1159 sizeof (response.identity.id));
1160 response.identity.id_length = responseInfo->info.identity.id_length;
1162 response.result = CAResponseToOCStackResult(responseInfo->result);
1164 if(responseInfo->info.payload &&
1165 responseInfo->info.payloadSize)
1167 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1168 // check the security resource
1169 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1171 type = PAYLOAD_TYPE_SECURITY;
1173 else if (cbNode->method == OC_REST_DISCOVER)
1175 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1176 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1178 type = PAYLOAD_TYPE_DISCOVERY;
1180 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1182 type = PAYLOAD_TYPE_DEVICE;
1184 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1186 type = PAYLOAD_TYPE_PLATFORM;
1188 #ifdef ROUTING_GATEWAY
1189 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1191 type = PAYLOAD_TYPE_REPRESENTATION;
1194 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1196 type = PAYLOAD_TYPE_RD;
1199 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1201 type = PAYLOAD_TYPE_REPRESENTATION;
1206 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1207 cbNode->method, cbNode->requestUri);
1211 else if (cbNode->method == OC_REST_GET ||
1212 cbNode->method == OC_REST_PUT ||
1213 cbNode->method == OC_REST_POST ||
1214 cbNode->method == OC_REST_OBSERVE ||
1215 cbNode->method == OC_REST_OBSERVE_ALL ||
1216 cbNode->method == OC_REST_DELETE)
1218 char targetUri[MAX_URI_LENGTH];
1219 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1220 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1221 if (strcmp(targetUri, cbNode->requestUri) == 0)
1223 type = PAYLOAD_TYPE_RD;
1225 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1227 type = PAYLOAD_TYPE_PLATFORM;
1229 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1231 type = PAYLOAD_TYPE_DEVICE;
1233 if (type == PAYLOAD_TYPE_INVALID)
1235 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1236 cbNode->method, cbNode->requestUri);
1237 type = PAYLOAD_TYPE_REPRESENTATION;
1242 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1243 cbNode->method, cbNode->requestUri);
1247 if(OC_STACK_OK != OCParsePayload(&response.payload,
1249 responseInfo->info.payload,
1250 responseInfo->info.payloadSize))
1252 OIC_LOG(ERROR, TAG, "Error converting payload");
1253 OCPayloadDestroy(response.payload);
1258 response.numRcvdVendorSpecificHeaderOptions = 0;
1259 if(responseInfo->info.numOptions > 0)
1262 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1263 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1266 uint32_t observationOption;
1267 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1268 for (observationOption=0, i=0;
1269 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1273 (observationOption << 8) | optionData[i];
1275 response.sequenceNumber = observationOption;
1277 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1282 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1285 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1287 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1288 OCPayloadDestroy(response.payload);
1292 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1294 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1295 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1299 if (cbNode->method == OC_REST_OBSERVE &&
1300 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1301 response.sequenceNumber <= cbNode->sequenceNumber)
1303 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1304 response.sequenceNumber);
1308 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1311 cbNode->sequenceNumber = response.sequenceNumber;
1313 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1315 FindAndDeleteClientCB(cbNode);
1319 // To keep discovery callbacks active.
1320 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1321 MILLISECONDS_PER_SECOND);
1325 //Need to send ACK when the response is CON
1326 if(responseInfo->info.type == CA_MSG_CONFIRM)
1328 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1329 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1332 OCPayloadDestroy(response.payload);
1339 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1340 if(responseInfo->result == CA_EMPTY)
1342 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1343 if(responseInfo->info.type == CA_MSG_RESET)
1345 OIC_LOG(INFO, TAG, "This is a RESET");
1346 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1347 OC_OBSERVER_NOT_INTERESTED);
1349 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1351 OIC_LOG(INFO, TAG, "This is a pure ACK");
1352 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1353 OC_OBSERVER_STILL_INTERESTED);
1356 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1358 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1359 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1360 OC_OBSERVER_FAILED_COMM);
1365 if(!cbNode && !observer)
1367 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1368 || myStackMode == OC_GATEWAY)
1370 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1371 if(responseInfo->result == CA_EMPTY)
1373 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1377 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1378 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1379 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1383 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1384 || myStackMode == OC_GATEWAY)
1386 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1387 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1389 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1390 responseInfo->info.messageId);
1392 if (responseInfo->info.type == CA_MSG_RESET)
1394 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1395 responseInfo->info.messageId);
1402 OIC_LOG(INFO, TAG, "Exit OCHandleResponse");
1405 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1407 VERIFY_NON_NULL_NR(endPoint, FATAL);
1408 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1410 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1412 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1413 #ifdef ROUTING_GATEWAY
1414 bool needRIHandling = false;
1416 * Routing manager is going to update either of endpoint or response or both.
1417 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1418 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1421 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1423 if(ret != OC_STACK_OK || !needRIHandling)
1425 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1431 * Put source in sender endpoint so that the next packet from application can be routed to
1432 * proper destination and remove "RM" coap header option before passing request / response to
1433 * RI as this option will make no sense to either RI or application.
1435 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1436 (uint8_t *) &(responseInfo->info.numOptions),
1437 (CAEndpoint_t *) endPoint);
1440 OCHandleResponse(endPoint, responseInfo);
1442 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1446 * This function handles error response from CA
1447 * code shall be added to handle the errors
1449 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1451 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1453 if (NULL == endPoint)
1455 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1459 if (NULL == errorInfo)
1461 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1465 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1466 errorInfo->info.tokenLength, NULL, NULL);
1469 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1470 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1471 FixUpClientResponse(&response);
1472 response.resourceUri = errorInfo->info.resourceUri;
1473 memcpy(response.identity.id, errorInfo->info.identity.id,
1474 sizeof (response.identity.id));
1475 response.identity.id_length = errorInfo->info.identity.id_length;
1476 response.result = CAResultToOCStackResult(errorInfo->result);
1478 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1479 FindAndDeleteClientCB(cbNode);
1482 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1486 * This function sends out Direct Stack Responses. These are responses that are not coming
1487 * from the application entity handler. These responses have no payload and are usually ACKs,
1488 * RESETs or some error conditions that were caught by the stack.
1490 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1491 const CAResponseResult_t responseResult, const CAMessageType_t type,
1492 const uint8_t numOptions, const CAHeaderOption_t *options,
1493 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1495 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1496 CAResponseInfo_t respInfo = {
1497 .result = responseResult
1499 respInfo.info.messageId = coapID;
1500 respInfo.info.numOptions = numOptions;
1502 if (respInfo.info.numOptions)
1504 respInfo.info.options =
1505 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1506 memcpy (respInfo.info.options, options,
1507 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1511 respInfo.info.payload = NULL;
1512 respInfo.info.token = token;
1513 respInfo.info.tokenLength = tokenLength;
1514 respInfo.info.type = type;
1515 respInfo.info.resourceUri = OICStrdup (resourceUri);
1516 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1518 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1519 // Add the destination to route option from the endpoint->routeData.
1520 bool doPost = false;
1521 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1522 if(OC_STACK_OK != result)
1524 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1529 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1530 CARequestInfo_t reqInfo = {.method = CA_POST };
1531 /* The following initialization is not done in a single initializer block as in
1532 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1533 * does not have designated initalizers. This is a work-around for now.
1535 reqInfo.info.type = CA_MSG_NONCONFIRM;
1536 reqInfo.info.messageId = coapID;
1537 reqInfo.info.tokenLength = tokenLength;
1538 reqInfo.info.token = token;
1539 reqInfo.info.numOptions = respInfo.info.numOptions;
1540 reqInfo.info.payload = NULL;
1541 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1542 if (reqInfo.info.numOptions)
1544 reqInfo.info.options =
1545 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1546 if (NULL == reqInfo.info.options)
1548 OIC_LOG(ERROR, TAG, "Calloc failed");
1549 return OC_STACK_NO_MEMORY;
1551 memcpy (reqInfo.info.options, respInfo.info.options,
1552 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1555 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1556 OICFree (reqInfo.info.resourceUri);
1557 OICFree (reqInfo.info.options);
1558 OICFree (respInfo.info.resourceUri);
1559 OICFree (respInfo.info.options);
1560 if (CA_STATUS_OK != caResult)
1562 OIC_LOG(ERROR, TAG, "CASendRequest error");
1563 return CAResultToOCResult(caResult);
1569 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1571 // resourceUri in the info field is cloned in the CA layer and
1572 // thus ownership is still here.
1573 OICFree (respInfo.info.resourceUri);
1574 OICFree (respInfo.info.options);
1575 if(CA_STATUS_OK != caResult)
1577 OIC_LOG(ERROR, TAG, "CASendResponse error");
1578 return CAResultToOCResult(caResult);
1581 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1585 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1587 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1588 OCStackResult result = OC_STACK_ERROR;
1589 if(!protocolRequest)
1591 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1592 return OC_STACK_INVALID_PARAM;
1595 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1596 protocolRequest->tokenLength);
1599 OIC_LOG(INFO, TAG, "This is a new Server Request");
1600 result = AddServerRequest(&request, protocolRequest->coapID,
1601 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1602 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1603 protocolRequest->observationOption, protocolRequest->qos,
1604 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1605 protocolRequest->payload, protocolRequest->requestToken,
1606 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1607 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1608 &protocolRequest->devAddr);
1609 if (OC_STACK_OK != result)
1611 OIC_LOG(ERROR, TAG, "Error adding server request");
1617 OIC_LOG(ERROR, TAG, "Out of Memory");
1618 return OC_STACK_NO_MEMORY;
1621 if(!protocolRequest->reqMorePacket)
1623 request->requestComplete = 1;
1628 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1631 if(request->requestComplete)
1633 OIC_LOG(INFO, TAG, "This Server Request is complete");
1634 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1635 OCResource *resource = NULL;
1636 result = DetermineResourceHandling (request, &resHandling, &resource);
1637 if (result == OC_STACK_OK)
1639 result = ProcessRequest(resHandling, resource, request);
1644 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1645 result = OC_STACK_CONTINUE;
1650 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1652 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1655 if (requestInfo->info.resourceUri &&
1656 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1658 HandleKeepAliveRequest(endPoint, requestInfo);
1663 OCStackResult requestResult = OC_STACK_ERROR;
1665 if(myStackMode == OC_CLIENT)
1667 //TODO: should the client be responding to requests?
1671 OCServerProtocolRequest serverRequest = {0};
1673 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1675 char * uriWithoutQuery = NULL;
1676 char * query = NULL;
1678 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1680 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1682 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1685 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1686 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1688 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1690 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1691 OICFree(uriWithoutQuery);
1695 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1696 OICFree(uriWithoutQuery);
1703 if(strlen(query) < MAX_QUERY_LENGTH)
1705 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1710 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1716 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1718 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1719 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1720 if (!serverRequest.payload)
1722 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1725 memcpy (serverRequest.payload, requestInfo->info.payload,
1726 requestInfo->info.payloadSize);
1730 serverRequest.reqTotalSize = 0;
1733 switch (requestInfo->method)
1736 serverRequest.method = OC_REST_GET;
1739 serverRequest.method = OC_REST_PUT;
1742 serverRequest.method = OC_REST_POST;
1745 serverRequest.method = OC_REST_DELETE;
1748 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1749 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1750 requestInfo->info.type, requestInfo->info.numOptions,
1751 requestInfo->info.options, requestInfo->info.token,
1752 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1753 OICFree(serverRequest.payload);
1757 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1758 requestInfo->info.tokenLength);
1760 serverRequest.tokenLength = requestInfo->info.tokenLength;
1761 if (serverRequest.tokenLength) {
1763 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1765 if (!serverRequest.requestToken)
1767 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1768 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1769 requestInfo->info.type, requestInfo->info.numOptions,
1770 requestInfo->info.options, requestInfo->info.token,
1771 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1772 OICFree(serverRequest.payload);
1775 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1778 switch (requestInfo->info.acceptFormat)
1780 case CA_FORMAT_APPLICATION_CBOR:
1781 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1783 case CA_FORMAT_UNDEFINED:
1784 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1787 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1790 if (requestInfo->info.type == CA_MSG_CONFIRM)
1792 serverRequest.qos = OC_HIGH_QOS;
1796 serverRequest.qos = OC_LOW_QOS;
1798 // CA does not need the following field
1799 // Are we sure CA does not need them? how is it responding to multicast
1800 serverRequest.delayedResNeeded = 0;
1802 serverRequest.coapID = requestInfo->info.messageId;
1804 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1806 // copy vendor specific header options
1807 uint8_t tempNum = (requestInfo->info.numOptions);
1809 // Assume no observation requested and it is a pure GET.
1810 // If obs registration/de-registration requested it'll be fetched from the
1811 // options in GetObserveHeaderOption()
1812 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1814 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1815 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1818 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1819 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1820 requestInfo->info.type, requestInfo->info.numOptions,
1821 requestInfo->info.options, requestInfo->info.token,
1822 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1823 OICFree(serverRequest.payload);
1824 OICFree(serverRequest.requestToken);
1827 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1828 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1830 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1831 sizeof(CAHeaderOption_t)*tempNum);
1834 requestResult = HandleStackRequests (&serverRequest);
1836 // Send ACK to client as precursor to slow response
1837 if (requestResult == OC_STACK_SLOW_RESOURCE)
1839 if (requestInfo->info.type == CA_MSG_CONFIRM)
1841 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1842 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1845 else if(requestResult != OC_STACK_OK)
1847 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1849 CAResponseResult_t stackResponse =
1850 OCToCAStackResult(requestResult, serverRequest.method);
1852 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1853 requestInfo->info.type, requestInfo->info.numOptions,
1854 requestInfo->info.options, requestInfo->info.token,
1855 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1857 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1858 // The token is copied in there, and is thus still owned by this function.
1859 OICFree(serverRequest.payload);
1860 OICFree(serverRequest.requestToken);
1861 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1864 //This function will be called back by CA layer when a request is received
1865 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1867 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1870 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1876 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
1880 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1881 #ifdef ROUTING_GATEWAY
1882 bool needRIHandling = false;
1883 bool isEmptyMsg = false;
1885 * Routing manager is going to update either of endpoint or request or both.
1886 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1887 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1888 * destination. It can also remove "RM" coap header option before passing request / response to
1889 * RI as this option will make no sense to either RI or application.
1891 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1892 &needRIHandling, &isEmptyMsg);
1893 if(OC_STACK_OK != ret || !needRIHandling)
1895 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1901 * Put source in sender endpoint so that the next packet from application can be routed to
1902 * proper destination and remove RM header option.
1904 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
1905 (uint8_t *) &(requestInfo->info.numOptions),
1906 (CAEndpoint_t *) endPoint);
1908 #ifdef ROUTING_GATEWAY
1912 * In Gateways, the MSGType in route option is used to check if the actual
1913 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
1914 * EMPTY response is sent in the form of POST request which need to be changed
1915 * to a EMPTY response by RM. This translation is done in this part of the code.
1917 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
1918 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
1919 .info.messageId = requestInfo->info.messageId,
1920 .info.type = CA_MSG_ACKNOWLEDGE};
1921 OCHandleResponse(endPoint, &respInfo);
1927 // Normal handling of the packet
1928 OCHandleRequests(endPoint, requestInfo);
1930 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
1933 bool validatePlatformInfo(OCPlatformInfo info)
1936 if (!info.platformID)
1938 OIC_LOG(ERROR, TAG, "No platform ID found.");
1942 if (info.manufacturerName)
1944 size_t lenManufacturerName = strlen(info.manufacturerName);
1946 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1948 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
1954 OIC_LOG(ERROR, TAG, "No manufacturer name present");
1958 if (info.manufacturerUrl)
1960 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1962 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
1969 //-----------------------------------------------------------------------------
1971 //-----------------------------------------------------------------------------
1973 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1976 !raInfo->username ||
1977 !raInfo->hostname ||
1978 !raInfo->xmpp_domain)
1981 return OC_STACK_INVALID_PARAM;
1983 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1984 gRASetInfo = (result == OC_STACK_OK)? true : false;
1990 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1994 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1997 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1999 if(stackState == OC_STACK_INITIALIZED)
2001 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2002 OCStop() between them are ignored.");
2006 #ifndef ROUTING_GATEWAY
2007 if (OC_GATEWAY == mode)
2009 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2010 return OC_STACK_INVALID_PARAM;
2017 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2018 return OC_STACK_ERROR;
2022 OCStackResult result = OC_STACK_ERROR;
2023 OIC_LOG(INFO, TAG, "Entering OCInit");
2026 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2027 || (mode == OC_GATEWAY)))
2029 OIC_LOG(ERROR, TAG, "Invalid mode");
2030 return OC_STACK_ERROR;
2034 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2036 caglobals.client = true;
2038 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2040 caglobals.server = true;
2043 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2044 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2046 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2048 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2049 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2051 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2054 defaultDeviceHandler = NULL;
2055 defaultDeviceHandlerCallbackParameter = NULL;
2057 result = CAResultToOCResult(CAInitialize());
2058 VERIFY_SUCCESS(result, OC_STACK_OK);
2060 result = CAResultToOCResult(OCSelectNetwork());
2061 VERIFY_SUCCESS(result, OC_STACK_OK);
2063 switch (myStackMode)
2066 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2067 result = CAResultToOCResult(CAStartDiscoveryServer());
2068 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2071 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2072 result = CAResultToOCResult(CAStartListeningServer());
2073 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2075 case OC_CLIENT_SERVER:
2077 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2078 result = CAResultToOCResult(CAStartListeningServer());
2079 if(result == OC_STACK_OK)
2081 result = CAResultToOCResult(CAStartDiscoveryServer());
2085 VERIFY_SUCCESS(result, OC_STACK_OK);
2088 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2091 #ifdef WITH_PRESENCE
2092 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2093 #endif // WITH_PRESENCE
2095 //Update Stack state to initialized
2096 stackState = OC_STACK_INITIALIZED;
2098 // Initialize resource
2099 if(myStackMode != OC_CLIENT)
2101 result = initResources();
2104 // Initialize the SRM Policy Engine
2105 if(result == OC_STACK_OK)
2107 result = SRMInitPolicyEngine();
2108 // TODO after BeachHead delivery: consolidate into single SRMInit()
2110 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2111 RMSetStackMode(mode);
2112 #ifdef ROUTING_GATEWAY
2113 if (OC_GATEWAY == myStackMode)
2115 result = RMInitialize();
2121 if (result == OC_STACK_OK)
2123 result = InitializeKeepAlive(myStackMode);
2128 if(result != OC_STACK_OK)
2130 OIC_LOG(ERROR, TAG, "Stack initialization error");
2131 deleteAllResources();
2133 stackState = OC_STACK_UNINITIALIZED;
2138 OCStackResult OCStop()
2140 OIC_LOG(INFO, TAG, "Entering OCStop");
2142 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2144 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2147 else if (stackState != OC_STACK_INITIALIZED)
2149 OIC_LOG(ERROR, TAG, "Stack not initialized");
2150 return OC_STACK_ERROR;
2153 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2155 #ifdef WITH_PRESENCE
2156 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2157 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2158 presenceResource.presenceTTL = 0;
2159 #endif // WITH_PRESENCE
2161 #ifdef ROUTING_GATEWAY
2162 if (OC_GATEWAY == myStackMode)
2169 TerminateKeepAlive(myStackMode);
2172 // Free memory dynamically allocated for resources
2173 deleteAllResources();
2175 DeletePlatformInfo();
2177 // Remove all observers
2178 DeleteObserverList();
2179 // Remove all the client callbacks
2180 DeleteClientCBList();
2182 // De-init the SRM Policy Engine
2183 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2184 SRMDeInitPolicyEngine();
2187 stackState = OC_STACK_UNINITIALIZED;
2191 OCStackResult OCStartMulticastServer()
2193 if(stackState != OC_STACK_INITIALIZED)
2195 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2196 return OC_STACK_ERROR;
2198 CAResult_t ret = CAStartListeningServer();
2199 if (CA_STATUS_OK != ret)
2201 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2202 return OC_STACK_ERROR;
2207 OCStackResult OCStopMulticastServer()
2209 CAResult_t ret = CAStopListeningServer();
2210 if (CA_STATUS_OK != ret)
2212 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2213 return OC_STACK_ERROR;
2218 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2223 return CA_MSG_CONFIRM;
2228 return CA_MSG_NONCONFIRM;
2233 * A request uri consists of the following components in order:
2236 * CoAP over UDP prefix "coap://"
2237 * CoAP over TCP prefix "coap+tcp://"
2239 * IPv6 address "[1234::5678]"
2240 * IPv4 address "192.168.1.1"
2241 * optional port ":5683"
2242 * resource uri "/oc/core..."
2244 * for PRESENCE requests, extract resource type.
2246 static OCStackResult ParseRequestUri(const char *fullUri,
2247 OCTransportAdapter adapter,
2248 OCTransportFlags flags,
2249 OCDevAddr **devAddr,
2251 char **resourceType)
2253 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2255 OCStackResult result = OC_STACK_OK;
2256 OCDevAddr *da = NULL;
2260 // provide defaults for all returned values
2267 *resourceUri = NULL;
2271 *resourceType = NULL;
2274 // delimit url prefix, if any
2275 const char *start = fullUri;
2276 char *slash2 = strstr(start, "//");
2281 char *slash = strchr(start, '/');
2284 return OC_STACK_INVALID_URI;
2287 // process url scheme
2288 size_t prefixLen = slash2 - fullUri;
2292 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2298 // TODO: this logic should come in with unit tests exercising the various strings
2299 // processs url prefix, if any
2300 size_t urlLen = slash - start;
2304 if (urlLen && devAddr)
2305 { // construct OCDevAddr
2306 if (start[0] == '[')
2308 char *close = strchr(++start, ']');
2309 if (!close || close > slash)
2311 return OC_STACK_INVALID_URI;
2314 if (close[1] == ':')
2321 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2325 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2327 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2331 char *dot = strchr(start, '.');
2332 if (dot && dot < slash)
2334 colon = strchr(start, ':');
2335 end = (colon && colon < slash) ? colon : slash;
2340 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2344 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2346 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2354 if (len >= sizeof(da->addr))
2356 return OC_STACK_INVALID_URI;
2358 // collect port, if any
2359 if (colon && colon < slash)
2361 for (colon++; colon < slash; colon++)
2364 if (c < '0' || c > '9')
2366 return OC_STACK_INVALID_URI;
2368 port = 10 * port + c - '0';
2373 if (len >= sizeof(da->addr))
2375 return OC_STACK_INVALID_URI;
2378 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2381 return OC_STACK_NO_MEMORY;
2383 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2385 da->adapter = adapter;
2387 if (!strncmp(fullUri, "coaps:", 6))
2389 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2394 // process resource uri, if any
2396 { // request uri and query
2397 size_t ulen = strlen(slash); // resource uri length
2398 size_t tlen = 0; // resource type length
2401 static const char strPresence[] = "/oic/ad?rt=";
2402 static const size_t lenPresence = sizeof(strPresence) - 1;
2403 if (!strncmp(slash, strPresence, lenPresence))
2405 type = slash + lenPresence;
2406 tlen = ulen - lenPresence;
2411 *resourceUri = (char *)OICMalloc(ulen + 1);
2414 result = OC_STACK_NO_MEMORY;
2417 strcpy(*resourceUri, slash);
2420 if (type && resourceType)
2422 *resourceType = (char *)OICMalloc(tlen + 1);
2425 result = OC_STACK_NO_MEMORY;
2429 OICStrcpy(*resourceType, (tlen+1), type);
2436 // free all returned values
2443 OICFree(*resourceUri);
2447 OICFree(*resourceType);
2452 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2453 char *resourceUri, char **requestUri)
2455 char uri[CA_MAX_URI_LENGTH];
2457 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2459 *requestUri = OICStrdup(uri);
2462 return OC_STACK_NO_MEMORY;
2469 * Discover or Perform requests on a specified resource
2471 OCStackResult OCDoResource(OCDoHandle *handle,
2473 const char *requestUri,
2474 const OCDevAddr *destination,
2476 OCConnectivityType connectivityType,
2477 OCQualityOfService qos,
2478 OCCallbackData *cbData,
2479 OCHeaderOption *options,
2482 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2484 // Validate input parameters
2485 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2486 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2487 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2489 OCStackResult result = OC_STACK_ERROR;
2490 CAResult_t caResult;
2491 CAToken_t token = NULL;
2492 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2493 ClientCB *clientCB = NULL;
2494 OCDoHandle resHandle = NULL;
2495 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2496 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2498 OCTransportAdapter adapter;
2499 OCTransportFlags flags;
2500 // the request contents are put here
2501 CARequestInfo_t requestInfo = {.method = CA_GET};
2502 // requestUri will be parsed into the following three variables
2503 OCDevAddr *devAddr = NULL;
2504 char *resourceUri = NULL;
2505 char *resourceType = NULL;
2508 * Support original behavior with address on resourceUri argument.
2510 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2511 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2513 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2515 if (result != OC_STACK_OK)
2517 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2524 case OC_REST_OBSERVE:
2525 case OC_REST_OBSERVE_ALL:
2526 case OC_REST_CANCEL_OBSERVE:
2527 requestInfo.method = CA_GET;
2530 requestInfo.method = CA_PUT;
2533 requestInfo.method = CA_POST;
2535 case OC_REST_DELETE:
2536 requestInfo.method = CA_DELETE;
2538 case OC_REST_DISCOVER:
2540 if (destination || devAddr)
2542 requestInfo.isMulticast = false;
2546 tmpDevAddr.adapter = adapter;
2547 tmpDevAddr.flags = flags;
2548 destination = &tmpDevAddr;
2549 requestInfo.isMulticast = true;
2551 // CA_DISCOVER will become GET and isMulticast
2552 requestInfo.method = CA_GET;
2554 #ifdef WITH_PRESENCE
2555 case OC_REST_PRESENCE:
2556 // Replacing method type with GET because "presence"
2557 // is a stack layer only implementation.
2558 requestInfo.method = CA_GET;
2562 result = OC_STACK_INVALID_METHOD;
2566 if (!devAddr && !destination)
2568 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2569 result = OC_STACK_INVALID_PARAM;
2573 /* If not original behavior, use destination argument */
2574 if (destination && !devAddr)
2576 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2579 result = OC_STACK_NO_MEMORY;
2582 *devAddr = *destination;
2585 resHandle = GenerateInvocationHandle();
2588 result = OC_STACK_NO_MEMORY;
2592 caResult = CAGenerateToken(&token, tokenLength);
2593 if (caResult != CA_STATUS_OK)
2595 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2596 result= OC_STACK_ERROR;
2600 // fill in request data
2601 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2602 requestInfo.info.token = token;
2603 requestInfo.info.tokenLength = tokenLength;
2604 requestInfo.info.resourceUri = resourceUri;
2606 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2608 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2609 options, numOptions, OC_OBSERVE_REGISTER);
2610 if (result != OC_STACK_OK)
2614 requestInfo.info.numOptions = numOptions + 1;
2618 requestInfo.info.numOptions = numOptions;
2619 requestInfo.info.options =
2620 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2621 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2622 numOptions * sizeof(CAHeaderOption_t));
2625 CopyDevAddrToEndpoint(devAddr, &endpoint);
2630 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2633 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2636 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2640 requestInfo.info.payload = NULL;
2641 requestInfo.info.payloadSize = 0;
2642 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2645 // prepare for response
2646 #ifdef WITH_PRESENCE
2647 if (method == OC_REST_PRESENCE)
2649 char *presenceUri = NULL;
2650 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2651 if (OC_STACK_OK != result)
2656 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2657 // Presence notification will form a canonical uri to
2658 // look for callbacks into the application.
2659 resourceUri = presenceUri;
2663 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2664 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2665 method, devAddr, resourceUri, resourceType, ttl);
2666 if (OC_STACK_OK != result)
2671 devAddr = NULL; // Client CB list entry now owns it
2672 resourceUri = NULL; // Client CB list entry now owns it
2673 resourceType = NULL; // Client CB list entry now owns it
2676 result = OCSendRequest(&endpoint, &requestInfo);
2677 if (OC_STACK_OK != result)
2684 *handle = resHandle;
2688 if (result != OC_STACK_OK)
2690 OIC_LOG(ERROR, TAG, "OCDoResource error");
2691 FindAndDeleteClientCB(clientCB);
2692 CADestroyToken(token);
2700 // This is the owner of the payload object, so we free it
2701 OCPayloadDestroy(payload);
2702 OICFree(requestInfo.info.payload);
2704 OICFree(resourceUri);
2705 OICFree(resourceType);
2706 OICFree(requestInfo.info.options);
2710 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2714 * This ftn is implemented one of two ways in the case of observation:
2716 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2717 * Remove the callback associated on client side.
2718 * When the next notification comes in from server,
2719 * reply with RESET message to server.
2720 * Keep in mind that the server will react to RESET only
2721 * if the last notification was sent as CON
2723 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2724 * and it is associated with an observe request
2725 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2726 * Send CON Observe request to server with
2727 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2728 * Remove the callback associated on client side.
2730 OCStackResult ret = OC_STACK_OK;
2731 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2732 CARequestInfo_t requestInfo = {.method = CA_GET};
2736 return OC_STACK_INVALID_PARAM;
2739 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2742 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2743 return OC_STACK_ERROR;
2746 switch (clientCB->method)
2748 case OC_REST_OBSERVE:
2749 case OC_REST_OBSERVE_ALL:
2751 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2753 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2755 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2757 FindAndDeleteClientCB(clientCB);
2761 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2763 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2764 requestInfo.info.token = clientCB->token;
2765 requestInfo.info.tokenLength = clientCB->tokenLength;
2767 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2768 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2770 return OC_STACK_ERROR;
2772 requestInfo.info.numOptions = numOptions + 1;
2773 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2776 ret = OCSendRequest(&endpoint, &requestInfo);
2778 if (requestInfo.info.options)
2780 OICFree (requestInfo.info.options);
2782 if (requestInfo.info.resourceUri)
2784 OICFree (requestInfo.info.resourceUri);
2789 case OC_REST_DISCOVER:
2790 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2791 clientCB->requestUri);
2792 FindAndDeleteClientCB(clientCB);
2795 #ifdef WITH_PRESENCE
2796 case OC_REST_PRESENCE:
2797 FindAndDeleteClientCB(clientCB);
2802 ret = OC_STACK_INVALID_METHOD;
2810 * @brief Register Persistent storage callback.
2811 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2813 * OC_STACK_OK - No errors; Success
2814 * OC_STACK_INVALID_PARAM - Invalid parameter
2816 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2818 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2819 if(!persistentStorageHandler)
2821 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2822 return OC_STACK_INVALID_PARAM;
2826 if( !persistentStorageHandler->open ||
2827 !persistentStorageHandler->close ||
2828 !persistentStorageHandler->read ||
2829 !persistentStorageHandler->unlink ||
2830 !persistentStorageHandler->write)
2832 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2833 return OC_STACK_INVALID_PARAM;
2836 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2839 #ifdef WITH_PRESENCE
2841 OCStackResult OCProcessPresence()
2843 OCStackResult result = OC_STACK_OK;
2845 // the following line floods the log with messages that are irrelevant
2846 // to most purposes. Uncomment as needed.
2847 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2848 ClientCB* cbNode = NULL;
2849 OCClientResponse clientResponse;
2850 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2852 LL_FOREACH(cbList, cbNode)
2854 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2859 uint32_t now = GetTicks(0);
2860 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2861 cbNode->presence->TTLlevel);
2862 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2864 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2869 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2871 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2872 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2874 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2876 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2878 clientResponse.sequenceNumber = 0;
2879 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2880 clientResponse.devAddr = *cbNode->devAddr;
2881 FixUpClientResponse(&clientResponse);
2882 clientResponse.payload = NULL;
2884 // Increment the TTLLevel (going to a next state), so we don't keep
2885 // sending presence notification to client.
2886 cbNode->presence->TTLlevel++;
2887 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2888 cbNode->presence->TTLlevel);
2890 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2891 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2893 FindAndDeleteClientCB(cbNode);
2897 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2902 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2903 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2904 CARequestInfo_t requestInfo = {.method = CA_GET};
2906 OIC_LOG(DEBUG, TAG, "time to test server presence");
2908 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2910 requestData.type = CA_MSG_NONCONFIRM;
2911 requestData.token = cbNode->token;
2912 requestData.tokenLength = cbNode->tokenLength;
2913 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2914 requestInfo.method = CA_GET;
2915 requestInfo.info = requestData;
2917 result = OCSendRequest(&endpoint, &requestInfo);
2918 if (OC_STACK_OK != result)
2923 cbNode->presence->TTLlevel++;
2924 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2927 if (result != OC_STACK_OK)
2929 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
2934 #endif // WITH_PRESENCE
2936 OCStackResult OCProcess()
2938 #ifdef WITH_PRESENCE
2939 OCProcessPresence();
2941 CAHandleRequestResponse();
2943 #ifdef ROUTING_GATEWAY
2953 #ifdef WITH_PRESENCE
2954 OCStackResult OCStartPresence(const uint32_t ttl)
2956 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2957 OCChangeResourceProperty(
2958 &(((OCResource *)presenceResource.handle)->resourceProperties),
2961 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2963 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2964 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
2968 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2969 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
2973 presenceResource.presenceTTL = ttl;
2975 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
2977 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2979 presenceState = OC_PRESENCE_INITIALIZED;
2981 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2983 CAToken_t caToken = NULL;
2984 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2985 if (caResult != CA_STATUS_OK)
2987 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2988 CADestroyToken(caToken);
2989 return OC_STACK_ERROR;
2992 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2993 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
2994 CADestroyToken(caToken);
2997 // Each time OCStartPresence is called
2998 // a different random 32-bit integer number is used
2999 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3001 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3002 OC_PRESENCE_TRIGGER_CREATE);
3005 OCStackResult OCStopPresence()
3007 OCStackResult result = OC_STACK_ERROR;
3009 if(presenceResource.handle)
3011 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3013 // make resource inactive
3014 result = OCChangeResourceProperty(
3015 &(((OCResource *) presenceResource.handle)->resourceProperties),
3019 if(result != OC_STACK_OK)
3022 "Changing the presence resource properties to ACTIVE not successful");
3026 return SendStopNotification();
3030 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3031 void* callbackParameter)
3033 defaultDeviceHandler = entityHandler;
3034 defaultDeviceHandlerCallbackParameter = callbackParameter;
3039 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3041 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3043 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3045 if (validatePlatformInfo(platformInfo))
3047 return SavePlatformInfo(platformInfo);
3051 return OC_STACK_INVALID_PARAM;
3056 return OC_STACK_ERROR;
3060 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3062 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3064 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3066 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3067 return OC_STACK_INVALID_PARAM;
3070 if (deviceInfo.types)
3072 OCStringLL *type = deviceInfo.types;
3073 OCResource *resource = findResource((OCResource *) deviceResource);
3076 return OC_STACK_INVALID_PARAM;
3078 deleteResourceType(resource->rsrcType);
3079 resource->rsrcType = NULL;
3083 OCBindResourceTypeToResource(deviceResource, type->value);
3087 return SaveDeviceInfo(deviceInfo);
3090 OCStackResult OCCreateResource(OCResourceHandle *handle,
3091 const char *resourceTypeName,
3092 const char *resourceInterfaceName,
3093 const char *uri, OCEntityHandler entityHandler,
3094 void* callbackParam,
3095 uint8_t resourceProperties)
3098 OCResource *pointer = NULL;
3099 OCStackResult result = OC_STACK_ERROR;
3101 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3103 if(myStackMode == OC_CLIENT)
3105 return OC_STACK_INVALID_PARAM;
3107 // Validate parameters
3108 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3110 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3111 return OC_STACK_INVALID_URI;
3113 // Is it presented during resource discovery?
3114 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3116 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3117 return OC_STACK_INVALID_PARAM;
3120 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3122 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3125 // Make sure resourceProperties bitmask has allowed properties specified
3126 if (resourceProperties
3127 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3128 OC_EXPLICIT_DISCOVERABLE))
3130 OIC_LOG(ERROR, TAG, "Invalid property");
3131 return OC_STACK_INVALID_PARAM;
3134 // If the headResource is NULL, then no resources have been created...
3135 pointer = headResource;
3138 // At least one resources is in the resource list, so we need to search for
3139 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3142 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3144 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3145 return OC_STACK_INVALID_PARAM;
3147 pointer = pointer->next;
3150 // Create the pointer and insert it into the resource list
3151 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3154 result = OC_STACK_NO_MEMORY;
3157 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3159 insertResource(pointer);
3162 pointer->uri = OICStrdup(uri);
3165 result = OC_STACK_NO_MEMORY;
3169 // Set properties. Set OC_ACTIVE
3170 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3173 // Add the resourcetype to the resource
3174 result = BindResourceTypeToResource(pointer, resourceTypeName);
3175 if (result != OC_STACK_OK)
3177 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3181 // Add the resourceinterface to the resource
3182 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3183 if (result != OC_STACK_OK)
3185 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3189 // If an entity handler has been passed, attach it to the newly created
3190 // resource. Otherwise, set the default entity handler.
3193 pointer->entityHandler = entityHandler;
3194 pointer->entityHandlerCallbackParam = callbackParam;
3198 pointer->entityHandler = defaultResourceEHandler;
3199 pointer->entityHandlerCallbackParam = NULL;
3202 // Initialize a pointer indicating child resources in case of collection
3203 pointer->rsrcChildResourcesHead = NULL;
3206 result = OC_STACK_OK;
3208 #ifdef WITH_PRESENCE
3209 if (presenceResource.handle)
3211 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3212 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3216 if (result != OC_STACK_OK)
3218 // Deep delete of resource and other dynamic elements that it contains
3219 deleteResource(pointer);
3224 OCStackResult OCBindResource(
3225 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3227 OCResource *resource = NULL;
3228 OCChildResource *tempChildResource = NULL;
3229 OCChildResource *newChildResource = NULL;
3231 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3233 // Validate parameters
3234 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3235 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3236 // Container cannot contain itself
3237 if (collectionHandle == resourceHandle)
3239 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3240 return OC_STACK_INVALID_PARAM;
3243 // Use the handle to find the resource in the resource linked list
3244 resource = findResource((OCResource *) collectionHandle);
3247 OIC_LOG(ERROR, TAG, "Collection handle not found");
3248 return OC_STACK_INVALID_PARAM;
3251 // Look for an open slot to add add the child resource.
3252 // If found, add it and return success
3254 tempChildResource = resource->rsrcChildResourcesHead;
3256 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3258 // TODO: what if one of child resource was deregistered without unbinding?
3259 tempChildResource = tempChildResource->next;
3262 // Do memory allocation for child resource
3263 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3264 if(!newChildResource)
3266 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3267 return OC_STACK_ERROR;
3270 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3271 newChildResource->next = NULL;
3273 if(!resource->rsrcChildResourcesHead)
3275 resource->rsrcChildResourcesHead = newChildResource;
3278 tempChildResource->next = newChildResource;
3281 OIC_LOG(INFO, TAG, "resource bound");
3283 #ifdef WITH_PRESENCE
3284 if (presenceResource.handle)
3286 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3287 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3288 OC_PRESENCE_TRIGGER_CHANGE);
3295 OCStackResult OCUnBindResource(
3296 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3298 OCResource *resource = NULL;
3299 OCChildResource *tempChildResource = NULL;
3300 OCChildResource *tempLastChildResource = NULL;
3302 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3304 // Validate parameters
3305 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3306 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3307 // Container cannot contain itself
3308 if (collectionHandle == resourceHandle)
3310 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3311 return OC_STACK_INVALID_PARAM;
3314 // Use the handle to find the resource in the resource linked list
3315 resource = findResource((OCResource *) collectionHandle);
3318 OIC_LOG(ERROR, TAG, "Collection handle not found");
3319 return OC_STACK_INVALID_PARAM;
3322 // Look for an open slot to add add the child resource.
3323 // If found, add it and return success
3324 if(!resource->rsrcChildResourcesHead)
3326 OIC_LOG(INFO, TAG, "resource not found in collection");
3328 // Unable to add resourceHandle, so return error
3329 return OC_STACK_ERROR;
3333 tempChildResource = resource->rsrcChildResourcesHead;
3335 while (tempChildResource)
3337 if(tempChildResource->rsrcResource == resourceHandle)
3339 // if resource going to be unbinded is the head one.
3340 if( tempChildResource == resource->rsrcChildResourcesHead )
3342 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3343 OICFree(resource->rsrcChildResourcesHead);
3344 resource->rsrcChildResourcesHead = temp;
3349 OCChildResource *temp = tempChildResource->next;
3350 OICFree(tempChildResource);
3351 tempLastChildResource->next = temp;
3355 OIC_LOG(INFO, TAG, "resource unbound");
3357 // Send notification when resource is unbounded successfully.
3358 #ifdef WITH_PRESENCE
3359 if (presenceResource.handle)
3361 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3362 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3363 OC_PRESENCE_TRIGGER_CHANGE);
3366 tempChildResource = NULL;
3367 tempLastChildResource = NULL;
3373 tempLastChildResource = tempChildResource;
3374 tempChildResource = tempChildResource->next;
3377 OIC_LOG(INFO, TAG, "resource not found in collection");
3379 tempChildResource = NULL;
3380 tempLastChildResource = NULL;
3382 // Unable to add resourceHandle, so return error
3383 return OC_STACK_ERROR;
3386 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3388 if (!resourceItemName)
3392 // Per RFC 6690 only registered values must follow the first rule below.
3393 // At this point in time the only values registered begin with "core", and
3394 // all other values are specified as opaque strings where multiple values
3395 // are separated by a space.
3396 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3398 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3400 if (resourceItemName[index] != '.'
3401 && resourceItemName[index] != '-'
3402 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3403 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3411 for (size_t index = 0; resourceItemName[index]; ++index)
3413 if (resourceItemName[index] == ' '
3414 || resourceItemName[index] == '\t'
3415 || resourceItemName[index] == '\r'
3416 || resourceItemName[index] == '\n')
3426 OCStackResult BindResourceTypeToResource(OCResource* resource,
3427 const char *resourceTypeName)
3429 OCResourceType *pointer = NULL;
3431 OCStackResult result = OC_STACK_ERROR;
3433 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3435 if (!ValidateResourceTypeInterface(resourceTypeName))
3437 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3438 return OC_STACK_INVALID_PARAM;
3441 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3444 result = OC_STACK_NO_MEMORY;
3448 str = OICStrdup(resourceTypeName);
3451 result = OC_STACK_NO_MEMORY;
3454 pointer->resourcetypename = str;
3455 pointer->next = NULL;
3457 insertResourceType(resource, pointer);
3458 result = OC_STACK_OK;
3461 if (result != OC_STACK_OK)
3470 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3471 const char *resourceInterfaceName)
3473 OCResourceInterface *pointer = NULL;
3475 OCStackResult result = OC_STACK_ERROR;
3477 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3479 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3481 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3482 return OC_STACK_INVALID_PARAM;
3485 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3487 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3490 result = OC_STACK_NO_MEMORY;
3494 str = OICStrdup(resourceInterfaceName);
3497 result = OC_STACK_NO_MEMORY;
3500 pointer->name = str;
3502 // Bind the resourceinterface to the resource
3503 insertResourceInterface(resource, pointer);
3505 result = OC_STACK_OK;
3508 if (result != OC_STACK_OK)
3517 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3518 const char *resourceTypeName)
3521 OCStackResult result = OC_STACK_ERROR;
3522 OCResource *resource = NULL;
3524 resource = findResource((OCResource *) handle);
3527 OIC_LOG(ERROR, TAG, "Resource not found");
3528 return OC_STACK_ERROR;
3531 result = BindResourceTypeToResource(resource, resourceTypeName);
3533 #ifdef WITH_PRESENCE
3534 if(presenceResource.handle)
3536 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3537 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3544 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3545 const char *resourceInterfaceName)
3548 OCStackResult result = OC_STACK_ERROR;
3549 OCResource *resource = NULL;
3551 resource = findResource((OCResource *) handle);
3554 OIC_LOG(ERROR, TAG, "Resource not found");
3555 return OC_STACK_ERROR;
3558 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3560 #ifdef WITH_PRESENCE
3561 if (presenceResource.handle)
3563 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3564 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3571 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3573 OCResource *pointer = headResource;
3575 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3579 *numResources = *numResources + 1;
3580 pointer = pointer->next;
3585 OCResourceHandle OCGetResourceHandle(uint8_t index)
3587 OCResource *pointer = headResource;
3589 for( uint8_t i = 0; i < index && pointer; ++i)
3591 pointer = pointer->next;
3593 return (OCResourceHandle) pointer;
3596 OCStackResult OCDeleteResource(OCResourceHandle handle)
3600 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3601 return OC_STACK_INVALID_PARAM;
3604 OCResource *resource = findResource((OCResource *) handle);
3605 if (resource == NULL)
3607 OIC_LOG(ERROR, TAG, "Resource not found");
3608 return OC_STACK_NO_RESOURCE;
3611 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3613 OIC_LOG(ERROR, TAG, "Error deleting resource");
3614 return OC_STACK_ERROR;
3620 const char *OCGetResourceUri(OCResourceHandle handle)
3622 OCResource *resource = NULL;
3624 resource = findResource((OCResource *) handle);
3627 return resource->uri;
3629 return (const char *) NULL;
3632 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3634 OCResource *resource = NULL;
3636 resource = findResource((OCResource *) handle);
3639 return resource->resourceProperties;
3641 return (OCResourceProperty)-1;
3644 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3645 uint8_t *numResourceTypes)
3647 OCResource *resource = NULL;
3648 OCResourceType *pointer = NULL;
3650 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3651 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3653 *numResourceTypes = 0;
3655 resource = findResource((OCResource *) handle);
3658 pointer = resource->rsrcType;
3661 *numResourceTypes = *numResourceTypes + 1;
3662 pointer = pointer->next;
3668 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3670 OCResourceType *resourceType = NULL;
3672 resourceType = findResourceTypeAtIndex(handle, index);
3675 return resourceType->resourcetypename;
3677 return (const char *) NULL;
3680 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3681 uint8_t *numResourceInterfaces)
3683 OCResourceInterface *pointer = NULL;
3684 OCResource *resource = NULL;
3686 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3687 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3689 *numResourceInterfaces = 0;
3690 resource = findResource((OCResource *) handle);
3693 pointer = resource->rsrcInterface;
3696 *numResourceInterfaces = *numResourceInterfaces + 1;
3697 pointer = pointer->next;
3703 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3705 OCResourceInterface *resourceInterface = NULL;
3707 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3708 if (resourceInterface)
3710 return resourceInterface->name;
3712 return (const char *) NULL;
3715 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3718 OCResource *resource = NULL;
3719 OCChildResource *tempChildResource = NULL;
3722 resource = findResource((OCResource *) collectionHandle);
3728 tempChildResource = resource->rsrcChildResourcesHead;
3730 while(tempChildResource)
3734 return tempChildResource->rsrcResource;
3737 tempChildResource = tempChildResource->next;
3740 // In this case, the number of resource handles in the collection exceeds the index
3741 tempChildResource = NULL;
3745 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3746 OCEntityHandler entityHandler,
3747 void* callbackParam)
3749 OCResource *resource = NULL;
3751 // Validate parameters
3752 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3754 // Use the handle to find the resource in the resource linked list
3755 resource = findResource((OCResource *)handle);
3758 OIC_LOG(ERROR, TAG, "Resource not found");
3759 return OC_STACK_ERROR;
3763 resource->entityHandler = entityHandler;
3764 resource->entityHandlerCallbackParam = callbackParam;
3766 #ifdef WITH_PRESENCE
3767 if (presenceResource.handle)
3769 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3770 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3777 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3779 OCResource *resource = NULL;
3781 resource = findResource((OCResource *)handle);
3784 OIC_LOG(ERROR, TAG, "Resource not found");
3789 return resource->entityHandler;
3792 void incrementSequenceNumber(OCResource * resPtr)
3794 // Increment the sequence number
3795 resPtr->sequenceNum += 1;
3796 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3798 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3803 #ifdef WITH_PRESENCE
3804 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3805 OCPresenceTrigger trigger)
3807 OCResource *resPtr = NULL;
3808 OCStackResult result = OC_STACK_ERROR;
3809 OCMethod method = OC_REST_PRESENCE;
3810 uint32_t maxAge = 0;
3811 resPtr = findResource((OCResource *) presenceResource.handle);
3814 return OC_STACK_NO_RESOURCE;
3817 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3819 maxAge = presenceResource.presenceTTL;
3821 result = SendAllObserverNotification(method, resPtr, maxAge,
3822 trigger, resourceType, OC_LOW_QOS);
3828 OCStackResult SendStopNotification()
3830 OCResource *resPtr = NULL;
3831 OCStackResult result = OC_STACK_ERROR;
3832 OCMethod method = OC_REST_PRESENCE;
3833 resPtr = findResource((OCResource *) presenceResource.handle);
3836 return OC_STACK_NO_RESOURCE;
3839 // maxAge is 0. ResourceType is NULL.
3840 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3846 #endif // WITH_PRESENCE
3847 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3849 OCResource *resPtr = NULL;
3850 OCStackResult result = OC_STACK_ERROR;
3851 OCMethod method = OC_REST_NOMETHOD;
3852 uint32_t maxAge = 0;
3854 OIC_LOG(INFO, TAG, "Notifying all observers");
3855 #ifdef WITH_PRESENCE
3856 if(handle == presenceResource.handle)
3860 #endif // WITH_PRESENCE
3861 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3863 // Verify that the resource exists
3864 resPtr = findResource ((OCResource *) handle);
3867 return OC_STACK_NO_RESOURCE;
3871 //only increment in the case of regular observing (not presence)
3872 incrementSequenceNumber(resPtr);
3873 method = OC_REST_OBSERVE;
3874 maxAge = MAX_OBSERVE_AGE;
3875 #ifdef WITH_PRESENCE
3876 result = SendAllObserverNotification (method, resPtr, maxAge,
3877 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3879 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3886 OCNotifyListOfObservers (OCResourceHandle handle,
3887 OCObservationId *obsIdList,
3888 uint8_t numberOfIds,
3889 const OCRepPayload *payload,
3890 OCQualityOfService qos)
3892 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3894 OCResource *resPtr = NULL;
3895 //TODO: we should allow the server to define this
3896 uint32_t maxAge = MAX_OBSERVE_AGE;
3898 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3899 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3900 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3902 resPtr = findResource ((OCResource *) handle);
3903 if (NULL == resPtr || myStackMode == OC_CLIENT)
3905 return OC_STACK_NO_RESOURCE;
3909 incrementSequenceNumber(resPtr);
3911 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3912 payload, maxAge, qos));
3915 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3917 OCStackResult result = OC_STACK_ERROR;
3918 OCServerRequest *serverRequest = NULL;
3920 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
3922 // Validate input parameters
3923 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3924 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3927 // Get pointer to request info
3928 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3931 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3932 result = serverRequest->ehResponseHandler(ehResponse);
3938 //#ifdef DIRECT_PAIRING
3939 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
3941 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
3942 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
3944 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
3948 return (const OCDPDev_t*)DPGetDiscoveredDevices();
3951 const OCDPDev_t* OCGetDirectPairedDevices()
3953 return (const OCDPDev_t*)DPGetPairedDevices();
3956 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
3957 OCDirectPairingCB resultCallback)
3959 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
3960 if(NULL == peer || NULL == pinNumber)
3962 OIC_LOG(ERROR, TAG, "Invalid parameters");
3963 return OC_STACK_INVALID_PARAM;
3965 if (NULL == resultCallback)
3967 OIC_LOG(ERROR, TAG, "Invalid callback");
3968 return OC_STACK_INVALID_CALLBACK;
3971 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
3972 pinNumber, (OCDirectPairingResultCB)resultCallback);
3974 //#endif // DIRECT_PAIRING
3976 //-----------------------------------------------------------------------------
3977 // Private internal function definitions
3978 //-----------------------------------------------------------------------------
3979 static OCDoHandle GenerateInvocationHandle()
3981 OCDoHandle handle = NULL;
3982 // Generate token here, it will be deleted when the transaction is deleted
3983 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3986 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3992 #ifdef WITH_PRESENCE
3993 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3994 OCResourceProperty resourceProperties, uint8_t enable)
3998 return OC_STACK_INVALID_PARAM;
4000 if (resourceProperties
4001 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4003 OIC_LOG(ERROR, TAG, "Invalid property");
4004 return OC_STACK_INVALID_PARAM;
4008 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4012 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4018 OCStackResult initResources()
4020 OCStackResult result = OC_STACK_OK;
4022 headResource = NULL;
4023 tailResource = NULL;
4024 // Init Virtual Resources
4025 #ifdef WITH_PRESENCE
4026 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4028 result = OCCreateResource(&presenceResource.handle,
4029 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4031 OC_RSRVD_PRESENCE_URI,
4035 //make resource inactive
4036 result = OCChangeResourceProperty(
4037 &(((OCResource *) presenceResource.handle)->resourceProperties),
4040 #ifndef WITH_ARDUINO
4041 if (result == OC_STACK_OK)
4043 result = SRMInitSecureResources();
4047 if(result == OC_STACK_OK)
4049 result = OCCreateResource(&deviceResource,
4050 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4051 OC_RSRVD_INTERFACE_DEFAULT,
4052 OC_RSRVD_DEVICE_URI,
4056 if(result == OC_STACK_OK)
4058 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4059 OC_RSRVD_INTERFACE_READ);
4063 if(result == OC_STACK_OK)
4065 result = OCCreateResource(&platformResource,
4066 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4067 OC_RSRVD_INTERFACE_DEFAULT,
4068 OC_RSRVD_PLATFORM_URI,
4072 if(result == OC_STACK_OK)
4074 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4075 OC_RSRVD_INTERFACE_READ);
4082 void insertResource(OCResource *resource)
4086 headResource = resource;
4087 tailResource = resource;
4091 tailResource->next = resource;
4092 tailResource = resource;
4094 resource->next = NULL;
4097 OCResource *findResource(OCResource *resource)
4099 OCResource *pointer = headResource;
4103 if (pointer == resource)
4107 pointer = pointer->next;
4112 void deleteAllResources()
4114 OCResource *pointer = headResource;
4115 OCResource *temp = NULL;
4119 temp = pointer->next;
4120 #ifdef WITH_PRESENCE
4121 if (pointer != (OCResource *) presenceResource.handle)
4123 #endif // WITH_PRESENCE
4124 deleteResource(pointer);
4125 #ifdef WITH_PRESENCE
4127 #endif // WITH_PRESENCE
4131 SRMDeInitSecureResources();
4133 #ifdef WITH_PRESENCE
4134 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4135 // presence notification attributed to their deletion to be processed.
4136 deleteResource((OCResource *) presenceResource.handle);
4137 #endif // WITH_PRESENCE
4140 OCStackResult deleteResource(OCResource *resource)
4142 OCResource *prev = NULL;
4143 OCResource *temp = NULL;
4146 OIC_LOG(DEBUG,TAG,"resource is NULL");
4147 return OC_STACK_INVALID_PARAM;
4150 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4152 temp = headResource;
4155 if (temp == resource)
4157 // Invalidate all Resource Properties.
4158 resource->resourceProperties = (OCResourceProperty) 0;
4159 #ifdef WITH_PRESENCE
4160 if(resource != (OCResource *) presenceResource.handle)
4162 #endif // WITH_PRESENCE
4163 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4164 #ifdef WITH_PRESENCE
4167 if(presenceResource.handle)
4169 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4170 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4173 // Only resource in list.
4174 if (temp == headResource && temp == tailResource)
4176 headResource = NULL;
4177 tailResource = NULL;
4180 else if (temp == headResource)
4182 headResource = temp->next;
4185 else if (temp == tailResource)
4187 tailResource = prev;
4188 tailResource->next = NULL;
4192 prev->next = temp->next;
4195 deleteResourceElements(temp);
4206 return OC_STACK_ERROR;
4209 void deleteResourceElements(OCResource *resource)
4216 OICFree(resource->uri);
4217 deleteResourceType(resource->rsrcType);
4218 deleteResourceInterface(resource->rsrcInterface);
4221 void deleteResourceType(OCResourceType *resourceType)
4223 OCResourceType *pointer = resourceType;
4224 OCResourceType *next = NULL;
4228 next = pointer->next;
4229 OICFree(pointer->resourcetypename);
4235 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4237 OCResourceInterface *pointer = resourceInterface;
4238 OCResourceInterface *next = NULL;
4242 next = pointer->next;
4243 OICFree(pointer->name);
4249 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4251 OCResourceType *pointer = NULL;
4252 OCResourceType *previous = NULL;
4253 if (!resource || !resourceType)
4257 // resource type list is empty.
4258 else if (!resource->rsrcType)
4260 resource->rsrcType = resourceType;
4264 pointer = resource->rsrcType;
4268 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4270 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4271 OICFree(resourceType->resourcetypename);
4272 OICFree(resourceType);
4276 pointer = pointer->next;
4281 previous->next = resourceType;
4284 resourceType->next = NULL;
4286 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4289 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4291 OCResource *resource = NULL;
4292 OCResourceType *pointer = NULL;
4294 // Find the specified resource
4295 resource = findResource((OCResource *) handle);
4301 // Make sure a resource has a resourcetype
4302 if (!resource->rsrcType)
4307 // Iterate through the list
4308 pointer = resource->rsrcType;
4309 for(uint8_t i = 0; i< index && pointer; ++i)
4311 pointer = pointer->next;
4316 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4318 if(resourceTypeList && resourceTypeName)
4320 OCResourceType * rtPointer = resourceTypeList;
4321 while(resourceTypeName && rtPointer)
4323 if(rtPointer->resourcetypename &&
4324 strcmp(resourceTypeName, (const char *)
4325 (rtPointer->resourcetypename)) == 0)
4329 rtPointer = rtPointer->next;
4337 * Insert a new interface into interface linked list only if not already present.
4338 * If alredy present, 2nd arg is free'd.
4339 * Default interface will always be first if present.
4341 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4343 OCResourceInterface *pointer = NULL;
4344 OCResourceInterface *previous = NULL;
4346 newInterface->next = NULL;
4348 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4350 if (!*firstInterface)
4352 // If first interface is not oic.if.baseline, by default add it as first interface type.
4353 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4355 *firstInterface = newInterface;
4359 OCStackResult result = BindResourceInterfaceToResource(resource, OC_RSRVD_INTERFACE_DEFAULT);
4360 if (result != OC_STACK_OK)
4362 OICFree(newInterface->name);
4363 OICFree(newInterface);
4366 if (*firstInterface)
4368 (*firstInterface)->next = newInterface;
4372 // If once add oic.if.baseline, later too below code take care of freeing memory.
4373 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4375 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4377 OICFree(newInterface->name);
4378 OICFree(newInterface);
4381 // This code will not hit anymore, keeping
4384 newInterface->next = *firstInterface;
4385 *firstInterface = newInterface;
4390 pointer = *firstInterface;
4393 if (strcmp(newInterface->name, pointer->name) == 0)
4395 OICFree(newInterface->name);
4396 OICFree(newInterface);
4400 pointer = pointer->next;
4405 previous->next = newInterface;
4410 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4413 OCResource *resource = NULL;
4414 OCResourceInterface *pointer = NULL;
4416 // Find the specified resource
4417 resource = findResource((OCResource *) handle);
4423 // Make sure a resource has a resourceinterface
4424 if (!resource->rsrcInterface)
4429 // Iterate through the list
4430 pointer = resource->rsrcInterface;
4432 for (uint8_t i = 0; i < index && pointer; ++i)
4434 pointer = pointer->next;
4440 * This function splits the uri using the '?' delimiter.
4441 * "uriWithoutQuery" is the block of characters between the beginning
4442 * till the delimiter or '\0' which ever comes first.
4443 * "query" is whatever is to the right of the delimiter if present.
4444 * No delimiter sets the query to NULL.
4445 * If either are present, they will be malloc'ed into the params 2, 3.
4446 * The first param, *uri is left untouched.
4448 * NOTE: This function does not account for whitespace at the end of the uri NOR
4449 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4450 * part of the query.
4452 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4456 return OC_STACK_INVALID_URI;
4458 if(!query || !uriWithoutQuery)
4460 return OC_STACK_INVALID_PARAM;
4464 *uriWithoutQuery = NULL;
4466 size_t uriWithoutQueryLen = 0;
4467 size_t queryLen = 0;
4468 size_t uriLen = strlen(uri);
4470 char *pointerToDelimiter = strstr(uri, "?");
4472 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4473 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4475 if (uriWithoutQueryLen)
4477 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4478 if (!*uriWithoutQuery)
4482 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4486 *query = (char *) OICCalloc(queryLen + 1, 1);
4489 OICFree(*uriWithoutQuery);
4490 *uriWithoutQuery = NULL;
4493 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4499 return OC_STACK_NO_MEMORY;
4502 static const OicUuid_t* OCGetServerInstanceID(void)
4504 static bool generated = false;
4505 static OicUuid_t sid;
4511 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4513 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4520 const char* OCGetServerInstanceIDString(void)
4522 static bool generated = false;
4523 static char sidStr[UUID_STRING_SIZE];
4530 const OicUuid_t *sid = OCGetServerInstanceID();
4531 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4533 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4541 CAResult_t OCSelectNetwork()
4543 CAResult_t retResult = CA_STATUS_FAILED;
4544 CAResult_t caResult = CA_STATUS_OK;
4546 CATransportAdapter_t connTypes[] = {
4548 CA_ADAPTER_RFCOMM_BTEDR,
4549 CA_ADAPTER_GATT_BTLE,
4552 ,CA_ADAPTER_REMOTE_ACCESS
4559 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4561 for(int i = 0; i<numConnTypes; i++)
4563 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4564 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4566 caResult = CASelectNetwork(connTypes[i]);
4567 if(caResult == CA_STATUS_OK)
4569 retResult = CA_STATUS_OK;
4574 if(retResult != CA_STATUS_OK)
4576 return caResult; // Returns error of appropriate transport that failed fatally.
4582 OCStackResult CAResultToOCResult(CAResult_t caResult)
4588 case CA_STATUS_INVALID_PARAM:
4589 return OC_STACK_INVALID_PARAM;
4590 case CA_ADAPTER_NOT_ENABLED:
4591 return OC_STACK_ADAPTER_NOT_ENABLED;
4592 case CA_SERVER_STARTED_ALREADY:
4594 case CA_SERVER_NOT_STARTED:
4595 return OC_STACK_ERROR;
4596 case CA_DESTINATION_NOT_REACHABLE:
4597 return OC_STACK_COMM_ERROR;
4598 case CA_SOCKET_OPERATION_FAILED:
4599 return OC_STACK_COMM_ERROR;
4600 case CA_SEND_FAILED:
4601 return OC_STACK_COMM_ERROR;
4602 case CA_RECEIVE_FAILED:
4603 return OC_STACK_COMM_ERROR;
4604 case CA_MEMORY_ALLOC_FAILED:
4605 return OC_STACK_NO_MEMORY;
4606 case CA_REQUEST_TIMEOUT:
4607 return OC_STACK_TIMEOUT;
4608 case CA_DESTINATION_DISCONNECTED:
4609 return OC_STACK_COMM_ERROR;
4610 case CA_STATUS_FAILED:
4611 return OC_STACK_ERROR;
4612 case CA_NOT_SUPPORTED:
4613 return OC_STACK_NOTIMPL;
4615 return OC_STACK_ERROR;