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
37 #include "ocstackinternal.h"
38 #include "ocresourcehandler.h"
39 #include "occlientcb.h"
40 #include "ocobserve.h"
42 #include "oic_malloc.h"
43 #include "oic_string.h"
44 #include "ocserverrequest.h"
45 #include "secureresourcemanager.h"
47 #include "cainterface.h"
48 #include "ocpayload.h"
49 #include "ocpayloadcbor.h"
56 #include "coap_time.h"
61 #include <arpa/inet.h>
65 #define UINT32_MAX (0xFFFFFFFFUL)
68 //-----------------------------------------------------------------------------
70 //-----------------------------------------------------------------------------
73 OC_STACK_UNINITIALIZED = 0,
75 OC_STACK_UNINIT_IN_PROGRESS
81 OC_PRESENCE_UNINITIALIZED = 0,
82 OC_PRESENCE_INITIALIZED
86 //-----------------------------------------------------------------------------
88 //-----------------------------------------------------------------------------
89 static OCStackState stackState = OC_STACK_UNINITIALIZED;
91 OCResource *headResource = NULL;
92 static OCResource *tailResource = NULL;
94 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
95 static PresenceResource presenceResource;
96 static uint8_t PresenceTimeOutSize = 0;
97 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
100 static OCMode myStackMode;
101 OCDeviceEntityHandler defaultDeviceHandler;
102 void* defaultDeviceHandlerCallbackParameter = NULL;
104 //-----------------------------------------------------------------------------
106 //-----------------------------------------------------------------------------
107 #define TAG PCF("OCStack")
108 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
109 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
110 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
111 TAG, PCF(#arg " is NULL")); return (retVal); } }
112 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OC_LOG((logLevel), \
113 TAG, PCF(#arg " is NULL")); return; } }
114 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
117 //TODO: we should allow the server to define this
118 #define MAX_OBSERVE_AGE (0x2FFFFUL)
120 #define MILLISECONDS_PER_SECOND (1000)
122 //-----------------------------------------------------------------------------
123 // Private internal function prototypes
124 //-----------------------------------------------------------------------------
127 * Generate handle of OCDoResource invocation for callback management.
129 * @return Generated OCDoResource handle.
131 static OCDoHandle GenerateInvocationHandle();
134 * Initialize resource data structures, variables, etc.
136 * @return ::OC_STACK_OK on success, some other value upon failure.
138 static OCStackResult initResources();
141 * Add a resource to the end of the linked list of resources.
143 * @param resource Resource to be added
145 static void insertResource(OCResource *resource);
148 * Find a resource in the linked list of resources.
150 * @param resource Resource to be found.
151 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
154 static OCResource *findResource(OCResource *resource);
157 * Insert a resource type into a resource's resource type linked list.
158 * If resource type already exists, it will not be inserted and the
159 * resourceType will be free'd.
160 * resourceType->next should be null to avoid memory leaks.
161 * Function returns silently for null args.
163 * @param resource Resource where resource type is to be inserted.
164 * @param resourceType Resource type to be inserted.
166 static void insertResourceType(OCResource *resource,
167 OCResourceType *resourceType);
170 * Get a resource type at the specified index within a resource.
172 * @param handle Handle of resource.
173 * @param index Index of resource type.
175 * @return Pointer to resource type if found, NULL otherwise.
177 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
181 * Insert a resource interface into a resource's resource interface linked list.
182 * If resource interface already exists, it will not be inserted and the
183 * resourceInterface will be free'd.
184 * resourceInterface->next should be null to avoid memory leaks.
186 * @param resource Resource where resource interface is to be inserted.
187 * @param resourceInterface Resource interface to be inserted.
189 static void insertResourceInterface(OCResource *resource,
190 OCResourceInterface *resourceInterface);
193 * Get a resource interface at the specified index within a resource.
195 * @param handle Handle of resource.
196 * @param index Index of resource interface.
198 * @return Pointer to resource interface if found, NULL otherwise.
200 static OCResourceInterface *findResourceInterfaceAtIndex(
201 OCResourceHandle handle, uint8_t index);
204 * Delete all of the dynamically allocated elements that were created for the resource type.
206 * @param resourceType Specified resource type.
208 static void deleteResourceType(OCResourceType *resourceType);
211 * Delete all of the dynamically allocated elements that were created for the resource interface.
213 * @param resourceInterface Specified resource interface.
215 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
218 * Delete all of the dynamically allocated elements that were created for the resource.
220 * @param resource Specified resource.
222 static void deleteResourceElements(OCResource *resource);
225 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
228 * @param handle Handle of resource to be deleted.
230 * @return ::OC_STACK_OK on success, some other value upon failure.
232 static OCStackResult deleteResource(OCResource *resource);
235 * Delete all of the resources in the resource list.
237 static void deleteAllResources();
240 * Increment resource sequence number. Handles rollover.
242 * @param resPtr Pointer to resource.
244 static void incrementSequenceNumber(OCResource * resPtr);
247 * Verify the lengths of the URI and the query separately.
249 * @param inputUri Input URI and query.
250 * @param uriLen The length of the initial URI with query.
251 * @return ::OC_STACK_OK on success, some other value upon failure.
253 static OCStackResult verifyUriQueryLength(const char * inputUri,
257 * Attempts to initialize every network interface that the CA Layer might have compiled in.
259 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
260 * return something other than @ref CA_STATUS_OK, then this function fails.
262 * @return ::CA_STATUS_OK on success, some other value upon failure.
264 static CAResult_t OCSelectNetwork();
267 * Get the CoAP ticks after the specified number of milli-seconds.
269 * @param afterMilliSeconds Milli-seconds.
273 static uint32_t GetTicks(uint32_t afterMilliSeconds);
276 * Convert CAResponseResult_t to OCStackResult.
278 * @param caCode CAResponseResult_t code.
279 * @return ::OC_STACK_OK on success, some other value upon failure.
281 static OCStackResult CAToOCStackResult(CAResponseResult_t caCode);
284 * Convert OCStackResult to CAResponseResult_t.
286 * @param caCode OCStackResult code.
287 * @return ::CA_SUCCESS on success, some other value upon failure.
289 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode);
292 * Convert OCTransportFlags_t to CATransportModifiers_t.
294 * @param ocConType OCTransportFlags_t input.
295 * @return CATransportFlags
297 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
300 * Convert CATransportFlags_t to OCTransportModifiers_t.
302 * @param caConType CATransportFlags_t input.
303 * @return OCTransportFlags
305 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
308 * Handle response from presence request.
310 * @param endPoint CA remote endpoint.
311 * @param responseInfo CA response info.
312 * @return ::OC_STACK_OK on success, some other value upon failure.
314 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
315 const CAResponseInfo_t *responseInfo);
318 * This function will be called back by CA layer when a response is received.
320 * @param endPoint CA remote endpoint.
321 * @param responseInfo CA response info.
323 static void HandleCAResponses(const CAEndpoint_t* endPoint,
324 const CAResponseInfo_t* responseInfo);
327 * This function will be called back by CA layer when a request is received.
329 * @param endPoint CA remote endpoint.
330 * @param requestInfo CA request info.
332 static void HandleCARequests(const CAEndpoint_t* endPoint,
333 const CARequestInfo_t* requestInfo);
336 * Extract query from a URI.
338 * @param uri Full URI with query.
339 * @param query Pointer to string that will contain query.
340 * @param newURI Pointer to string that will contain URI.
341 * @return ::OC_STACK_OK on success, some other value upon failure.
343 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
346 * Finds a resource type in an OCResourceType link-list.
348 * @param resourceTypeList The link-list to be searched through.
349 * @param resourceTypeName The key to search for.
351 * @return Resource type that matches the key (ie. resourceTypeName) or
352 * NULL if there is either an invalid parameter or this function was unable to find the key.
354 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
355 const char * resourceTypeName);
358 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
359 * TTL will be set to maxAge.
361 * @param cbNode Callback Node for which presence ttl is to be reset.
362 * @param maxAge New value of ttl in seconds.
364 * @return ::OC_STACK_OK on success, some other value upon failure.
366 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
368 //-----------------------------------------------------------------------------
369 // Internal functions
370 //-----------------------------------------------------------------------------
372 uint32_t GetTicks(uint32_t afterMilliSeconds)
377 // Guard against overflow of uint32_t
378 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
379 COAP_TICKS_PER_SECOND)
381 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
389 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
391 VERIFY_NON_NULL_NR(in, FATAL);
392 VERIFY_NON_NULL_NR(out, FATAL);
394 out->adapter = (OCTransportAdapter)in->adapter;
395 out->flags = CAToOCTransportFlags(in->flags);
396 strncpy(out->addr, in->addr, MAX_ADDR_STR_SIZE);
397 out->addr[MAX_ADDR_STR_SIZE - 1] = '\0';
398 out->port = in->port;
401 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
403 VERIFY_NON_NULL_NR(in, FATAL);
404 VERIFY_NON_NULL_NR(out, FATAL);
406 out->adapter = (CATransportAdapter_t)in->adapter;
407 out->flags = OCToCATransportFlags(in->flags);
408 strncpy(out->addr, in->addr, MAX_ADDR_STR_SIZE);
409 out->port = in->port;
412 static OCStackResult OCCreateEndpoint(OCDevAddr *devAddr, CAEndpoint_t **endpoint)
414 VERIFY_NON_NULL(devAddr, FATAL, OC_STACK_INVALID_PARAM);
415 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
417 CAEndpoint_t *ep = (CAEndpoint_t *)OICMalloc(sizeof (CAEndpoint_t));
420 return OC_STACK_NO_MEMORY;
423 ep->adapter = (CATransportAdapter_t)devAddr->adapter;
424 ep->flags = OCToCATransportFlags(devAddr->flags);
425 strncpy(ep->addr, devAddr->addr, MAX_ADDR_STR_SIZE_CA);
426 ep->port = devAddr->port;
433 static void OCDestroyEndpoint(CAEndpoint_t *endpoint)
438 void FixUpClientResponse(OCClientResponse *cr)
440 VERIFY_NON_NULL_NR(cr, FATAL);
442 cr->addr = &cr->devAddr;
443 cr->connType = (OCConnectivityType)
444 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
447 //-----------------------------------------------------------------------------
448 // Internal API function
449 //-----------------------------------------------------------------------------
451 // This internal function is called to update the stack with the status of
452 // observers and communication failures
453 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
455 OCStackResult result = OC_STACK_ERROR;
456 ResourceObserver * observer = NULL;
457 OCEntityHandlerRequest ehRequest = {};
461 case OC_OBSERVER_NOT_INTERESTED:
462 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
463 observer = GetObserverUsingToken (token, tokenLength);
466 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
467 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0, 0,
468 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
469 if(result != OC_STACK_OK)
473 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
474 observer->resource->entityHandlerCallbackParam);
476 //observer is not observing anymore
477 result = DeleteObserverUsingToken (token, tokenLength);
478 if(result == OC_STACK_OK)
480 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
484 result = OC_STACK_OK;
485 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
488 case OC_OBSERVER_STILL_INTERESTED:
489 //observer is still interested
490 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
491 notifications, reset the failedCount"));
492 observer = GetObserverUsingToken (token, tokenLength);
495 observer->forceHighQos = 0;
496 observer->failedCommCount = 0;
497 result = OC_STACK_OK;
501 result = OC_STACK_OBSERVER_NOT_FOUND;
504 case OC_OBSERVER_FAILED_COMM:
505 //observer is not reachable
506 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
507 observer = GetObserverUsingToken (token, tokenLength);
510 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
512 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
513 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0, 0,
514 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
515 if(result != OC_STACK_OK)
517 return OC_STACK_ERROR;
519 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
520 observer->resource->entityHandlerCallbackParam);
521 //observer is unreachable
522 result = DeleteObserverUsingToken (token, tokenLength);
523 if(result == OC_STACK_OK)
525 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
529 result = OC_STACK_OK;
530 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
535 observer->failedCommCount++;
536 result = OC_STACK_CONTINUE;
538 observer->forceHighQos = 1;
539 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
543 OC_LOG(ERROR, TAG, PCF("Unknown status"));
544 result = OC_STACK_ERROR;
549 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
551 OCStackResult ret = OC_STACK_ERROR;
559 ret = OC_STACK_RESOURCE_CREATED;
562 ret = OC_STACK_RESOURCE_DELETED;
565 ret = OC_STACK_INVALID_QUERY;
568 ret = OC_STACK_INVALID_OPTION;
571 ret = OC_STACK_NO_RESOURCE;
573 case CA_RETRANSMIT_TIMEOUT:
574 ret = OC_STACK_COMM_ERROR;
582 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode)
584 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
591 case OC_STACK_RESOURCE_CREATED:
594 case OC_STACK_RESOURCE_DELETED:
597 case OC_STACK_INVALID_QUERY:
600 case OC_STACK_INVALID_OPTION:
603 case OC_STACK_NO_RESOURCE:
606 case OC_STACK_COMM_ERROR:
607 ret = CA_RETRANSMIT_TIMEOUT;
615 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
617 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
619 // supply default behavior.
620 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
622 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
624 if ((caFlags & OC_MASK_SCOPE) == 0)
626 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
631 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
633 return (OCTransportFlags)caFlags;
636 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
638 uint32_t lowerBound = 0;
639 uint32_t higherBound = 0;
641 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
643 return OC_STACK_INVALID_PARAM;
646 OC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
648 cbNode->presence->TTL = maxAgeSeconds;
650 for(int index = 0; index < PresenceTimeOutSize; index++)
652 // Guard against overflow
653 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
656 lowerBound = GetTicks((PresenceTimeOut[index] *
657 cbNode->presence->TTL *
658 MILLISECONDS_PER_SECOND)/100);
662 lowerBound = GetTicks(UINT32_MAX);
665 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
668 higherBound = GetTicks((PresenceTimeOut[index + 1] *
669 cbNode->presence->TTL *
670 MILLISECONDS_PER_SECOND)/100);
674 higherBound = GetTicks(UINT32_MAX);
677 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
679 OC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
680 OC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
681 OC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
684 cbNode->presence->TTLlevel = 0;
686 OC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
690 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
692 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
694 return OC_RSRVD_TRIGGER_CREATE;
696 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
698 return OC_RSRVD_TRIGGER_CHANGE;
702 return OC_RSRVD_TRIGGER_DELETE;
706 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
708 if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
710 return OC_PRESENCE_TRIGGER_CREATE;
712 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
714 return OC_PRESENCE_TRIGGER_CHANGE;
718 return OC_PRESENCE_TRIGGER_DELETE;
723 * The cononical presence allows constructed URIs to be string compared.
725 * requestUri must be a char array of size CA_MAX_URI_LENGTH
727 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
730 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
731 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
732 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
736 if (endpoint->flags & CA_IPV6)
738 format = "coap://[%s]:%u%s";
742 format = "coap://%s:%u%s";
745 return snprintf(presenceUri, CA_MAX_URI_LENGTH, format, endpoint->addr,
746 endpoint->port, OC_RSRVD_PRESENCE_URI);
750 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
751 const CAResponseInfo_t *responseInfo)
753 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
754 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
756 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
757 ClientCB * cbNode = NULL;
758 char *resourceTypeName = NULL;
759 OCClientResponse response;
760 OCStackResult result = OC_STACK_ERROR;
763 char presenceUri[CA_MAX_URI_LENGTH];
765 int presenceSubscribe = 0;
766 int multicastPresenceSubscribe = 0;
768 if (responseInfo->result != CA_SUCCESS)
770 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
771 return OC_STACK_ERROR;
774 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
775 if (uriLen < 0 || uriLen >= sizeof (presenceUri))
777 return OC_STACK_INVALID_URI;
780 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
783 presenceSubscribe = 1;
787 snprintf (presenceUri, MAX_URI_LENGTH, "coap://[%s]:%u%s", OC_MULTICAST_IP,
788 OC_MULTICAST_PORT, OC_RSRVD_PRESENCE_URI);
789 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
792 multicastPresenceSubscribe = 1;
796 if (!presenceSubscribe && !multicastPresenceSubscribe)
798 OC_LOG(ERROR, TAG, PCF("Received a presence notification, but no callback, ignoring"));
802 response.payload = NULL;
803 response.result = OC_STACK_OK;
805 CopyEndpointToDevAddr(endpoint, &response.devAddr);
806 FixUpClientResponse(&response);
808 if (responseInfo->info.payload)
810 result = OCParsePayload(&response.payload, responseInfo->info.payload,
811 responseInfo->info.payloadSize);
813 if(result != OC_STACK_OK || response.payload->type != PAYLOAD_TYPE_PRESENCE)
815 OC_LOG(ERROR, TAG, PCF("Presence parse failed"));
818 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
819 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
820 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
823 if (presenceSubscribe)
825 if(cbNode->sequenceNumber == response.sequenceNumber)
827 OC_LOG(INFO, TAG, PCF("No presence change"));
833 OC_LOG(INFO, TAG, PCF("Stopping presence"));
834 response.result = OC_STACK_PRESENCE_STOPPED;
837 OICFree(cbNode->presence->timeOut);
838 OICFree(cbNode->presence);
839 cbNode->presence = NULL;
844 if(!cbNode->presence)
846 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
848 if(!(cbNode->presence))
850 OC_LOG(ERROR, TAG, PCF("Could not allocate memory for cbNode->presence"));
851 result = OC_STACK_NO_MEMORY;
855 VERIFY_NON_NULL_V(cbNode->presence);
856 cbNode->presence->timeOut = NULL;
857 cbNode->presence->timeOut = (uint32_t *)
858 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
859 if(!(cbNode->presence->timeOut)){
861 PCF("Could not allocate memory for cbNode->presence->timeOut"));
862 OICFree(cbNode->presence);
863 result = OC_STACK_NO_MEMORY;
868 ResetPresenceTTL(cbNode, maxAge);
870 cbNode->sequenceNumber = response.sequenceNumber;
872 // Ensure that a filter is actually applied.
873 if( resourceTypeName && cbNode->filterResourceType)
875 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
884 // This is the multicast case
885 OCMulticastNode* mcNode = NULL;
886 mcNode = GetMCPresenceNode(presenceUri);
890 if(mcNode->nonce == response.sequenceNumber)
892 OC_LOG(INFO, TAG, PCF("No presence change (Multicast)"));
895 mcNode->nonce = response.sequenceNumber;
899 OC_LOG(INFO, TAG, PCF("Stopping presence"));
900 response.result = OC_STACK_PRESENCE_STOPPED;
905 char* uri = OICStrdup(presenceUri);
909 PCF("No Memory for URI to store in the presence node"));
910 result = OC_STACK_NO_MEMORY;
914 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
915 if(result == OC_STACK_NO_MEMORY)
918 PCF("No Memory for Multicast Presence Node"));
922 // presence node now owns uri
925 // Ensure that a filter is actually applied.
926 if(resourceTypeName && cbNode->filterResourceType)
928 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
935 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
937 if (cbResult == OC_STACK_DELETE_TRANSACTION)
939 FindAndDeleteClientCB(cbNode);
943 OICFree(resourceTypeName);
947 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
949 VERIFY_NON_NULL_NR(endPoint, FATAL);
950 VERIFY_NON_NULL_NR(responseInfo, FATAL);
951 VERIFY_NON_NULL_NR(responseInfo->info.resourceUri, FATAL);
952 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
954 if(strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
956 HandlePresenceResponse(endPoint, responseInfo);
960 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
961 responseInfo->info.tokenLength, NULL, NULL);
962 OC_LOG(DEBUG, TAG, PCF("Response has the token:"));
963 OC_LOG_BUFFER(DEBUG, TAG, (const uint8_t*)responseInfo->info.token, responseInfo->info.tokenLength);
964 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
965 responseInfo->info.tokenLength);
969 OC_LOG(INFO, TAG, PCF("There is a cbNode associated with the response token"));
970 if(responseInfo->result == CA_EMPTY)
972 OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
973 // We do not have a case for the client to receive a RESET
974 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
976 //This is the case of receiving an ACK on a request to a slow resource!
977 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
978 //TODO: should we inform the client
979 // app that at least the request was received at the server?
982 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
984 OC_LOG(INFO, TAG, PCF("Receiving A Timeout for this token"));
985 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
987 OCClientResponse response = {};
988 CopyEndpointToDevAddr(endPoint, &response.devAddr);
989 FixUpClientResponse(&response);
990 response.resourceUri = responseInfo->info.resourceUri;
992 response.result = CAToOCStackResult(responseInfo->result);
993 cbNode->callBack(cbNode->context,
994 cbNode->handle, &response);
995 FindAndDeleteClientCB(cbNode);
999 OC_LOG(INFO, TAG, PCF("This is a regular response, A client call back is found"));
1000 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1002 OCClientResponse response = {};
1003 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1004 FixUpClientResponse(&response);
1005 response.resourceUri = responseInfo->info.resourceUri;
1007 response.result = CAToOCStackResult(responseInfo->result);
1008 if(responseInfo->info.payload &&
1009 responseInfo->info.payloadSize &&
1010 OC_STACK_OK != OCParsePayload(&response.payload, responseInfo->info.payload,
1011 responseInfo->info.payloadSize))
1013 OC_LOG(ERROR, TAG, PCF("Error converting payload"));
1017 response.numRcvdVendorSpecificHeaderOptions = 0;
1018 if(responseInfo->info.numOptions > 0)
1021 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1022 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1024 memcpy (&(response.sequenceNumber),
1025 &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
1026 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1031 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1034 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1036 OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
1040 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1042 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1043 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1047 if (cbNode->method == OC_REST_OBSERVE &&
1048 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1049 response.sequenceNumber <= cbNode->sequenceNumber)
1051 OC_LOG_V(INFO, TAG, PCF("Received stale notification. Number :%d"),
1052 response.sequenceNumber);
1056 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1059 cbNode->sequenceNumber = response.sequenceNumber;
1061 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1063 FindAndDeleteClientCB(cbNode);
1067 // To keep discovery callbacks active.
1068 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1069 MILLISECONDS_PER_SECOND);
1071 OCPayloadDestroy(response.payload);
1074 //Need to send ACK when the response is CON
1075 if(responseInfo->info.type == CA_MSG_CONFIRM)
1077 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1078 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0);
1086 OC_LOG(INFO, TAG, PCF("There is an observer associated with the response token"));
1087 if(responseInfo->result == CA_EMPTY)
1089 OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
1090 if(responseInfo->info.type == CA_MSG_RESET)
1092 OC_LOG(INFO, TAG, PCF("This is a RESET"));
1093 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1094 OC_OBSERVER_NOT_INTERESTED);
1096 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1098 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
1099 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1100 OC_OBSERVER_STILL_INTERESTED);
1103 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1105 OC_LOG(INFO, TAG, PCF("Receiving Time Out for an observer"));
1106 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1107 OC_OBSERVER_FAILED_COMM);
1112 if(!cbNode && !observer)
1114 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER)
1116 OC_LOG(INFO, TAG, PCF("This is a client, but no cbNode was found for token"));
1117 if(responseInfo->result == CA_EMPTY)
1119 OC_LOG(INFO, TAG, PCF("Receiving CA_EMPTY in the ocstack"));
1123 OC_LOG(INFO, TAG, PCF("Received a response or notification,\
1124 but I do not have callback. Sending RESET"));
1125 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1126 CA_MSG_RESET, 0, NULL, NULL, 0);
1130 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
1132 OC_LOG(INFO, TAG, PCF("This is a server, but no observer was found for token"));
1133 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1135 OC_LOG_V(INFO, TAG, PCF("Received ACK at server for messageId : %d"),
1136 responseInfo->info.messageId);
1138 if (responseInfo->info.type == CA_MSG_RESET)
1140 OC_LOG_V(INFO, TAG, PCF("Received RESET at server for messageId : %d"),
1141 responseInfo->info.messageId);
1147 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
1151 * This function handles error response from CA
1152 * code shall be added to handle the errors
1154 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1156 OC_LOG(INFO, TAG, PCF("Enter HandleCAErrorResponse"));
1158 if(NULL == endPoint)
1160 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1164 if(NULL == errrorInfo)
1166 OC_LOG(ERROR, TAG, PCF("errrorInfo is NULL"));
1169 OC_LOG(INFO, TAG, PCF("Exit HandleCAErrorResponse"));
1173 * This function sends out Direct Stack Responses. These are responses that are not coming
1174 * from the application entity handler. These responses have no payload and are usually ACKs,
1175 * RESETs or some error conditions that were caught by the stack.
1177 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1178 const CAResponseResult_t responseResult, const CAMessageType_t type,
1179 const uint8_t numOptions, const CAHeaderOption_t *options,
1180 CAToken_t token, uint8_t tokenLength)
1182 CAResponseInfo_t respInfo = {};
1183 respInfo.result = responseResult;
1184 respInfo.info.messageId = coapID;
1185 respInfo.info.numOptions = numOptions;
1186 respInfo.info.options = (CAHeaderOption_t*)options;
1187 respInfo.info.payload = NULL;
1188 respInfo.info.token = token;
1189 respInfo.info.tokenLength = tokenLength;
1190 respInfo.info.type = type;
1192 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1193 if(caResult != CA_STATUS_OK)
1195 OC_LOG(ERROR, TAG, PCF("CASendResponse error"));
1196 return OC_STACK_ERROR;
1201 //This function will be called back by CA layer when a request is received
1202 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1204 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
1207 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1213 OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
1217 OCStackResult requestResult = OC_STACK_ERROR;
1219 if(myStackMode == OC_CLIENT)
1221 //TODO: should the client be responding to requests?
1225 OCServerProtocolRequest serverRequest = {};
1227 OC_LOG_V(INFO, TAG, PCF("Endpoint URI : %s\n"), requestInfo->info.resourceUri);
1229 char * newUri = NULL;
1230 char * query = NULL;
1232 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &newUri);
1234 if (requestResult != OC_STACK_OK)
1236 OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1239 OC_LOG_V(INFO, TAG, PCF("URI without query: %s\n"), newUri);
1240 OC_LOG_V(INFO, TAG, PCF("Query : %s\n"), query);
1242 if(strlen(newUri) < MAX_URI_LENGTH)
1245 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl),
1251 OC_LOG(ERROR, TAG, PCF("URI length exceeds MAX_URI_LENGTH."));
1259 if(strlen(query) < MAX_QUERY_LENGTH)
1261 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1266 OC_LOG(ERROR, TAG, PCF("Query length exceeds MAX_QUERY_LENGTH."));
1271 //copy request payload
1272 if (requestInfo->info.payload)
1274 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1275 memcpy (&(serverRequest.payload), requestInfo->info.payload,
1276 requestInfo->info.payloadSize);
1280 serverRequest.reqTotalSize = 0;
1283 switch (requestInfo->method)
1286 serverRequest.method = OC_REST_GET;
1289 serverRequest.method = OC_REST_PUT;
1292 serverRequest.method = OC_REST_POST;
1295 serverRequest.method = OC_REST_DELETE;
1298 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
1299 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1300 requestInfo->info.type, requestInfo->info.numOptions,
1301 requestInfo->info.options, requestInfo->info.token,
1302 requestInfo->info.tokenLength);
1306 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d",
1307 requestInfo->info.tokenLength);
1308 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1309 requestInfo->info.tokenLength);
1310 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1311 serverRequest.tokenLength = requestInfo->info.tokenLength;
1313 if (!serverRequest.requestToken)
1315 OC_LOG(FATAL, TAG, "Server Request Token is NULL");
1316 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1317 requestInfo->info.type, requestInfo->info.numOptions,
1318 requestInfo->info.options, requestInfo->info.token,
1319 requestInfo->info.tokenLength);
1322 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1324 if (requestInfo->info.type == CA_MSG_CONFIRM)
1326 serverRequest.qos = OC_HIGH_QOS;
1330 serverRequest.qos = OC_LOW_QOS;
1332 // CA does not need the following field
1333 // Are we sure CA does not need them? how is it responding to multicast
1334 serverRequest.delayedResNeeded = 0;
1336 serverRequest.coapID = requestInfo->info.messageId;
1339 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1341 // copy vendor specific header options
1342 uint8_t tempNum = (requestInfo->info.numOptions);
1343 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1344 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1347 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
1348 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1349 requestInfo->info.type, requestInfo->info.numOptions,
1350 requestInfo->info.options, requestInfo->info.token,
1351 requestInfo->info.tokenLength);
1352 OICFree(serverRequest.requestToken);
1355 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1356 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1358 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1359 sizeof(CAHeaderOption_t)*tempNum);
1362 requestResult = HandleStackRequests (&serverRequest);
1364 // Send ACK to client as precursor to slow response
1365 if(requestResult == OC_STACK_SLOW_RESOURCE)
1367 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1368 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0);
1370 else if(requestResult != OC_STACK_OK)
1372 OC_LOG_V(ERROR, TAG, PCF("HandleStackRequests failed. error: %d"), requestResult);
1374 CAResponseResult_t stackResponse = OCToCAStackResult(requestResult);
1376 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1377 requestInfo->info.type, requestInfo->info.numOptions,
1378 requestInfo->info.options, requestInfo->info.token,
1379 requestInfo->info.tokenLength);
1381 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1382 // The token is copied in there, and is thus still owned by this function.
1383 OICFree(serverRequest.requestToken);
1384 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
1387 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1389 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
1390 OCStackResult result = OC_STACK_ERROR;
1391 ResourceHandling resHandling;
1392 OCResource *resource;
1393 if(!protocolRequest)
1395 OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
1396 return OC_STACK_INVALID_PARAM;
1399 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1400 protocolRequest->tokenLength);
1403 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
1404 result = AddServerRequest(&request, protocolRequest->coapID,
1405 protocolRequest->delayedResNeeded, 0,
1406 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
1407 protocolRequest->observationOption, protocolRequest->qos,
1408 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1409 protocolRequest->payload, protocolRequest->requestToken,
1410 protocolRequest->tokenLength,
1411 protocolRequest->resourceUrl, protocolRequest->reqTotalSize,
1412 &protocolRequest->devAddr);
1413 if (OC_STACK_OK != result)
1415 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
1421 OC_LOG(ERROR, TAG, PCF("Out of Memory"));
1422 return OC_STACK_NO_MEMORY;
1425 if(!protocolRequest->reqMorePacket)
1427 request->requestComplete = 1;
1433 PCF("This is either a repeated or blocked Server Request"));
1436 if(request->requestComplete)
1438 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
1439 result = DetermineResourceHandling (request, &resHandling, &resource);
1440 if (result == OC_STACK_OK)
1442 result = ProcessRequest(resHandling, resource, request);
1447 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
1448 result = OC_STACK_CONTINUE;
1453 bool validatePlatformInfo(OCPlatformInfo info)
1456 if (!info.platformID)
1458 OC_LOG(ERROR, TAG, PCF("No platform ID found."));
1462 if (info.manufacturerName)
1464 size_t lenManufacturerName = strlen(info.manufacturerName);
1466 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1468 OC_LOG(ERROR, TAG, PCF("Manufacturer name fails length requirements."));
1474 OC_LOG(ERROR, TAG, PCF("No manufacturer name present"));
1478 if (info.manufacturerUrl)
1480 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1482 OC_LOG(ERROR, TAG, PCF("Manufacturer url fails length requirements."));
1489 //-----------------------------------------------------------------------------
1491 //-----------------------------------------------------------------------------
1493 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1498 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1501 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1503 if(stackState == OC_STACK_INITIALIZED)
1505 OC_LOG(INFO, TAG, PCF("Subsequent calls to OCInit() without calling \
1506 OCStop() between them are ignored."));
1510 OCStackResult result = OC_STACK_ERROR;
1511 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1514 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)))
1516 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1517 return OC_STACK_ERROR;
1521 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1522 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
1524 defaultDeviceHandler = NULL;
1525 defaultDeviceHandlerCallbackParameter = NULL;
1528 result = CAResultToOCResult(CAInitialize());
1529 VERIFY_SUCCESS(result, OC_STACK_OK);
1531 result = CAResultToOCResult(OCSelectNetwork());
1532 VERIFY_SUCCESS(result, OC_STACK_OK);
1534 switch (myStackMode)
1537 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1538 result = CAResultToOCResult(CAStartDiscoveryServer());
1539 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1542 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1543 result = CAResultToOCResult(CAStartListeningServer());
1544 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1546 case OC_CLIENT_SERVER:
1547 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1548 result = CAResultToOCResult(CAStartListeningServer());
1549 if(result == OC_STACK_OK)
1551 result = CAResultToOCResult(CAStartDiscoveryServer());
1555 VERIFY_SUCCESS(result, OC_STACK_OK);
1557 #ifdef WITH_PRESENCE
1558 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1559 #endif // WITH_PRESENCE
1561 //Update Stack state to initialized
1562 stackState = OC_STACK_INITIALIZED;
1564 // Initialize resource
1565 if(myStackMode != OC_CLIENT)
1567 result = initResources();
1570 // Initialize the SRM Policy Engine
1571 if(result == OC_STACK_OK)
1573 result = SRMInitPolicyEngine();
1574 // TODO after BeachHead delivery: consolidate into single SRMInit()
1578 if(result != OC_STACK_OK)
1580 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1581 deleteAllResources();
1583 stackState = OC_STACK_UNINITIALIZED;
1588 OCStackResult OCStop()
1590 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1592 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1594 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1597 else if (stackState != OC_STACK_INITIALIZED)
1599 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1600 return OC_STACK_ERROR;
1603 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1605 #ifdef WITH_PRESENCE
1606 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1607 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1608 presenceResource.presenceTTL = 0;
1609 #endif // WITH_PRESENCE
1611 // Free memory dynamically allocated for resources
1612 deleteAllResources();
1614 DeletePlatformInfo();
1616 // Remove all observers
1617 DeleteObserverList();
1618 // Remove all the client callbacks
1619 DeleteClientCBList();
1621 // De-init the SRM Policy Engine
1622 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
1623 SRMDeInitPolicyEngine();
1626 stackState = OC_STACK_UNINITIALIZED;
1630 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1635 return CA_MSG_CONFIRM;
1640 return CA_MSG_NONCONFIRM;
1644 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1648 query = strchr (inputUri, '?');
1652 if((query - inputUri) > MAX_URI_LENGTH)
1654 return OC_STACK_INVALID_URI;
1657 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1659 return OC_STACK_INVALID_QUERY;
1662 else if(uriLen > MAX_URI_LENGTH)
1664 return OC_STACK_INVALID_URI;
1670 * A request uri consists of the following components in order:
1672 * optional prefix "coap://"
1674 * IPv6 address "[1234::5678]"
1675 * IPv4 address "192.168.1.1"
1676 * optional port ":5683"
1677 * resource uri "/oc/core..."
1679 * for PRESENCE requests, extract resource type.
1681 static OCStackResult ParseRequestUri(const char *fullUri,
1682 OCTransportAdapter adapter,
1683 OCTransportFlags flags,
1684 OCDevAddr **devAddr,
1686 char **resourceType)
1688 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
1690 OCStackResult result = OC_STACK_OK;
1691 OCDevAddr *da = NULL;
1695 // provide defaults for all returned values
1702 *resourceUri = NULL;
1706 *resourceType = NULL;
1709 // delimit url prefix, if any
1710 const char *start = fullUri;
1711 char *slash2 = strstr(start, "//");
1716 char *slash = strchr(start, '/');
1719 return OC_STACK_INVALID_URI;
1722 // processs url prefix, if any
1723 size_t urlLen = slash - start;
1724 if (urlLen && devAddr)
1725 { // construct OCDevAddr
1726 if (start[0] == '[')
1728 char *close = strchr(++start, ']');
1729 if (!close || close > slash)
1731 return OC_STACK_INVALID_URI;
1734 if (close[1] == ':')
1742 colon = strchr(start, ':');
1743 end = (colon && colon < slash) ? colon : slash;
1745 size_t len = end - start;
1746 if (len >= sizeof(da->addr))
1748 return OC_STACK_INVALID_URI;
1752 uint16_t port = 0; // use standard multicast port
1753 if (colon && colon < slash)
1755 for (colon++; colon < slash; colon++)
1758 if (c < '0' || c > '9')
1760 return OC_STACK_INVALID_URI;
1762 port = 10 * port + c - '0';
1766 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
1769 return OC_STACK_NO_MEMORY;
1771 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
1773 da->adapter = adapter;
1775 if (!strncmp(fullUri, "coaps:", 6))
1777 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
1782 // process resource uri, if any
1784 { // request uri and query
1785 size_t ulen = strlen(slash); // resource uri length
1786 size_t tlen = 0; // resource type length
1789 static const char *strPresence = "/oc/presence?rt=";
1790 static const size_t lenPresence = 15; // = strlen(presence);
1791 if (!strncmp(slash, strPresence, lenPresence))
1793 type = slash + lenPresence;
1794 tlen = ulen - lenPresence;
1799 *resourceUri = (char *)OICMalloc(ulen + 1);
1802 result = OC_STACK_NO_MEMORY;
1805 strcpy(*resourceUri, slash);
1808 if (type && resourceType)
1810 *resourceType = (char *)OICMalloc(tlen + 1);
1813 result = OC_STACK_NO_MEMORY;
1816 strncpy(*resourceType, type, tlen);
1823 // free all returned values
1830 OICFree(*resourceUri);
1834 OICFree(*resourceType);
1839 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
1840 char *resourceUri, char **requestUri)
1842 char uri[CA_MAX_URI_LENGTH];
1844 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
1846 *requestUri = (char *)OICMalloc(strlen(uri) + 1);
1849 return OC_STACK_NO_MEMORY;
1852 strcpy(*requestUri, uri);
1857 * Discover or Perform requests on a specified resource
1859 OCStackResult OCDoResource(OCDoHandle *handle,
1861 const char *requestUri,
1862 const OCDevAddr *destination,
1864 OCConnectivityType connectivityType,
1865 OCQualityOfService qos,
1866 OCCallbackData *cbData,
1867 OCHeaderOption *options,
1870 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1872 // Validate input parameters
1873 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1874 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1875 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
1877 OCStackResult result = OC_STACK_ERROR;
1878 CAResult_t caResult;
1879 CAToken_t token = NULL;
1880 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
1881 ClientCB *clientCB = NULL;
1882 OCDoHandle resHandle = NULL;
1883 CAEndpoint_t *endpoint = NULL;
1884 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
1886 OCTransportAdapter adapter;
1887 OCTransportFlags flags;
1888 // the request contents are put here
1889 CARequestInfo_t requestInfo = { CA_GET };
1890 // requestUri will be parsed into the following three variables
1891 OCDevAddr *devAddr = NULL;
1892 char *resourceUri = NULL;
1893 char *resourceType = NULL;
1895 // To track if memory is allocated for additional header options
1896 uint8_t hdrOptionMemAlloc = 0;
1898 // This validation is broken, but doesn't cause harm
1899 size_t uriLen = strlen(requestUri );
1900 if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
1906 * Support original behavior with address on resourceUri argument.
1908 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
1909 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
1911 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
1913 if (result != OC_STACK_OK)
1915 OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
1922 case OC_REST_OBSERVE:
1923 case OC_REST_OBSERVE_ALL:
1924 case OC_REST_CANCEL_OBSERVE:
1925 requestInfo.method = CA_GET;
1928 requestInfo.method = CA_PUT;
1931 requestInfo.method = CA_POST;
1933 case OC_REST_DELETE:
1934 requestInfo.method = CA_DELETE;
1936 case OC_REST_DISCOVER:
1938 if (!destination && !devAddr)
1940 destination = &tmpDevAddr;
1942 // CA_DISCOVER will become GET and isMulticast
1943 requestInfo.method = CA_GET;
1944 requestInfo.isMulticast = true;
1946 #ifdef WITH_PRESENCE
1947 case OC_REST_PRESENCE:
1948 // Replacing method type with GET because "presence"
1949 // is a stack layer only implementation.
1950 requestInfo.method = CA_GET;
1954 result = OC_STACK_INVALID_METHOD;
1958 if (!devAddr && !destination)
1960 OC_LOG_V(DEBUG, TAG, "no devAddr and no destination");
1961 result = OC_STACK_INVALID_PARAM;
1965 /* If not original behavior, use destination argument */
1966 if (destination && !devAddr)
1968 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
1971 result = OC_STACK_NO_MEMORY;
1974 *devAddr = *destination;
1977 resHandle = GenerateInvocationHandle();
1980 result = OC_STACK_NO_MEMORY;
1984 caResult = CAGenerateToken(&token, tokenLength);
1985 if (caResult != CA_STATUS_OK)
1987 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1991 // fill in request data
1992 requestInfo.info.type = qualityOfServiceToMessageType(qos);
1993 requestInfo.info.token = token;
1994 requestInfo.info.tokenLength = tokenLength;
1995 requestInfo.info.resourceUri = resourceUri;
1997 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1999 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2000 options, numOptions, OC_OBSERVE_REGISTER);
2001 if (result != OC_STACK_OK)
2005 hdrOptionMemAlloc = 1;
2006 requestInfo.info.numOptions = numOptions + 1;
2010 requestInfo.info.options = (CAHeaderOption_t*)options;
2011 requestInfo.info.numOptions = numOptions;
2014 // create remote endpoint
2015 result = OCCreateEndpoint(devAddr, &endpoint);
2019 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2022 OC_LOG(ERROR, TAG, PCF("Failed to create CBOR Payload"));
2028 requestInfo.info.payload = NULL;
2029 requestInfo.info.payloadSize = 0;
2034 if (result != OC_STACK_OK)
2036 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2040 // prepare for response
2041 #ifdef WITH_PRESENCE
2042 if (method == OC_REST_PRESENCE)
2044 char *presenceUri = NULL;
2045 result = OCPreparePresence(endpoint, resourceUri, &presenceUri);
2046 if (OC_STACK_OK != result)
2051 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2052 // Presence notification will form a canonical uri to
2053 // look for callbacks into the application.
2054 resourceUri = presenceUri;
2058 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2059 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2060 method, devAddr, resourceUri, resourceType, ttl);
2061 if (OC_STACK_OK != result)
2066 devAddr = NULL; // Client CB list entry now owns it
2067 resourceUri = NULL; // Client CB list entry now owns it
2068 resourceType = NULL; // Client CB list entry now owns it
2071 caResult = CASendRequest(endpoint, &requestInfo);
2072 if (caResult != CA_STATUS_OK)
2074 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
2075 result = OC_STACK_COMM_ERROR;
2081 *handle = resHandle;
2085 if (result != OC_STACK_OK)
2087 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
2088 FindAndDeleteClientCB(clientCB);
2089 CADestroyToken(token);
2097 // This is the owner of the payload object, so we free it
2098 OCPayloadDestroy(payload);
2100 OICFree(resourceUri);
2101 OICFree(resourceType);
2103 if (hdrOptionMemAlloc)
2105 OICFree(requestInfo.info.options);
2110 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2114 * This ftn is implemented one of two ways in the case of observation:
2116 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2117 * Remove the callback associated on client side.
2118 * When the next notification comes in from server,
2119 * reply with RESET message to server.
2120 * Keep in mind that the server will react to RESET only
2121 * if the last notification was sent as CON
2123 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2124 * and it is associated with an observe request
2125 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2126 * Send CON Observe request to server with
2127 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2128 * Remove the callback associated on client side.
2130 OCStackResult ret = OC_STACK_OK;
2131 CAEndpoint_t* endpoint = NULL;
2132 CAResult_t caResult;
2133 CAInfo_t requestData = {};
2134 CARequestInfo_t requestInfo = {};
2138 return OC_STACK_INVALID_PARAM;
2141 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
2143 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2146 OC_LOG(ERROR, TAG, PCF("Client callback not found. Called OCCancel twice?"));
2150 switch (clientCB->method)
2152 case OC_REST_OBSERVE:
2153 case OC_REST_OBSERVE_ALL:
2154 OC_LOG(INFO, TAG, PCF("Canceling observation"));
2155 if (qos != OC_HIGH_QOS)
2157 FindAndDeleteClientCB(clientCB);
2161 requestData.type = qualityOfServiceToMessageType(qos);
2162 requestData.token = clientCB->token;
2163 requestData.tokenLength = clientCB->tokenLength;
2164 if (CreateObserveHeaderOption (&(requestData.options),
2165 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2167 return OC_STACK_ERROR;
2169 requestData.numOptions = numOptions + 1;
2170 requestData.resourceUri = OICStrdup (clientCB->requestUri);
2172 requestInfo.method = CA_GET;
2173 requestInfo.info = requestData;
2175 ret = OCCreateEndpoint(clientCB->devAddr, &endpoint);
2176 if (ret != OC_STACK_OK)
2178 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2183 caResult = CASendRequest(endpoint, &requestInfo);
2184 if (caResult != CA_STATUS_OK)
2186 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2187 ret = OC_STACK_ERROR;
2189 ret = CAResultToOCResult (caResult);
2192 #ifdef WITH_PRESENCE
2193 case OC_REST_PRESENCE:
2194 FindAndDeleteClientCB(clientCB);
2199 ret = OC_STACK_INVALID_METHOD;
2204 OCDestroyEndpoint(endpoint);
2205 if (requestData.numOptions > 0)
2207 OICFree(requestData.options);
2209 if (requestData.resourceUri)
2211 OICFree (requestData.resourceUri);
2218 * @brief Register Persistent storage callback.
2219 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2221 * OC_STACK_OK - No errors; Success
2222 * OC_STACK_INVALID_PARAM - Invalid parameter
2224 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2226 OC_LOG(INFO, TAG, PCF("RegisterPersistentStorageHandler !!"));
2227 if(!persistentStorageHandler)
2229 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2230 return OC_STACK_INVALID_PARAM;
2234 if( !persistentStorageHandler->open ||
2235 !persistentStorageHandler->close ||
2236 !persistentStorageHandler->read ||
2237 !persistentStorageHandler->unlink ||
2238 !persistentStorageHandler->write)
2240 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2241 return OC_STACK_INVALID_PARAM;
2244 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2247 #ifdef WITH_PRESENCE
2249 OCStackResult OCProcessPresence()
2251 OCStackResult result = OC_STACK_OK;
2253 // the following line floods the log with messages that are irrelevant
2254 // to most purposes. Uncomment as needed.
2255 //OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
2256 ClientCB* cbNode = NULL;
2257 OCClientResponse clientResponse;
2258 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2260 LL_FOREACH(cbList, cbNode)
2262 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2267 uint32_t now = GetTicks(0);
2268 OC_LOG_V(DEBUG, TAG, "this TTL level %d",
2269 cbNode->presence->TTLlevel);
2270 OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2272 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
2277 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2279 OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2280 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2283 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2285 OC_LOG(DEBUG, TAG, PCF("No more timeout ticks"));
2287 clientResponse.sequenceNumber = 0;
2288 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2289 clientResponse.devAddr = *cbNode->devAddr;
2290 FixUpClientResponse(&clientResponse);
2291 clientResponse.payload = NULL;
2293 // Increment the TTLLevel (going to a next state), so we don't keep
2294 // sending presence notification to client.
2295 cbNode->presence->TTLlevel++;
2296 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2297 cbNode->presence->TTLlevel);
2299 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2300 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2302 FindAndDeleteClientCB(cbNode);
2306 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2311 CAResult_t caResult = CA_STATUS_OK;
2312 CAEndpoint_t* endpoint = NULL;
2313 CAInfo_t requestData ={};
2314 CARequestInfo_t requestInfo = {};
2316 OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
2318 result = OCCreateEndpoint(cbNode->devAddr, &endpoint);
2319 if (result != OC_STACK_OK)
2321 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2325 requestData.type = CA_MSG_NONCONFIRM;
2326 requestData.token = cbNode->token;
2327 requestData.tokenLength = cbNode->tokenLength;
2328 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2329 requestInfo.method = CA_GET;
2330 requestInfo.info = requestData;
2332 caResult = CASendRequest(endpoint, &requestInfo);
2333 OCDestroyEndpoint(endpoint);
2335 if (caResult != CA_STATUS_OK)
2337 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2341 cbNode->presence->TTLlevel++;
2342 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2345 if (result != OC_STACK_OK)
2347 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2351 #endif // WITH_PRESENCE
2353 OCStackResult OCProcess()
2355 #ifdef WITH_PRESENCE
2356 OCProcessPresence();
2358 CAHandleRequestResponse();
2363 #ifdef WITH_PRESENCE
2364 OCStackResult OCStartPresence(const uint32_t ttl)
2366 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2367 OCChangeResourceProperty(
2368 &(((OCResource *)presenceResource.handle)->resourceProperties),
2371 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2373 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2374 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to max value"));
2378 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2379 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to default value"));
2383 presenceResource.presenceTTL = ttl;
2385 OC_LOG_V(DEBUG, TAG, "Presence TTL is %lu seconds", presenceResource.presenceTTL);
2387 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2389 presenceState = OC_PRESENCE_INITIALIZED;
2391 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2392 OICStrcpy(devAddr.addr, sizeof(devAddr.addr), OC_MULTICAST_IP);
2393 devAddr.port = OC_MULTICAST_PORT;
2395 CAToken_t caToken = NULL;
2396 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2397 if (caResult != CA_STATUS_OK)
2399 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2400 CADestroyToken(caToken);
2401 return OC_STACK_ERROR;
2404 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2405 (OCResource *)presenceResource.handle, OC_LOW_QOS, &devAddr);
2406 CADestroyToken(caToken);
2409 // Each time OCStartPresence is called
2410 // a different random 32-bit integer number is used
2411 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2413 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2414 OC_PRESENCE_TRIGGER_CREATE);
2417 OCStackResult OCStopPresence()
2419 OCStackResult result = OC_STACK_ERROR;
2421 if(presenceResource.handle)
2423 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2425 // make resource inactive
2426 result = OCChangeResourceProperty(
2427 &(((OCResource *) presenceResource.handle)->resourceProperties),
2431 if(result != OC_STACK_OK)
2434 PCF("Changing the presence resource properties to ACTIVE not successful"));
2438 return SendStopNotification();
2442 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
2443 void* callbackParameter)
2445 defaultDeviceHandler = entityHandler;
2446 defaultDeviceHandlerCallbackParameter = callbackParameter;
2451 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
2453 OC_LOG(INFO, TAG, PCF("Entering OCSetPlatformInfo"));
2455 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
2457 if (validatePlatformInfo(platformInfo))
2459 return SavePlatformInfo(platformInfo);
2463 return OC_STACK_INVALID_PARAM;
2468 return OC_STACK_ERROR;
2472 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2474 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2476 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
2478 OC_LOG(ERROR, TAG, PCF("Null or empty device name."));
2479 return OC_STACK_INVALID_PARAM;
2482 return SaveDeviceInfo(deviceInfo);
2485 OCStackResult OCCreateResource(OCResourceHandle *handle,
2486 const char *resourceTypeName,
2487 const char *resourceInterfaceName,
2488 const char *uri, OCEntityHandler entityHandler,
2489 void* callbackParam,
2490 uint8_t resourceProperties)
2493 OCResource *pointer = NULL;
2495 OCStackResult result = OC_STACK_ERROR;
2497 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2499 if(myStackMode == OC_CLIENT)
2501 return OC_STACK_INVALID_PARAM;
2503 // Validate parameters
2504 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2506 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
2507 return OC_STACK_INVALID_URI;
2509 // Is it presented during resource discovery?
2510 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
2512 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2513 return OC_STACK_INVALID_PARAM;
2516 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2518 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2521 // Make sure resourceProperties bitmask has allowed properties specified
2522 if (resourceProperties
2523 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE))
2525 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2526 return OC_STACK_INVALID_PARAM;
2529 // If the headResource is NULL, then no resources have been created...
2530 pointer = headResource;
2533 // At least one resources is in the resource list, so we need to search for
2534 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2537 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
2539 OC_LOG(ERROR, TAG, PCF("URI already in use"));
2540 return OC_STACK_INVALID_PARAM;
2542 pointer = pointer->next;
2545 // Create the pointer and insert it into the resource list
2546 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
2549 result = OC_STACK_NO_MEMORY;
2552 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2554 insertResource(pointer);
2557 str = OICStrdup(uri);
2560 result = OC_STACK_NO_MEMORY;
2565 // Set properties. Set OC_ACTIVE
2566 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2569 // Add the resourcetype to the resource
2570 result = BindResourceTypeToResource(pointer, resourceTypeName);
2571 if (result != OC_STACK_OK)
2573 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2577 // Add the resourceinterface to the resource
2578 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2579 if (result != OC_STACK_OK)
2581 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2585 // If an entity handler has been passed, attach it to the newly created
2586 // resource. Otherwise, set the default entity handler.
2589 pointer->entityHandler = entityHandler;
2590 pointer->entityHandlerCallbackParam = callbackParam;
2594 pointer->entityHandler = defaultResourceEHandler;
2595 pointer->entityHandlerCallbackParam = NULL;
2599 result = OC_STACK_OK;
2601 #ifdef WITH_PRESENCE
2602 if(presenceResource.handle)
2604 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2605 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
2609 if (result != OC_STACK_OK)
2611 // Deep delete of resource and other dynamic elements that it contains
2612 deleteResource(pointer);
2619 OCStackResult OCBindResource(
2620 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2622 OCResource *resource = NULL;
2625 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2627 // Validate parameters
2628 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2629 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2630 // Container cannot contain itself
2631 if (collectionHandle == resourceHandle)
2633 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2634 return OC_STACK_INVALID_PARAM;
2637 // Use the handle to find the resource in the resource linked list
2638 resource = findResource((OCResource *) collectionHandle);
2641 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2642 return OC_STACK_INVALID_PARAM;
2645 // Look for an open slot to add add the child resource.
2646 // If found, add it and return success
2647 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2649 if (!resource->rsrcResources[i])
2651 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2652 OC_LOG(INFO, TAG, PCF("resource bound"));
2654 #ifdef WITH_PRESENCE
2655 if(presenceResource.handle)
2657 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2658 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2659 OC_PRESENCE_TRIGGER_CHANGE);
2667 // Unable to add resourceHandle, so return error
2668 return OC_STACK_ERROR;
2671 OCStackResult OCUnBindResource(
2672 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2674 OCResource *resource = NULL;
2677 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2679 // Validate parameters
2680 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2681 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2682 // Container cannot contain itself
2683 if (collectionHandle == resourceHandle)
2685 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2686 return OC_STACK_INVALID_PARAM;
2689 // Use the handle to find the resource in the resource linked list
2690 resource = findResource((OCResource *) collectionHandle);
2693 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2694 return OC_STACK_INVALID_PARAM;
2697 // Look for an open slot to add add the child resource.
2698 // If found, add it and return success
2699 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2701 if (resourceHandle == resource->rsrcResources[i])
2703 resource->rsrcResources[i] = (OCResource *) NULL;
2704 OC_LOG(INFO, TAG, PCF("resource unbound"));
2706 // Send notification when resource is unbounded successfully.
2707 #ifdef WITH_PRESENCE
2708 if(presenceResource.handle)
2710 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2711 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2712 OC_PRESENCE_TRIGGER_CHANGE);
2719 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2721 // Unable to add resourceHandle, so return error
2722 return OC_STACK_ERROR;
2725 OCStackResult BindResourceTypeToResource(OCResource* resource,
2726 const char *resourceTypeName)
2728 OCResourceType *pointer = NULL;
2730 OCStackResult result = OC_STACK_ERROR;
2732 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
2734 // Validate parameters
2735 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2736 // TODO: Does resource attribute representation really have to be maintained in stack?
2737 // Is it presented during resource discovery?
2739 // Create the resourcetype and insert it into the resource list
2740 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
2743 result = OC_STACK_NO_MEMORY;
2747 // Set the resourceTypeName
2748 str = OICStrdup(resourceTypeName);
2751 result = OC_STACK_NO_MEMORY;
2754 pointer->resourcetypename = str;
2756 insertResourceType(resource, pointer);
2757 result = OC_STACK_OK;
2760 if (result != OC_STACK_OK)
2769 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2770 const char *resourceInterfaceName)
2772 OCResourceInterface *pointer = NULL;
2774 OCStackResult result = OC_STACK_ERROR;
2776 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2778 // Validate parameters
2779 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2781 //TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2783 // Create the resourceinterface and insert it into the resource list
2784 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
2787 result = OC_STACK_NO_MEMORY;
2791 // Set the resourceinterface name
2792 str = OICStrdup(resourceInterfaceName);
2795 result = OC_STACK_NO_MEMORY;
2798 pointer->name = str;
2800 // Bind the resourceinterface to the resource
2801 insertResourceInterface(resource, pointer);
2803 result = OC_STACK_OK;
2806 if (result != OC_STACK_OK)
2815 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2816 const char *resourceTypeName)
2819 OCStackResult result = OC_STACK_ERROR;
2820 OCResource *resource = NULL;
2822 // Make sure resource exists
2823 resource = findResource((OCResource *) handle);
2826 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2827 return OC_STACK_ERROR;
2830 // call internal function
2831 result = BindResourceTypeToResource(resource, resourceTypeName);
2833 #ifdef WITH_PRESENCE
2834 if(presenceResource.handle)
2836 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2837 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2844 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2845 const char *resourceInterfaceName)
2848 OCStackResult result = OC_STACK_ERROR;
2849 OCResource *resource = NULL;
2851 // Make sure resource exists
2852 resource = findResource((OCResource *) handle);
2855 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2856 return OC_STACK_ERROR;
2859 // call internal function
2860 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2862 #ifdef WITH_PRESENCE
2863 if(presenceResource.handle)
2865 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2866 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2873 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
2875 OCResource *pointer = headResource;
2877 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2878 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2882 *numResources = *numResources + 1;
2883 pointer = pointer->next;
2888 OCResourceHandle OCGetResourceHandle(uint8_t index)
2890 OCResource *pointer = headResource;
2892 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2894 // Iterate through the list
2895 for( uint8_t i = 0; i < index && pointer; ++i)
2897 pointer = pointer->next;
2899 return (OCResourceHandle) pointer;
2902 OCStackResult OCDeleteResource(OCResourceHandle handle)
2904 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2908 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2909 return OC_STACK_INVALID_PARAM;
2912 OCResource *resource = findResource((OCResource *) handle);
2913 if (resource == NULL)
2915 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2916 return OC_STACK_NO_RESOURCE;
2919 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
2921 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2922 return OC_STACK_ERROR;
2928 const char *OCGetResourceUri(OCResourceHandle handle)
2930 OCResource *resource = NULL;
2931 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2933 resource = findResource((OCResource *) handle);
2936 return resource->uri;
2938 return (const char *) NULL;
2941 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
2943 OCResource *resource = NULL;
2944 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2946 resource = findResource((OCResource *) handle);
2949 return resource->resourceProperties;
2951 return (OCResourceProperty)-1;
2954 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2955 uint8_t *numResourceTypes)
2957 OCResource *resource = NULL;
2958 OCResourceType *pointer = NULL;
2960 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2961 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2962 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2964 *numResourceTypes = 0;
2966 resource = findResource((OCResource *) handle);
2969 pointer = resource->rsrcType;
2972 *numResourceTypes = *numResourceTypes + 1;
2973 pointer = pointer->next;
2979 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
2981 OCResourceType *resourceType = NULL;
2983 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2985 resourceType = findResourceTypeAtIndex(handle, index);
2988 return resourceType->resourcetypename;
2990 return (const char *) NULL;
2993 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2994 uint8_t *numResourceInterfaces)
2996 OCResourceInterface *pointer = NULL;
2997 OCResource *resource = NULL;
2999 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
3001 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3002 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3004 *numResourceInterfaces = 0;
3005 resource = findResource((OCResource *) handle);
3008 pointer = resource->rsrcInterface;
3011 *numResourceInterfaces = *numResourceInterfaces + 1;
3012 pointer = pointer->next;
3018 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3020 OCResourceInterface *resourceInterface = NULL;
3022 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
3024 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3025 if (resourceInterface)
3027 return resourceInterface->name;
3029 return (const char *) NULL;
3032 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3035 OCResource *resource = NULL;
3037 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
3039 if (index >= MAX_CONTAINED_RESOURCES)
3044 resource = findResource((OCResource *) collectionHandle);
3050 return resource->rsrcResources[index];
3053 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3054 OCEntityHandler entityHandler,
3055 void* callbackParam)
3057 OCResource *resource = NULL;
3059 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
3061 // Validate parameters
3062 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3064 // Use the handle to find the resource in the resource linked list
3065 resource = findResource((OCResource *)handle);
3068 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3069 return OC_STACK_ERROR;
3073 resource->entityHandler = entityHandler;
3074 resource->entityHandlerCallbackParam = callbackParam;
3076 #ifdef WITH_PRESENCE
3077 if(presenceResource.handle)
3079 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3080 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3087 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3089 OCResource *resource = NULL;
3091 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
3093 // Use the handle to find the resource in the resource linked list
3094 resource = findResource((OCResource *)handle);
3097 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3102 return resource->entityHandler;
3105 void incrementSequenceNumber(OCResource * resPtr)
3107 // Increment the sequence number
3108 resPtr->sequenceNum += 1;
3109 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3111 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3116 #ifdef WITH_PRESENCE
3117 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3118 OCPresenceTrigger trigger)
3120 OCResource *resPtr = NULL;
3121 OCStackResult result = OC_STACK_ERROR;
3122 OCMethod method = OC_REST_PRESENCE;
3123 uint32_t maxAge = 0;
3124 resPtr = findResource((OCResource *) presenceResource.handle);
3127 return OC_STACK_NO_RESOURCE;
3130 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3132 maxAge = presenceResource.presenceTTL;
3134 result = SendAllObserverNotification(method, resPtr, maxAge,
3135 trigger, resourceType, OC_LOW_QOS);
3141 OCStackResult SendStopNotification()
3143 OCResource *resPtr = NULL;
3144 OCStackResult result = OC_STACK_ERROR;
3145 OCMethod method = OC_REST_PRESENCE;
3146 resPtr = findResource((OCResource *) presenceResource.handle);
3149 return OC_STACK_NO_RESOURCE;
3152 // maxAge is 0. ResourceType is NULL.
3153 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3159 #endif // WITH_PRESENCE
3160 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3163 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
3165 OCResource *resPtr = NULL;
3166 OCStackResult result = OC_STACK_ERROR;
3167 OCMethod method = OC_REST_NOMETHOD;
3168 uint32_t maxAge = 0;
3170 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
3171 #ifdef WITH_PRESENCE
3172 if(handle == presenceResource.handle)
3176 #endif // WITH_PRESENCE
3177 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3179 // Verify that the resource exists
3180 resPtr = findResource ((OCResource *) handle);
3183 return OC_STACK_NO_RESOURCE;
3187 //only increment in the case of regular observing (not presence)
3188 incrementSequenceNumber(resPtr);
3189 method = OC_REST_OBSERVE;
3190 maxAge = MAX_OBSERVE_AGE;
3191 #ifdef WITH_PRESENCE
3192 result = SendAllObserverNotification (method, resPtr, maxAge,
3193 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3195 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3202 OCNotifyListOfObservers (OCResourceHandle handle,
3203 OCObservationId *obsIdList,
3204 uint8_t numberOfIds,
3205 const OCRepPayload *payload,
3206 OCQualityOfService qos)
3208 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3210 OCResource *resPtr = NULL;
3211 //TODO: we should allow the server to define this
3212 uint32_t maxAge = MAX_OBSERVE_AGE;
3214 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3215 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3216 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3218 // Verify that the resource exists
3219 resPtr = findResource ((OCResource *) handle);
3220 if (NULL == resPtr || myStackMode == OC_CLIENT)
3222 return OC_STACK_NO_RESOURCE;
3226 incrementSequenceNumber(resPtr);
3228 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3229 payload, maxAge, qos));
3232 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3234 OCStackResult result = OC_STACK_ERROR;
3235 OCServerRequest *serverRequest = NULL;
3237 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3239 // Validate input parameters
3240 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3241 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3244 // Get pointer to request info
3245 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3248 result = serverRequest->ehResponseHandler(ehResponse);
3254 //-----------------------------------------------------------------------------
3255 // Private internal function definitions
3256 //-----------------------------------------------------------------------------
3257 static OCDoHandle GenerateInvocationHandle()
3259 OCDoHandle handle = NULL;
3260 // Generate token here, it will be deleted when the transaction is deleted
3261 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3264 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3270 #ifdef WITH_PRESENCE
3271 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3272 OCResourceProperty resourceProperties, uint8_t enable)
3276 return OC_STACK_INVALID_PARAM;
3278 if (resourceProperties
3279 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3281 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3282 return OC_STACK_INVALID_PARAM;
3286 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3290 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3296 OCStackResult initResources()
3298 OCStackResult result = OC_STACK_OK;
3299 // Init application resource vars
3300 headResource = NULL;
3301 tailResource = NULL;
3302 // Init Virtual Resources
3303 #ifdef WITH_PRESENCE
3304 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3305 //presenceResource.token = OCGenerateCoAPToken();
3306 result = OCCreateResource(&presenceResource.handle,
3307 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3309 OC_RSRVD_PRESENCE_URI,
3313 //make resource inactive
3314 result = OCChangeResourceProperty(
3315 &(((OCResource *) presenceResource.handle)->resourceProperties),
3319 if (result == OC_STACK_OK)
3321 result = SRMInitSecureResources();
3327 void insertResource(OCResource *resource)
3331 headResource = resource;
3332 tailResource = resource;
3336 tailResource->next = resource;
3337 tailResource = resource;
3339 resource->next = NULL;
3342 OCResource *findResource(OCResource *resource)
3344 OCResource *pointer = headResource;
3348 if (pointer == resource)
3352 pointer = pointer->next;
3357 void deleteAllResources()
3359 OCResource *pointer = headResource;
3360 OCResource *temp = NULL;
3364 temp = pointer->next;
3365 #ifdef WITH_PRESENCE
3366 if(pointer != (OCResource *) presenceResource.handle)
3368 #endif // WITH_PRESENCE
3369 deleteResource(pointer);
3370 #ifdef WITH_PRESENCE
3372 #endif // WITH_PRESENCE
3376 SRMDeInitSecureResources();
3378 #ifdef WITH_PRESENCE
3379 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3380 // presence notification attributed to their deletion to be processed.
3381 deleteResource((OCResource *) presenceResource.handle);
3382 #endif // WITH_PRESENCE
3385 OCStackResult deleteResource(OCResource *resource)
3387 OCResource *prev = NULL;
3388 OCResource *temp = NULL;
3390 temp = headResource;
3393 if (temp == resource)
3395 // Invalidate all Resource Properties.
3396 resource->resourceProperties = (OCResourceProperty) 0;
3397 #ifdef WITH_PRESENCE
3398 if(resource != (OCResource *) presenceResource.handle)
3400 #endif // WITH_PRESENCE
3401 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3402 #ifdef WITH_PRESENCE
3405 if(presenceResource.handle)
3407 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3408 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
3411 // Only resource in list.
3412 if (temp == headResource && temp == tailResource)
3414 headResource = NULL;
3415 tailResource = NULL;
3418 else if (temp == headResource)
3420 headResource = temp->next;
3423 else if (temp == tailResource)
3425 tailResource = prev;
3426 tailResource->next = NULL;
3430 prev->next = temp->next;
3433 deleteResourceElements(temp);
3444 return OC_STACK_ERROR;
3447 void deleteResourceElements(OCResource *resource)
3455 OICFree(resource->uri);
3457 // Delete resourcetype linked list
3458 deleteResourceType(resource->rsrcType);
3460 // Delete resourceinterface linked list
3461 deleteResourceInterface(resource->rsrcInterface);
3464 void deleteResourceType(OCResourceType *resourceType)
3466 OCResourceType *pointer = resourceType;
3467 OCResourceType *next = NULL;
3471 next = pointer->next;
3472 OICFree(pointer->resourcetypename);
3478 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3480 OCResourceInterface *pointer = resourceInterface;
3481 OCResourceInterface *next = NULL;
3485 next = pointer->next;
3486 OICFree(pointer->name);
3492 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3494 OCResourceType *pointer = NULL;
3495 OCResourceType *previous = NULL;
3496 if (!resource || !resourceType)
3500 // resource type list is empty.
3501 else if (!resource->rsrcType)
3503 resource->rsrcType = resourceType;
3507 pointer = resource->rsrcType;
3511 // resource type already exists. Free 2nd arg and return.
3512 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
3514 OICFree(resourceType->resourcetypename);
3515 OICFree(resourceType);
3519 pointer = pointer->next;
3521 previous->next = resourceType;
3523 resourceType->next = NULL;
3526 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3528 OCResource *resource = NULL;
3529 OCResourceType *pointer = NULL;
3531 // Find the specified resource
3532 resource = findResource((OCResource *) handle);
3538 // Make sure a resource has a resourcetype
3539 if (!resource->rsrcType)
3544 // Iterate through the list
3545 pointer = resource->rsrcType;
3546 for(uint8_t i = 0; i< index && pointer; ++i)
3548 pointer = pointer->next;
3553 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3555 if(resourceTypeList && resourceTypeName)
3557 OCResourceType * rtPointer = resourceTypeList;
3558 while(resourceTypeName && rtPointer)
3560 if(rtPointer->resourcetypename &&
3561 strcmp(resourceTypeName, (const char *)
3562 (rtPointer->resourcetypename)) == 0)
3566 rtPointer = rtPointer->next;
3574 * Insert a new interface into interface linked list only if not already present.
3575 * If alredy present, 2nd arg is free'd.
3576 * Default interface will always be first if present.
3578 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
3580 OCResourceInterface *pointer = NULL;
3581 OCResourceInterface *previous = NULL;
3583 newInterface->next = NULL;
3585 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
3587 if (!*firstInterface)
3589 *firstInterface = newInterface;
3591 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3593 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3595 OICFree(newInterface->name);
3596 OICFree(newInterface);
3601 newInterface->next = *firstInterface;
3602 *firstInterface = newInterface;
3607 pointer = *firstInterface;
3610 if (strcmp(newInterface->name, pointer->name) == 0)
3612 OICFree(newInterface->name);
3613 OICFree(newInterface);
3617 pointer = pointer->next;
3619 previous->next = newInterface;
3623 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3626 OCResource *resource = NULL;
3627 OCResourceInterface *pointer = NULL;
3629 // Find the specified resource
3630 resource = findResource((OCResource *) handle);
3636 // Make sure a resource has a resourceinterface
3637 if (!resource->rsrcInterface)
3642 // Iterate through the list
3643 pointer = resource->rsrcInterface;
3645 for (uint8_t i = 0; i < index && pointer; ++i)
3647 pointer = pointer->next;
3653 * This function splits the uri using the '?' delimiter.
3654 * "uriWithoutQuery" is the block of characters between the beginning
3655 * till the delimiter or '\0' which ever comes first.
3656 * "query" is whatever is to the right of the delimiter if present.
3657 * No delimiter sets the query to NULL.
3658 * If either are present, they will be malloc'ed into the params 2, 3.
3659 * The first param, *uri is left untouched.
3661 * NOTE: This function does not account for whitespace at the end of the uri NOR
3662 * malformed uri's with '??'. Whitespace at the end will be assumed to be
3663 * part of the query.
3665 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
3669 return OC_STACK_INVALID_URI;
3671 if(!query || !uriWithoutQuery)
3673 return OC_STACK_INVALID_PARAM;
3677 *uriWithoutQuery = NULL;
3679 size_t uriWithoutQueryLen = 0;
3680 size_t queryLen = 0;
3681 size_t uriLen = strlen(uri);
3683 char *pointerToDelimiter = strstr(uri, "?");
3685 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : pointerToDelimiter - uri;
3686 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
3688 if (uriWithoutQueryLen)
3690 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
3691 if (!*uriWithoutQuery)
3695 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
3699 *query = (char *) OICCalloc(queryLen + 1, 1);
3702 OICFree(*uriWithoutQuery);
3703 *uriWithoutQuery = NULL;
3706 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
3712 return OC_STACK_NO_MEMORY;
3715 const uint8_t* OCGetServerInstanceID(void)
3717 static bool generated = false;
3718 static ServerID sid;
3724 if (OCGenerateUuid(sid) != RAND_UUID_OK)
3726 OC_LOG(FATAL, TAG, PCF("Generate UUID for Server Instance failed!"));
3733 const char* OCGetServerInstanceIDString(void)
3735 static bool generated = false;
3736 static char sidStr[UUID_STRING_SIZE];
3743 const uint8_t* sid = OCGetServerInstanceID();
3745 if(OCConvertUuidToString(sid, sidStr) != RAND_UUID_OK)
3747 OC_LOG(FATAL, TAG, PCF("Generate UUID String for Server Instance failed!"));
3755 CAResult_t OCSelectNetwork()
3757 CAResult_t retResult = CA_STATUS_FAILED;
3758 CAResult_t caResult = CA_STATUS_OK;
3760 CATransportAdapter_t connTypes[] = {
3762 CA_ADAPTER_RFCOMM_BTEDR,
3763 CA_ADAPTER_GATT_BTLE};
3764 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
3766 for(int i = 0; i<numConnTypes; i++)
3768 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
3769 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
3771 caResult = CASelectNetwork(connTypes[i]);
3772 if(caResult == CA_STATUS_OK)
3774 retResult = CA_STATUS_OK;
3779 if(retResult != CA_STATUS_OK)
3781 return caResult; // Returns error of appropriate transport that failed fatally.
3787 OCStackResult CAResultToOCResult(CAResult_t caResult)
3793 case CA_STATUS_INVALID_PARAM:
3794 return OC_STACK_INVALID_PARAM;
3795 case CA_ADAPTER_NOT_ENABLED:
3796 return OC_STACK_ADAPTER_NOT_ENABLED;
3797 case CA_SERVER_STARTED_ALREADY:
3799 case CA_SERVER_NOT_STARTED:
3800 return OC_STACK_ERROR;
3801 case CA_DESTINATION_NOT_REACHABLE:
3802 return OC_STACK_COMM_ERROR;
3803 case CA_SOCKET_OPERATION_FAILED:
3804 return OC_STACK_COMM_ERROR;
3805 case CA_SEND_FAILED:
3806 return OC_STACK_COMM_ERROR;
3807 case CA_RECEIVE_FAILED:
3808 return OC_STACK_COMM_ERROR;
3809 case CA_MEMORY_ALLOC_FAILED:
3810 return OC_STACK_NO_MEMORY;
3811 case CA_REQUEST_TIMEOUT:
3812 return OC_STACK_TIMEOUT;
3813 case CA_DESTINATION_DISCONNECTED:
3814 return OC_STACK_COMM_ERROR;
3815 case CA_STATUS_FAILED:
3816 return OC_STACK_ERROR;
3817 case CA_NOT_SUPPORTED:
3818 return OC_STACK_NOTIMPL;
3820 return OC_STACK_ERROR;