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 if (result != OC_STACK_OK)
2647 OIC_LOG(ERROR, TAG, "CACreateEndpoint error");
2651 // prepare for response
2652 #ifdef WITH_PRESENCE
2653 if (method == OC_REST_PRESENCE)
2655 char *presenceUri = NULL;
2656 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2657 if (OC_STACK_OK != result)
2662 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2663 // Presence notification will form a canonical uri to
2664 // look for callbacks into the application.
2665 resourceUri = presenceUri;
2669 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2670 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2671 method, devAddr, resourceUri, resourceType, ttl);
2672 if (OC_STACK_OK != result)
2677 devAddr = NULL; // Client CB list entry now owns it
2678 resourceUri = NULL; // Client CB list entry now owns it
2679 resourceType = NULL; // Client CB list entry now owns it
2682 result = OCSendRequest(&endpoint, &requestInfo);
2683 if (OC_STACK_OK != result)
2690 *handle = resHandle;
2694 if (result != OC_STACK_OK)
2696 OIC_LOG(ERROR, TAG, "OCDoResource error");
2697 FindAndDeleteClientCB(clientCB);
2698 CADestroyToken(token);
2706 // This is the owner of the payload object, so we free it
2707 OCPayloadDestroy(payload);
2708 OICFree(requestInfo.info.payload);
2710 OICFree(resourceUri);
2711 OICFree(resourceType);
2712 OICFree(requestInfo.info.options);
2716 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2720 * This ftn is implemented one of two ways in the case of observation:
2722 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2723 * Remove the callback associated on client side.
2724 * When the next notification comes in from server,
2725 * reply with RESET message to server.
2726 * Keep in mind that the server will react to RESET only
2727 * if the last notification was sent as CON
2729 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2730 * and it is associated with an observe request
2731 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2732 * Send CON Observe request to server with
2733 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2734 * Remove the callback associated on client side.
2736 OCStackResult ret = OC_STACK_OK;
2737 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2738 CARequestInfo_t requestInfo = {.method = CA_GET};
2742 return OC_STACK_INVALID_PARAM;
2745 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2748 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2749 return OC_STACK_ERROR;
2752 switch (clientCB->method)
2754 case OC_REST_OBSERVE:
2755 case OC_REST_OBSERVE_ALL:
2757 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2759 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2761 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2763 FindAndDeleteClientCB(clientCB);
2767 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2769 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2770 requestInfo.info.token = clientCB->token;
2771 requestInfo.info.tokenLength = clientCB->tokenLength;
2773 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2774 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2776 return OC_STACK_ERROR;
2778 requestInfo.info.numOptions = numOptions + 1;
2779 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2782 ret = OCSendRequest(&endpoint, &requestInfo);
2784 if (requestInfo.info.options)
2786 OICFree (requestInfo.info.options);
2788 if (requestInfo.info.resourceUri)
2790 OICFree (requestInfo.info.resourceUri);
2795 case OC_REST_DISCOVER:
2796 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2797 clientCB->requestUri);
2798 FindAndDeleteClientCB(clientCB);
2801 #ifdef WITH_PRESENCE
2802 case OC_REST_PRESENCE:
2803 FindAndDeleteClientCB(clientCB);
2808 ret = OC_STACK_INVALID_METHOD;
2816 * @brief Register Persistent storage callback.
2817 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2819 * OC_STACK_OK - No errors; Success
2820 * OC_STACK_INVALID_PARAM - Invalid parameter
2822 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2824 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2825 if(!persistentStorageHandler)
2827 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2828 return OC_STACK_INVALID_PARAM;
2832 if( !persistentStorageHandler->open ||
2833 !persistentStorageHandler->close ||
2834 !persistentStorageHandler->read ||
2835 !persistentStorageHandler->unlink ||
2836 !persistentStorageHandler->write)
2838 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2839 return OC_STACK_INVALID_PARAM;
2842 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2845 #ifdef WITH_PRESENCE
2847 OCStackResult OCProcessPresence()
2849 OCStackResult result = OC_STACK_OK;
2851 // the following line floods the log with messages that are irrelevant
2852 // to most purposes. Uncomment as needed.
2853 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2854 ClientCB* cbNode = NULL;
2855 OCClientResponse clientResponse;
2856 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2858 LL_FOREACH(cbList, cbNode)
2860 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2865 uint32_t now = GetTicks(0);
2866 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2867 cbNode->presence->TTLlevel);
2868 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2870 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2875 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2877 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2878 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2880 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2882 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2884 clientResponse.sequenceNumber = 0;
2885 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2886 clientResponse.devAddr = *cbNode->devAddr;
2887 FixUpClientResponse(&clientResponse);
2888 clientResponse.payload = NULL;
2890 // Increment the TTLLevel (going to a next state), so we don't keep
2891 // sending presence notification to client.
2892 cbNode->presence->TTLlevel++;
2893 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2894 cbNode->presence->TTLlevel);
2896 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2897 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2899 FindAndDeleteClientCB(cbNode);
2903 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2908 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2909 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2910 CARequestInfo_t requestInfo = {.method = CA_GET};
2912 OIC_LOG(DEBUG, TAG, "time to test server presence");
2914 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2916 requestData.type = CA_MSG_NONCONFIRM;
2917 requestData.token = cbNode->token;
2918 requestData.tokenLength = cbNode->tokenLength;
2919 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2920 requestInfo.method = CA_GET;
2921 requestInfo.info = requestData;
2923 result = OCSendRequest(&endpoint, &requestInfo);
2924 if (OC_STACK_OK != result)
2929 cbNode->presence->TTLlevel++;
2930 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2933 if (result != OC_STACK_OK)
2935 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
2940 #endif // WITH_PRESENCE
2942 OCStackResult OCProcess()
2944 #ifdef WITH_PRESENCE
2945 OCProcessPresence();
2947 CAHandleRequestResponse();
2949 #ifdef ROUTING_GATEWAY
2959 #ifdef WITH_PRESENCE
2960 OCStackResult OCStartPresence(const uint32_t ttl)
2962 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2963 OCChangeResourceProperty(
2964 &(((OCResource *)presenceResource.handle)->resourceProperties),
2967 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2969 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2970 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
2974 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2975 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
2979 presenceResource.presenceTTL = ttl;
2981 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
2983 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2985 presenceState = OC_PRESENCE_INITIALIZED;
2987 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2989 CAToken_t caToken = NULL;
2990 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2991 if (caResult != CA_STATUS_OK)
2993 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2994 CADestroyToken(caToken);
2995 return OC_STACK_ERROR;
2998 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2999 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3000 CADestroyToken(caToken);
3003 // Each time OCStartPresence is called
3004 // a different random 32-bit integer number is used
3005 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3007 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3008 OC_PRESENCE_TRIGGER_CREATE);
3011 OCStackResult OCStopPresence()
3013 OCStackResult result = OC_STACK_ERROR;
3015 if(presenceResource.handle)
3017 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3019 // make resource inactive
3020 result = OCChangeResourceProperty(
3021 &(((OCResource *) presenceResource.handle)->resourceProperties),
3025 if(result != OC_STACK_OK)
3028 "Changing the presence resource properties to ACTIVE not successful");
3032 return SendStopNotification();
3036 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3037 void* callbackParameter)
3039 defaultDeviceHandler = entityHandler;
3040 defaultDeviceHandlerCallbackParameter = callbackParameter;
3045 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3047 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3049 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3051 if (validatePlatformInfo(platformInfo))
3053 return SavePlatformInfo(platformInfo);
3057 return OC_STACK_INVALID_PARAM;
3062 return OC_STACK_ERROR;
3066 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3068 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3070 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3072 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3073 return OC_STACK_INVALID_PARAM;
3076 if (deviceInfo.types)
3078 OCStringLL *type = deviceInfo.types;
3079 OCResource *resource = findResource((OCResource *) deviceResource);
3082 return OC_STACK_INVALID_PARAM;
3084 deleteResourceType(resource->rsrcType);
3085 resource->rsrcType = NULL;
3089 OCBindResourceTypeToResource(deviceResource, type->value);
3093 return SaveDeviceInfo(deviceInfo);
3096 OCStackResult OCCreateResource(OCResourceHandle *handle,
3097 const char *resourceTypeName,
3098 const char *resourceInterfaceName,
3099 const char *uri, OCEntityHandler entityHandler,
3100 void* callbackParam,
3101 uint8_t resourceProperties)
3104 OCResource *pointer = NULL;
3105 OCStackResult result = OC_STACK_ERROR;
3107 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3109 if(myStackMode == OC_CLIENT)
3111 return OC_STACK_INVALID_PARAM;
3113 // Validate parameters
3114 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3116 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3117 return OC_STACK_INVALID_URI;
3119 // Is it presented during resource discovery?
3120 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3122 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3123 return OC_STACK_INVALID_PARAM;
3126 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3128 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3131 // Make sure resourceProperties bitmask has allowed properties specified
3132 if (resourceProperties
3133 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3134 OC_EXPLICIT_DISCOVERABLE))
3136 OIC_LOG(ERROR, TAG, "Invalid property");
3137 return OC_STACK_INVALID_PARAM;
3140 // If the headResource is NULL, then no resources have been created...
3141 pointer = headResource;
3144 // At least one resources is in the resource list, so we need to search for
3145 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3148 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3150 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3151 return OC_STACK_INVALID_PARAM;
3153 pointer = pointer->next;
3156 // Create the pointer and insert it into the resource list
3157 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3160 result = OC_STACK_NO_MEMORY;
3163 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3165 insertResource(pointer);
3168 pointer->uri = OICStrdup(uri);
3171 result = OC_STACK_NO_MEMORY;
3175 // Set properties. Set OC_ACTIVE
3176 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3179 // Add the resourcetype to the resource
3180 result = BindResourceTypeToResource(pointer, resourceTypeName);
3181 if (result != OC_STACK_OK)
3183 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3187 // Add the resourceinterface to the resource
3188 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3189 if (result != OC_STACK_OK)
3191 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3195 // If an entity handler has been passed, attach it to the newly created
3196 // resource. Otherwise, set the default entity handler.
3199 pointer->entityHandler = entityHandler;
3200 pointer->entityHandlerCallbackParam = callbackParam;
3204 pointer->entityHandler = defaultResourceEHandler;
3205 pointer->entityHandlerCallbackParam = NULL;
3208 // Initialize a pointer indicating child resources in case of collection
3209 pointer->rsrcChildResourcesHead = NULL;
3212 result = OC_STACK_OK;
3214 #ifdef WITH_PRESENCE
3215 if (presenceResource.handle)
3217 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3218 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3222 if (result != OC_STACK_OK)
3224 // Deep delete of resource and other dynamic elements that it contains
3225 deleteResource(pointer);
3230 OCStackResult OCBindResource(
3231 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3233 OCResource *resource = NULL;
3234 OCChildResource *tempChildResource = NULL;
3235 OCChildResource *newChildResource = NULL;
3237 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3239 // Validate parameters
3240 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3241 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3242 // Container cannot contain itself
3243 if (collectionHandle == resourceHandle)
3245 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3246 return OC_STACK_INVALID_PARAM;
3249 // Use the handle to find the resource in the resource linked list
3250 resource = findResource((OCResource *) collectionHandle);
3253 OIC_LOG(ERROR, TAG, "Collection handle not found");
3254 return OC_STACK_INVALID_PARAM;
3257 // Look for an open slot to add add the child resource.
3258 // If found, add it and return success
3260 tempChildResource = resource->rsrcChildResourcesHead;
3262 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3264 // TODO: what if one of child resource was deregistered without unbinding?
3265 tempChildResource = tempChildResource->next;
3268 // Do memory allocation for child resource
3269 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3270 if(!newChildResource)
3272 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3273 return OC_STACK_ERROR;
3276 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3277 newChildResource->next = NULL;
3279 if(!resource->rsrcChildResourcesHead)
3281 resource->rsrcChildResourcesHead = newChildResource;
3284 tempChildResource->next = newChildResource;
3287 OIC_LOG(INFO, TAG, "resource bound");
3289 #ifdef WITH_PRESENCE
3290 if (presenceResource.handle)
3292 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3293 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3294 OC_PRESENCE_TRIGGER_CHANGE);
3301 OCStackResult OCUnBindResource(
3302 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3304 OCResource *resource = NULL;
3305 OCChildResource *tempChildResource = NULL;
3306 OCChildResource *tempLastChildResource = NULL;
3308 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3310 // Validate parameters
3311 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3312 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3313 // Container cannot contain itself
3314 if (collectionHandle == resourceHandle)
3316 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3317 return OC_STACK_INVALID_PARAM;
3320 // Use the handle to find the resource in the resource linked list
3321 resource = findResource((OCResource *) collectionHandle);
3324 OIC_LOG(ERROR, TAG, "Collection handle not found");
3325 return OC_STACK_INVALID_PARAM;
3328 // Look for an open slot to add add the child resource.
3329 // If found, add it and return success
3330 if(!resource->rsrcChildResourcesHead)
3332 OIC_LOG(INFO, TAG, "resource not found in collection");
3334 // Unable to add resourceHandle, so return error
3335 return OC_STACK_ERROR;
3339 tempChildResource = resource->rsrcChildResourcesHead;
3341 while (tempChildResource)
3343 if(tempChildResource->rsrcResource == resourceHandle)
3345 // if resource going to be unbinded is the head one.
3346 if( tempChildResource == resource->rsrcChildResourcesHead )
3348 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3349 OICFree(resource->rsrcChildResourcesHead);
3350 resource->rsrcChildResourcesHead = temp;
3355 OCChildResource *temp = tempChildResource->next;
3356 OICFree(tempChildResource);
3357 tempLastChildResource->next = temp;
3361 OIC_LOG(INFO, TAG, "resource unbound");
3363 // Send notification when resource is unbounded successfully.
3364 #ifdef WITH_PRESENCE
3365 if (presenceResource.handle)
3367 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3368 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3369 OC_PRESENCE_TRIGGER_CHANGE);
3372 tempChildResource = NULL;
3373 tempLastChildResource = NULL;
3379 tempLastChildResource = tempChildResource;
3380 tempChildResource = tempChildResource->next;
3383 OIC_LOG(INFO, TAG, "resource not found in collection");
3385 tempChildResource = NULL;
3386 tempLastChildResource = NULL;
3388 // Unable to add resourceHandle, so return error
3389 return OC_STACK_ERROR;
3392 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3394 if (!resourceItemName)
3398 // Per RFC 6690 only registered values must follow the first rule below.
3399 // At this point in time the only values registered begin with "core", and
3400 // all other values are specified as opaque strings where multiple values
3401 // are separated by a space.
3402 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3404 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3406 if (resourceItemName[index] != '.'
3407 && resourceItemName[index] != '-'
3408 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3409 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3417 for (size_t index = 0; resourceItemName[index]; ++index)
3419 if (resourceItemName[index] == ' '
3420 || resourceItemName[index] == '\t'
3421 || resourceItemName[index] == '\r'
3422 || resourceItemName[index] == '\n')
3432 OCStackResult BindResourceTypeToResource(OCResource* resource,
3433 const char *resourceTypeName)
3435 OCResourceType *pointer = NULL;
3437 OCStackResult result = OC_STACK_ERROR;
3439 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3441 if (!ValidateResourceTypeInterface(resourceTypeName))
3443 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3444 return OC_STACK_INVALID_PARAM;
3447 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3450 result = OC_STACK_NO_MEMORY;
3454 str = OICStrdup(resourceTypeName);
3457 result = OC_STACK_NO_MEMORY;
3460 pointer->resourcetypename = str;
3461 pointer->next = NULL;
3463 insertResourceType(resource, pointer);
3464 result = OC_STACK_OK;
3467 if (result != OC_STACK_OK)
3476 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3477 const char *resourceInterfaceName)
3479 OCResourceInterface *pointer = NULL;
3481 OCStackResult result = OC_STACK_ERROR;
3483 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3485 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3487 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3488 return OC_STACK_INVALID_PARAM;
3491 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3493 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3496 result = OC_STACK_NO_MEMORY;
3500 str = OICStrdup(resourceInterfaceName);
3503 result = OC_STACK_NO_MEMORY;
3506 pointer->name = str;
3508 // Bind the resourceinterface to the resource
3509 insertResourceInterface(resource, pointer);
3511 result = OC_STACK_OK;
3514 if (result != OC_STACK_OK)
3523 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3524 const char *resourceTypeName)
3527 OCStackResult result = OC_STACK_ERROR;
3528 OCResource *resource = NULL;
3530 resource = findResource((OCResource *) handle);
3533 OIC_LOG(ERROR, TAG, "Resource not found");
3534 return OC_STACK_ERROR;
3537 result = BindResourceTypeToResource(resource, resourceTypeName);
3539 #ifdef WITH_PRESENCE
3540 if(presenceResource.handle)
3542 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3543 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3550 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3551 const char *resourceInterfaceName)
3554 OCStackResult result = OC_STACK_ERROR;
3555 OCResource *resource = NULL;
3557 resource = findResource((OCResource *) handle);
3560 OIC_LOG(ERROR, TAG, "Resource not found");
3561 return OC_STACK_ERROR;
3564 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3566 #ifdef WITH_PRESENCE
3567 if (presenceResource.handle)
3569 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3570 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3577 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3579 OCResource *pointer = headResource;
3581 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3585 *numResources = *numResources + 1;
3586 pointer = pointer->next;
3591 OCResourceHandle OCGetResourceHandle(uint8_t index)
3593 OCResource *pointer = headResource;
3595 for( uint8_t i = 0; i < index && pointer; ++i)
3597 pointer = pointer->next;
3599 return (OCResourceHandle) pointer;
3602 OCStackResult OCDeleteResource(OCResourceHandle handle)
3606 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3607 return OC_STACK_INVALID_PARAM;
3610 OCResource *resource = findResource((OCResource *) handle);
3611 if (resource == NULL)
3613 OIC_LOG(ERROR, TAG, "Resource not found");
3614 return OC_STACK_NO_RESOURCE;
3617 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3619 OIC_LOG(ERROR, TAG, "Error deleting resource");
3620 return OC_STACK_ERROR;
3626 const char *OCGetResourceUri(OCResourceHandle handle)
3628 OCResource *resource = NULL;
3630 resource = findResource((OCResource *) handle);
3633 return resource->uri;
3635 return (const char *) NULL;
3638 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3640 OCResource *resource = NULL;
3642 resource = findResource((OCResource *) handle);
3645 return resource->resourceProperties;
3647 return (OCResourceProperty)-1;
3650 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3651 uint8_t *numResourceTypes)
3653 OCResource *resource = NULL;
3654 OCResourceType *pointer = NULL;
3656 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3657 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3659 *numResourceTypes = 0;
3661 resource = findResource((OCResource *) handle);
3664 pointer = resource->rsrcType;
3667 *numResourceTypes = *numResourceTypes + 1;
3668 pointer = pointer->next;
3674 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3676 OCResourceType *resourceType = NULL;
3678 resourceType = findResourceTypeAtIndex(handle, index);
3681 return resourceType->resourcetypename;
3683 return (const char *) NULL;
3686 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3687 uint8_t *numResourceInterfaces)
3689 OCResourceInterface *pointer = NULL;
3690 OCResource *resource = NULL;
3692 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3693 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3695 *numResourceInterfaces = 0;
3696 resource = findResource((OCResource *) handle);
3699 pointer = resource->rsrcInterface;
3702 *numResourceInterfaces = *numResourceInterfaces + 1;
3703 pointer = pointer->next;
3709 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3711 OCResourceInterface *resourceInterface = NULL;
3713 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3714 if (resourceInterface)
3716 return resourceInterface->name;
3718 return (const char *) NULL;
3721 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3724 OCResource *resource = NULL;
3725 OCChildResource *tempChildResource = NULL;
3728 resource = findResource((OCResource *) collectionHandle);
3734 tempChildResource = resource->rsrcChildResourcesHead;
3736 while(tempChildResource)
3740 return tempChildResource->rsrcResource;
3743 tempChildResource = tempChildResource->next;
3746 // In this case, the number of resource handles in the collection exceeds the index
3747 tempChildResource = NULL;
3751 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3752 OCEntityHandler entityHandler,
3753 void* callbackParam)
3755 OCResource *resource = NULL;
3757 // Validate parameters
3758 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3760 // Use the handle to find the resource in the resource linked list
3761 resource = findResource((OCResource *)handle);
3764 OIC_LOG(ERROR, TAG, "Resource not found");
3765 return OC_STACK_ERROR;
3769 resource->entityHandler = entityHandler;
3770 resource->entityHandlerCallbackParam = callbackParam;
3772 #ifdef WITH_PRESENCE
3773 if (presenceResource.handle)
3775 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3776 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3783 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3785 OCResource *resource = NULL;
3787 resource = findResource((OCResource *)handle);
3790 OIC_LOG(ERROR, TAG, "Resource not found");
3795 return resource->entityHandler;
3798 void incrementSequenceNumber(OCResource * resPtr)
3800 // Increment the sequence number
3801 resPtr->sequenceNum += 1;
3802 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3804 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3809 #ifdef WITH_PRESENCE
3810 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3811 OCPresenceTrigger trigger)
3813 OCResource *resPtr = NULL;
3814 OCStackResult result = OC_STACK_ERROR;
3815 OCMethod method = OC_REST_PRESENCE;
3816 uint32_t maxAge = 0;
3817 resPtr = findResource((OCResource *) presenceResource.handle);
3820 return OC_STACK_NO_RESOURCE;
3823 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3825 maxAge = presenceResource.presenceTTL;
3827 result = SendAllObserverNotification(method, resPtr, maxAge,
3828 trigger, resourceType, OC_LOW_QOS);
3834 OCStackResult SendStopNotification()
3836 OCResource *resPtr = NULL;
3837 OCStackResult result = OC_STACK_ERROR;
3838 OCMethod method = OC_REST_PRESENCE;
3839 resPtr = findResource((OCResource *) presenceResource.handle);
3842 return OC_STACK_NO_RESOURCE;
3845 // maxAge is 0. ResourceType is NULL.
3846 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3852 #endif // WITH_PRESENCE
3853 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3855 OCResource *resPtr = NULL;
3856 OCStackResult result = OC_STACK_ERROR;
3857 OCMethod method = OC_REST_NOMETHOD;
3858 uint32_t maxAge = 0;
3860 OIC_LOG(INFO, TAG, "Notifying all observers");
3861 #ifdef WITH_PRESENCE
3862 if(handle == presenceResource.handle)
3866 #endif // WITH_PRESENCE
3867 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3869 // Verify that the resource exists
3870 resPtr = findResource ((OCResource *) handle);
3873 return OC_STACK_NO_RESOURCE;
3877 //only increment in the case of regular observing (not presence)
3878 incrementSequenceNumber(resPtr);
3879 method = OC_REST_OBSERVE;
3880 maxAge = MAX_OBSERVE_AGE;
3881 #ifdef WITH_PRESENCE
3882 result = SendAllObserverNotification (method, resPtr, maxAge,
3883 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3885 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3892 OCNotifyListOfObservers (OCResourceHandle handle,
3893 OCObservationId *obsIdList,
3894 uint8_t numberOfIds,
3895 const OCRepPayload *payload,
3896 OCQualityOfService qos)
3898 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3900 OCResource *resPtr = NULL;
3901 //TODO: we should allow the server to define this
3902 uint32_t maxAge = MAX_OBSERVE_AGE;
3904 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3905 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3906 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3908 resPtr = findResource ((OCResource *) handle);
3909 if (NULL == resPtr || myStackMode == OC_CLIENT)
3911 return OC_STACK_NO_RESOURCE;
3915 incrementSequenceNumber(resPtr);
3917 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3918 payload, maxAge, qos));
3921 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3923 OCStackResult result = OC_STACK_ERROR;
3924 OCServerRequest *serverRequest = NULL;
3926 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
3928 // Validate input parameters
3929 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3930 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3933 // Get pointer to request info
3934 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3937 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3938 result = serverRequest->ehResponseHandler(ehResponse);
3944 //#ifdef DIRECT_PAIRING
3945 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
3947 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
3948 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
3950 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
3954 return (const OCDPDev_t*)DPGetDiscoveredDevices();
3957 const OCDPDev_t* OCGetDirectPairedDevices()
3959 return (const OCDPDev_t*)DPGetPairedDevices();
3962 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
3963 OCDirectPairingCB resultCallback)
3965 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
3966 if(NULL == peer || NULL == pinNumber)
3968 OIC_LOG(ERROR, TAG, "Invalid parameters");
3969 return OC_STACK_INVALID_PARAM;
3971 if (NULL == resultCallback)
3973 OIC_LOG(ERROR, TAG, "Invalid callback");
3974 return OC_STACK_INVALID_CALLBACK;
3977 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
3978 pinNumber, (OCDirectPairingResultCB)resultCallback);
3980 //#endif // DIRECT_PAIRING
3982 //-----------------------------------------------------------------------------
3983 // Private internal function definitions
3984 //-----------------------------------------------------------------------------
3985 static OCDoHandle GenerateInvocationHandle()
3987 OCDoHandle handle = NULL;
3988 // Generate token here, it will be deleted when the transaction is deleted
3989 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3992 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3998 #ifdef WITH_PRESENCE
3999 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4000 OCResourceProperty resourceProperties, uint8_t enable)
4004 return OC_STACK_INVALID_PARAM;
4006 if (resourceProperties
4007 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4009 OIC_LOG(ERROR, TAG, "Invalid property");
4010 return OC_STACK_INVALID_PARAM;
4014 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4018 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4024 OCStackResult initResources()
4026 OCStackResult result = OC_STACK_OK;
4028 headResource = NULL;
4029 tailResource = NULL;
4030 // Init Virtual Resources
4031 #ifdef WITH_PRESENCE
4032 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4034 result = OCCreateResource(&presenceResource.handle,
4035 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4037 OC_RSRVD_PRESENCE_URI,
4041 //make resource inactive
4042 result = OCChangeResourceProperty(
4043 &(((OCResource *) presenceResource.handle)->resourceProperties),
4046 #ifndef WITH_ARDUINO
4047 if (result == OC_STACK_OK)
4049 result = SRMInitSecureResources();
4053 if(result == OC_STACK_OK)
4055 result = OCCreateResource(&deviceResource,
4056 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4057 OC_RSRVD_INTERFACE_DEFAULT,
4058 OC_RSRVD_DEVICE_URI,
4062 if(result == OC_STACK_OK)
4064 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4065 OC_RSRVD_INTERFACE_READ);
4069 if(result == OC_STACK_OK)
4071 result = OCCreateResource(&platformResource,
4072 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4073 OC_RSRVD_INTERFACE_DEFAULT,
4074 OC_RSRVD_PLATFORM_URI,
4078 if(result == OC_STACK_OK)
4080 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4081 OC_RSRVD_INTERFACE_READ);
4088 void insertResource(OCResource *resource)
4092 headResource = resource;
4093 tailResource = resource;
4097 tailResource->next = resource;
4098 tailResource = resource;
4100 resource->next = NULL;
4103 OCResource *findResource(OCResource *resource)
4105 OCResource *pointer = headResource;
4109 if (pointer == resource)
4113 pointer = pointer->next;
4118 void deleteAllResources()
4120 OCResource *pointer = headResource;
4121 OCResource *temp = NULL;
4125 temp = pointer->next;
4126 #ifdef WITH_PRESENCE
4127 if (pointer != (OCResource *) presenceResource.handle)
4129 #endif // WITH_PRESENCE
4130 deleteResource(pointer);
4131 #ifdef WITH_PRESENCE
4133 #endif // WITH_PRESENCE
4137 SRMDeInitSecureResources();
4139 #ifdef WITH_PRESENCE
4140 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4141 // presence notification attributed to their deletion to be processed.
4142 deleteResource((OCResource *) presenceResource.handle);
4143 #endif // WITH_PRESENCE
4146 OCStackResult deleteResource(OCResource *resource)
4148 OCResource *prev = NULL;
4149 OCResource *temp = NULL;
4152 OIC_LOG(DEBUG,TAG,"resource is NULL");
4153 return OC_STACK_INVALID_PARAM;
4156 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4158 temp = headResource;
4161 if (temp == resource)
4163 // Invalidate all Resource Properties.
4164 resource->resourceProperties = (OCResourceProperty) 0;
4165 #ifdef WITH_PRESENCE
4166 if(resource != (OCResource *) presenceResource.handle)
4168 #endif // WITH_PRESENCE
4169 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4170 #ifdef WITH_PRESENCE
4173 if(presenceResource.handle)
4175 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4176 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4179 // Only resource in list.
4180 if (temp == headResource && temp == tailResource)
4182 headResource = NULL;
4183 tailResource = NULL;
4186 else if (temp == headResource)
4188 headResource = temp->next;
4191 else if (temp == tailResource)
4193 tailResource = prev;
4194 tailResource->next = NULL;
4198 prev->next = temp->next;
4201 deleteResourceElements(temp);
4212 return OC_STACK_ERROR;
4215 void deleteResourceElements(OCResource *resource)
4222 OICFree(resource->uri);
4223 deleteResourceType(resource->rsrcType);
4224 deleteResourceInterface(resource->rsrcInterface);
4227 void deleteResourceType(OCResourceType *resourceType)
4229 OCResourceType *pointer = resourceType;
4230 OCResourceType *next = NULL;
4234 next = pointer->next;
4235 OICFree(pointer->resourcetypename);
4241 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4243 OCResourceInterface *pointer = resourceInterface;
4244 OCResourceInterface *next = NULL;
4248 next = pointer->next;
4249 OICFree(pointer->name);
4255 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4257 OCResourceType *pointer = NULL;
4258 OCResourceType *previous = NULL;
4259 if (!resource || !resourceType)
4263 // resource type list is empty.
4264 else if (!resource->rsrcType)
4266 resource->rsrcType = resourceType;
4270 pointer = resource->rsrcType;
4274 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4276 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4277 OICFree(resourceType->resourcetypename);
4278 OICFree(resourceType);
4282 pointer = pointer->next;
4287 previous->next = resourceType;
4290 resourceType->next = NULL;
4292 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4295 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4297 OCResource *resource = NULL;
4298 OCResourceType *pointer = NULL;
4300 // Find the specified resource
4301 resource = findResource((OCResource *) handle);
4307 // Make sure a resource has a resourcetype
4308 if (!resource->rsrcType)
4313 // Iterate through the list
4314 pointer = resource->rsrcType;
4315 for(uint8_t i = 0; i< index && pointer; ++i)
4317 pointer = pointer->next;
4322 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4324 if(resourceTypeList && resourceTypeName)
4326 OCResourceType * rtPointer = resourceTypeList;
4327 while(resourceTypeName && rtPointer)
4329 if(rtPointer->resourcetypename &&
4330 strcmp(resourceTypeName, (const char *)
4331 (rtPointer->resourcetypename)) == 0)
4335 rtPointer = rtPointer->next;
4343 * Insert a new interface into interface linked list only if not already present.
4344 * If alredy present, 2nd arg is free'd.
4345 * Default interface will always be first if present.
4347 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4349 OCResourceInterface *pointer = NULL;
4350 OCResourceInterface *previous = NULL;
4352 newInterface->next = NULL;
4354 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4356 if (!*firstInterface)
4358 // If first interface is not oic.if.baseline, by default add it as first interface type.
4359 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4361 *firstInterface = newInterface;
4365 OCStackResult result = BindResourceInterfaceToResource(resource, OC_RSRVD_INTERFACE_DEFAULT);
4366 if (result != OC_STACK_OK)
4368 OICFree(newInterface->name);
4369 OICFree(newInterface);
4372 if (*firstInterface)
4374 (*firstInterface)->next = newInterface;
4378 // If once add oic.if.baseline, later too below code take care of freeing memory.
4379 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4381 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4383 OICFree(newInterface->name);
4384 OICFree(newInterface);
4387 // This code will not hit anymore, keeping
4390 newInterface->next = *firstInterface;
4391 *firstInterface = newInterface;
4396 pointer = *firstInterface;
4399 if (strcmp(newInterface->name, pointer->name) == 0)
4401 OICFree(newInterface->name);
4402 OICFree(newInterface);
4406 pointer = pointer->next;
4408 previous->next = newInterface;
4412 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4415 OCResource *resource = NULL;
4416 OCResourceInterface *pointer = NULL;
4418 // Find the specified resource
4419 resource = findResource((OCResource *) handle);
4425 // Make sure a resource has a resourceinterface
4426 if (!resource->rsrcInterface)
4431 // Iterate through the list
4432 pointer = resource->rsrcInterface;
4434 for (uint8_t i = 0; i < index && pointer; ++i)
4436 pointer = pointer->next;
4442 * This function splits the uri using the '?' delimiter.
4443 * "uriWithoutQuery" is the block of characters between the beginning
4444 * till the delimiter or '\0' which ever comes first.
4445 * "query" is whatever is to the right of the delimiter if present.
4446 * No delimiter sets the query to NULL.
4447 * If either are present, they will be malloc'ed into the params 2, 3.
4448 * The first param, *uri is left untouched.
4450 * NOTE: This function does not account for whitespace at the end of the uri NOR
4451 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4452 * part of the query.
4454 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4458 return OC_STACK_INVALID_URI;
4460 if(!query || !uriWithoutQuery)
4462 return OC_STACK_INVALID_PARAM;
4466 *uriWithoutQuery = NULL;
4468 size_t uriWithoutQueryLen = 0;
4469 size_t queryLen = 0;
4470 size_t uriLen = strlen(uri);
4472 char *pointerToDelimiter = strstr(uri, "?");
4474 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4475 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4477 if (uriWithoutQueryLen)
4479 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4480 if (!*uriWithoutQuery)
4484 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4488 *query = (char *) OICCalloc(queryLen + 1, 1);
4491 OICFree(*uriWithoutQuery);
4492 *uriWithoutQuery = NULL;
4495 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4501 return OC_STACK_NO_MEMORY;
4504 static const OicUuid_t* OCGetServerInstanceID(void)
4506 static bool generated = false;
4507 static OicUuid_t sid;
4513 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4515 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4522 const char* OCGetServerInstanceIDString(void)
4524 static bool generated = false;
4525 static char sidStr[UUID_STRING_SIZE];
4532 const OicUuid_t *sid = OCGetServerInstanceID();
4533 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4535 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4543 CAResult_t OCSelectNetwork()
4545 CAResult_t retResult = CA_STATUS_FAILED;
4546 CAResult_t caResult = CA_STATUS_OK;
4548 CATransportAdapter_t connTypes[] = {
4550 CA_ADAPTER_RFCOMM_BTEDR,
4551 CA_ADAPTER_GATT_BTLE,
4554 ,CA_ADAPTER_REMOTE_ACCESS
4561 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4563 for(int i = 0; i<numConnTypes; i++)
4565 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4566 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4568 caResult = CASelectNetwork(connTypes[i]);
4569 if(caResult == CA_STATUS_OK)
4571 retResult = CA_STATUS_OK;
4576 if(retResult != CA_STATUS_OK)
4578 return caResult; // Returns error of appropriate transport that failed fatally.
4584 OCStackResult CAResultToOCResult(CAResult_t caResult)
4590 case CA_STATUS_INVALID_PARAM:
4591 return OC_STACK_INVALID_PARAM;
4592 case CA_ADAPTER_NOT_ENABLED:
4593 return OC_STACK_ADAPTER_NOT_ENABLED;
4594 case CA_SERVER_STARTED_ALREADY:
4596 case CA_SERVER_NOT_STARTED:
4597 return OC_STACK_ERROR;
4598 case CA_DESTINATION_NOT_REACHABLE:
4599 return OC_STACK_COMM_ERROR;
4600 case CA_SOCKET_OPERATION_FAILED:
4601 return OC_STACK_COMM_ERROR;
4602 case CA_SEND_FAILED:
4603 return OC_STACK_COMM_ERROR;
4604 case CA_RECEIVE_FAILED:
4605 return OC_STACK_COMM_ERROR;
4606 case CA_MEMORY_ALLOC_FAILED:
4607 return OC_STACK_NO_MEMORY;
4608 case CA_REQUEST_TIMEOUT:
4609 return OC_STACK_TIMEOUT;
4610 case CA_DESTINATION_DISCONNECTED:
4611 return OC_STACK_COMM_ERROR;
4612 case CA_STATUS_FAILED:
4613 return OC_STACK_ERROR;
4614 case CA_NOT_SUPPORTED:
4615 return OC_STACK_NOTIMPL;
4617 return OC_STACK_ERROR;