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 not interested in our notifications"));
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);
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"));
489 case OC_OBSERVER_STILL_INTERESTED:
490 OC_LOG(DEBUG, TAG, PCF("observer still interested, reset the failedCount"));
491 observer = GetObserverUsingToken (token, tokenLength);
494 observer->forceHighQos = 0;
495 observer->failedCommCount = 0;
496 result = OC_STACK_OK;
500 result = OC_STACK_OBSERVER_NOT_FOUND;
504 case OC_OBSERVER_FAILED_COMM:
505 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
506 observer = GetObserverUsingToken (token, tokenLength);
509 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
511 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
512 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0, 0,
513 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
514 if(result != OC_STACK_OK)
516 return OC_STACK_ERROR;
518 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
519 observer->resource->entityHandlerCallbackParam);
521 result = DeleteObserverUsingToken (token, tokenLength);
522 if(result == OC_STACK_OK)
524 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
528 result = OC_STACK_OK;
529 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
534 observer->failedCommCount++;
535 result = OC_STACK_CONTINUE;
537 observer->forceHighQos = 1;
538 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
542 OC_LOG(ERROR, TAG, PCF("Unknown status"));
543 result = OC_STACK_ERROR;
548 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
550 OCStackResult ret = OC_STACK_ERROR;
558 ret = OC_STACK_RESOURCE_CREATED;
561 ret = OC_STACK_RESOURCE_DELETED;
564 ret = OC_STACK_INVALID_QUERY;
566 case CA_UNAUTHORIZED_REQ:
567 ret = OC_STACK_UNAUTHORIZED_REQ;
570 ret = OC_STACK_INVALID_OPTION;
573 ret = OC_STACK_NO_RESOURCE;
575 case CA_RETRANSMIT_TIMEOUT:
576 ret = OC_STACK_COMM_ERROR;
584 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode)
586 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
593 case OC_STACK_RESOURCE_CREATED:
596 case OC_STACK_RESOURCE_DELETED:
599 case OC_STACK_INVALID_QUERY:
602 case OC_STACK_INVALID_OPTION:
605 case OC_STACK_NO_RESOURCE:
608 case OC_STACK_COMM_ERROR:
609 ret = CA_RETRANSMIT_TIMEOUT;
611 case OC_STACK_UNAUTHORIZED_REQ:
612 ret = CA_UNAUTHORIZED_REQ;
620 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
622 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
624 // supply default behavior.
625 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
627 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
629 if ((caFlags & OC_MASK_SCOPE) == 0)
631 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
636 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
638 return (OCTransportFlags)caFlags;
641 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
643 uint32_t lowerBound = 0;
644 uint32_t higherBound = 0;
646 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
648 return OC_STACK_INVALID_PARAM;
651 OC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
653 cbNode->presence->TTL = maxAgeSeconds;
655 for(int index = 0; index < PresenceTimeOutSize; index++)
657 // Guard against overflow
658 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
661 lowerBound = GetTicks((PresenceTimeOut[index] *
662 cbNode->presence->TTL *
663 MILLISECONDS_PER_SECOND)/100);
667 lowerBound = GetTicks(UINT32_MAX);
670 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
673 higherBound = GetTicks((PresenceTimeOut[index + 1] *
674 cbNode->presence->TTL *
675 MILLISECONDS_PER_SECOND)/100);
679 higherBound = GetTicks(UINT32_MAX);
682 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
684 OC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
685 OC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
686 OC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
689 cbNode->presence->TTLlevel = 0;
691 OC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
695 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
697 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
699 return OC_RSRVD_TRIGGER_CREATE;
701 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
703 return OC_RSRVD_TRIGGER_CHANGE;
707 return OC_RSRVD_TRIGGER_DELETE;
711 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
713 if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
715 return OC_PRESENCE_TRIGGER_CREATE;
717 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
719 return OC_PRESENCE_TRIGGER_CHANGE;
723 return OC_PRESENCE_TRIGGER_DELETE;
728 * The cononical presence allows constructed URIs to be string compared.
730 * requestUri must be a char array of size CA_MAX_URI_LENGTH
732 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
735 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
736 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
737 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
741 if ((endpoint->flags & CA_IPV6) && !(endpoint->flags & CA_IPV4))
743 format = "coap://[%s]:%u%s";
747 format = "coap://%s:%u%s";
750 return snprintf(presenceUri, CA_MAX_URI_LENGTH, format, endpoint->addr,
751 endpoint->port, OC_RSRVD_PRESENCE_URI);
755 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
756 const CAResponseInfo_t *responseInfo)
758 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
759 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
761 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
762 ClientCB * cbNode = NULL;
763 char *resourceTypeName = NULL;
764 OCClientResponse response;
765 OCStackResult result = OC_STACK_ERROR;
768 char presenceUri[CA_MAX_URI_LENGTH];
770 int presenceSubscribe = 0;
771 int multicastPresenceSubscribe = 0;
773 if (responseInfo->result != CA_SUCCESS)
775 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
776 return OC_STACK_ERROR;
779 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
780 if (uriLen < 0 || uriLen >= sizeof (presenceUri))
782 return OC_STACK_INVALID_URI;
785 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
788 presenceSubscribe = 1;
792 CAEndpoint_t endpointMulticast;
793 endpointMulticast.flags = endpoint->flags;
794 OICStrcpy(endpointMulticast.addr, sizeof(endpointMulticast.addr), OC_MULTICAST_IP);
795 endpointMulticast.port = OC_MULTICAST_PORT;
797 uriLen = FormCanonicalPresenceUri(&endpointMulticast, OC_RSRVD_PRESENCE_URI, presenceUri);
799 if (uriLen < 0 || uriLen >= sizeof (presenceUri))
801 return OC_STACK_INVALID_URI;
804 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
807 multicastPresenceSubscribe = 1;
811 if (!presenceSubscribe && !multicastPresenceSubscribe)
813 OC_LOG(ERROR, TAG, PCF("Received a presence notification, but no callback, ignoring"));
817 response.payload = NULL;
818 response.result = OC_STACK_OK;
820 CopyEndpointToDevAddr(endpoint, &response.devAddr);
821 FixUpClientResponse(&response);
823 if (responseInfo->info.payload)
825 result = OCParsePayload(&response.payload, responseInfo->info.payload,
826 responseInfo->info.payloadSize);
828 if(result != OC_STACK_OK || response.payload->type != PAYLOAD_TYPE_PRESENCE)
830 OC_LOG(ERROR, TAG, PCF("Presence parse failed"));
833 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
834 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
835 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
838 if (presenceSubscribe)
840 if(cbNode->sequenceNumber == response.sequenceNumber)
842 OC_LOG(INFO, TAG, PCF("No presence change"));
848 OC_LOG(INFO, TAG, PCF("Stopping presence"));
849 response.result = OC_STACK_PRESENCE_STOPPED;
852 OICFree(cbNode->presence->timeOut);
853 OICFree(cbNode->presence);
854 cbNode->presence = NULL;
859 if(!cbNode->presence)
861 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
863 if(!(cbNode->presence))
865 OC_LOG(ERROR, TAG, PCF("Could not allocate memory for cbNode->presence"));
866 result = OC_STACK_NO_MEMORY;
870 VERIFY_NON_NULL_V(cbNode->presence);
871 cbNode->presence->timeOut = NULL;
872 cbNode->presence->timeOut = (uint32_t *)
873 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
874 if(!(cbNode->presence->timeOut)){
876 PCF("Could not allocate memory for cbNode->presence->timeOut"));
877 OICFree(cbNode->presence);
878 result = OC_STACK_NO_MEMORY;
883 ResetPresenceTTL(cbNode, maxAge);
885 cbNode->sequenceNumber = response.sequenceNumber;
887 // Ensure that a filter is actually applied.
888 if( resourceTypeName && cbNode->filterResourceType)
890 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
899 // This is the multicast case
900 OCMulticastNode* mcNode = NULL;
901 mcNode = GetMCPresenceNode(presenceUri);
905 if(mcNode->nonce == response.sequenceNumber)
907 OC_LOG(INFO, TAG, PCF("No presence change (Multicast)"));
910 mcNode->nonce = response.sequenceNumber;
914 OC_LOG(INFO, TAG, PCF("Stopping presence"));
915 response.result = OC_STACK_PRESENCE_STOPPED;
920 char* uri = OICStrdup(presenceUri);
924 PCF("No Memory for URI to store in the presence node"));
925 result = OC_STACK_NO_MEMORY;
929 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
930 if(result == OC_STACK_NO_MEMORY)
933 PCF("No Memory for Multicast Presence Node"));
937 // presence node now owns uri
940 // Ensure that a filter is actually applied.
941 if(resourceTypeName && cbNode->filterResourceType)
943 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
950 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
952 if (cbResult == OC_STACK_DELETE_TRANSACTION)
954 FindAndDeleteClientCB(cbNode);
958 OICFree(resourceTypeName);
962 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
964 VERIFY_NON_NULL_NR(endPoint, FATAL);
965 VERIFY_NON_NULL_NR(responseInfo, FATAL);
966 VERIFY_NON_NULL_NR(responseInfo->info.resourceUri, FATAL);
967 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
969 if(strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
971 HandlePresenceResponse(endPoint, responseInfo);
975 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
976 responseInfo->info.tokenLength, NULL, NULL);
978 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
979 responseInfo->info.tokenLength);
983 OC_LOG(INFO, TAG, PCF("There is a cbNode associated with the response token"));
984 if(responseInfo->result == CA_EMPTY)
986 OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
987 // We do not have a case for the client to receive a RESET
988 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
990 //This is the case of receiving an ACK on a request to a slow resource!
991 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
992 //TODO: should we inform the client
993 // app that at least the request was received at the server?
996 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
998 OC_LOG(INFO, TAG, PCF("Receiving A Timeout for this token"));
999 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1001 OCClientResponse response = {};
1002 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1003 FixUpClientResponse(&response);
1004 response.resourceUri = responseInfo->info.resourceUri;
1006 response.result = CAToOCStackResult(responseInfo->result);
1007 cbNode->callBack(cbNode->context,
1008 cbNode->handle, &response);
1009 FindAndDeleteClientCB(cbNode);
1013 OC_LOG(INFO, TAG, PCF("This is a regular response, A client call back is found"));
1014 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1016 OCClientResponse response = {};
1017 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1018 FixUpClientResponse(&response);
1019 response.resourceUri = responseInfo->info.resourceUri;
1021 response.result = CAToOCStackResult(responseInfo->result);
1022 if(responseInfo->info.payload &&
1023 responseInfo->info.payloadSize &&
1024 OC_STACK_OK != OCParsePayload(&response.payload, responseInfo->info.payload,
1025 responseInfo->info.payloadSize))
1027 OC_LOG(ERROR, TAG, PCF("Error converting payload"));
1031 response.numRcvdVendorSpecificHeaderOptions = 0;
1032 if(responseInfo->info.numOptions > 0)
1035 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1036 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1038 memcpy (&(response.sequenceNumber),
1039 &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
1040 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1045 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1048 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1050 OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
1054 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1056 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1057 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1061 if (cbNode->method == OC_REST_OBSERVE &&
1062 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1063 response.sequenceNumber <= cbNode->sequenceNumber)
1065 OC_LOG_V(INFO, TAG, PCF("Received stale notification. Number :%d"),
1066 response.sequenceNumber);
1070 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1073 cbNode->sequenceNumber = response.sequenceNumber;
1075 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1077 FindAndDeleteClientCB(cbNode);
1081 // To keep discovery callbacks active.
1082 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1083 MILLISECONDS_PER_SECOND);
1085 OCPayloadDestroy(response.payload);
1088 //Need to send ACK when the response is CON
1089 if(responseInfo->info.type == CA_MSG_CONFIRM)
1091 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1092 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0);
1100 OC_LOG(INFO, TAG, PCF("There is an observer associated with the response token"));
1101 if(responseInfo->result == CA_EMPTY)
1103 OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
1104 if(responseInfo->info.type == CA_MSG_RESET)
1106 OC_LOG(INFO, TAG, PCF("This is a RESET"));
1107 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1108 OC_OBSERVER_NOT_INTERESTED);
1110 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1112 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
1113 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1114 OC_OBSERVER_STILL_INTERESTED);
1117 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1119 OC_LOG(INFO, TAG, PCF("Receiving Time Out for an observer"));
1120 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1121 OC_OBSERVER_FAILED_COMM);
1126 if(!cbNode && !observer)
1128 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER)
1130 OC_LOG(INFO, TAG, PCF("This is a client, but no cbNode was found for token"));
1131 if(responseInfo->result == CA_EMPTY)
1133 OC_LOG(INFO, TAG, PCF("Receiving CA_EMPTY in the ocstack"));
1137 OC_LOG(INFO, TAG, PCF("Received a response or notification,\
1138 but I do not have callback. Sending RESET"));
1139 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1140 CA_MSG_RESET, 0, NULL, NULL, 0);
1144 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
1146 OC_LOG(INFO, TAG, PCF("This is a server, but no observer was found for token"));
1147 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1149 OC_LOG_V(INFO, TAG, PCF("Received ACK at server for messageId : %d"),
1150 responseInfo->info.messageId);
1152 if (responseInfo->info.type == CA_MSG_RESET)
1154 OC_LOG_V(INFO, TAG, PCF("Received RESET at server for messageId : %d"),
1155 responseInfo->info.messageId);
1161 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
1165 * This function handles error response from CA
1166 * code shall be added to handle the errors
1168 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1170 OC_LOG(INFO, TAG, PCF("Enter HandleCAErrorResponse"));
1172 if(NULL == endPoint)
1174 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1178 if(NULL == errrorInfo)
1180 OC_LOG(ERROR, TAG, PCF("errrorInfo is NULL"));
1183 OC_LOG(INFO, TAG, PCF("Exit HandleCAErrorResponse"));
1187 * This function sends out Direct Stack Responses. These are responses that are not coming
1188 * from the application entity handler. These responses have no payload and are usually ACKs,
1189 * RESETs or some error conditions that were caught by the stack.
1191 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1192 const CAResponseResult_t responseResult, const CAMessageType_t type,
1193 const uint8_t numOptions, const CAHeaderOption_t *options,
1194 CAToken_t token, uint8_t tokenLength)
1196 CAResponseInfo_t respInfo = {};
1197 respInfo.result = responseResult;
1198 respInfo.info.messageId = coapID;
1199 respInfo.info.numOptions = numOptions;
1200 respInfo.info.options = (CAHeaderOption_t*)options;
1201 respInfo.info.payload = NULL;
1202 respInfo.info.token = token;
1203 respInfo.info.tokenLength = tokenLength;
1204 respInfo.info.type = type;
1206 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1207 if(caResult != CA_STATUS_OK)
1209 OC_LOG(ERROR, TAG, PCF("CASendResponse error"));
1210 return OC_STACK_ERROR;
1215 //This function will be called back by CA layer when a request is received
1216 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1218 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
1221 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1227 OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
1231 OCStackResult requestResult = OC_STACK_ERROR;
1233 if(myStackMode == OC_CLIENT)
1235 //TODO: should the client be responding to requests?
1239 OCServerProtocolRequest serverRequest = {};
1241 OC_LOG_V(INFO, TAG, PCF("Endpoint URI : %s"), requestInfo->info.resourceUri);
1243 char * uriWithoutQuery = NULL;
1244 char * query = NULL;
1246 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1248 if (requestResult != OC_STACK_OK)
1250 OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1253 OC_LOG_V(INFO, TAG, PCF("URI without query: %s"), uriWithoutQuery);
1254 OC_LOG_V(INFO, TAG, PCF("Query : %s"), query);
1256 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1258 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1259 OICFree(uriWithoutQuery);
1263 OC_LOG(ERROR, TAG, PCF("URI length exceeds MAX_URI_LENGTH."));
1264 OICFree(uriWithoutQuery);
1271 if(strlen(query) < MAX_QUERY_LENGTH)
1273 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1278 OC_LOG(ERROR, TAG, PCF("Query length exceeds MAX_QUERY_LENGTH."));
1284 if (requestInfo->info.payload)
1286 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1287 memcpy (&(serverRequest.payload), requestInfo->info.payload,
1288 requestInfo->info.payloadSize);
1292 serverRequest.reqTotalSize = 0;
1295 switch (requestInfo->method)
1298 serverRequest.method = OC_REST_GET;
1301 serverRequest.method = OC_REST_PUT;
1304 serverRequest.method = OC_REST_POST;
1307 serverRequest.method = OC_REST_DELETE;
1310 OC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1311 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1312 requestInfo->info.type, requestInfo->info.numOptions,
1313 requestInfo->info.options, requestInfo->info.token,
1314 requestInfo->info.tokenLength);
1318 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1319 requestInfo->info.tokenLength);
1320 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1321 serverRequest.tokenLength = requestInfo->info.tokenLength;
1323 if (!serverRequest.requestToken)
1325 OC_LOG(FATAL, TAG, "Allocation for token failed.");
1326 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1327 requestInfo->info.type, requestInfo->info.numOptions,
1328 requestInfo->info.options, requestInfo->info.token,
1329 requestInfo->info.tokenLength);
1332 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1334 if (requestInfo->info.type == CA_MSG_CONFIRM)
1336 serverRequest.qos = OC_HIGH_QOS;
1340 serverRequest.qos = OC_LOW_QOS;
1342 // CA does not need the following field
1343 // Are we sure CA does not need them? how is it responding to multicast
1344 serverRequest.delayedResNeeded = 0;
1346 serverRequest.coapID = requestInfo->info.messageId;
1348 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1350 // copy vendor specific header options
1351 uint8_t tempNum = (requestInfo->info.numOptions);
1352 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1353 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1356 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
1357 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1358 requestInfo->info.type, requestInfo->info.numOptions,
1359 requestInfo->info.options, requestInfo->info.token,
1360 requestInfo->info.tokenLength);
1361 OICFree(serverRequest.requestToken);
1364 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1365 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1367 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1368 sizeof(CAHeaderOption_t)*tempNum);
1371 requestResult = HandleStackRequests (&serverRequest);
1373 // Send ACK to client as precursor to slow response
1374 if(requestResult == OC_STACK_SLOW_RESOURCE)
1376 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1377 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0);
1379 else if(requestResult != OC_STACK_OK)
1381 OC_LOG_V(ERROR, TAG, PCF("HandleStackRequests failed. error: %d"), requestResult);
1383 CAResponseResult_t stackResponse = OCToCAStackResult(requestResult);
1385 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1386 requestInfo->info.type, requestInfo->info.numOptions,
1387 requestInfo->info.options, requestInfo->info.token,
1388 requestInfo->info.tokenLength);
1390 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1391 // The token is copied in there, and is thus still owned by this function.
1392 OICFree(serverRequest.requestToken);
1393 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
1396 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1398 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
1399 OCStackResult result = OC_STACK_ERROR;
1400 ResourceHandling resHandling;
1401 OCResource *resource;
1402 if(!protocolRequest)
1404 OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
1405 return OC_STACK_INVALID_PARAM;
1408 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1409 protocolRequest->tokenLength);
1412 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
1413 result = AddServerRequest(&request, protocolRequest->coapID,
1414 protocolRequest->delayedResNeeded, 0,
1415 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
1416 protocolRequest->observationOption, protocolRequest->qos,
1417 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1418 protocolRequest->payload, protocolRequest->requestToken,
1419 protocolRequest->tokenLength,
1420 protocolRequest->resourceUrl, protocolRequest->reqTotalSize,
1421 &protocolRequest->devAddr);
1422 if (OC_STACK_OK != result)
1424 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
1430 OC_LOG(ERROR, TAG, PCF("Out of Memory"));
1431 return OC_STACK_NO_MEMORY;
1434 if(!protocolRequest->reqMorePacket)
1436 request->requestComplete = 1;
1441 OC_LOG(INFO, TAG, PCF("This is either a repeated or blocked Server Request"));
1444 if(request->requestComplete)
1446 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
1447 result = DetermineResourceHandling (request, &resHandling, &resource);
1448 if (result == OC_STACK_OK)
1450 result = ProcessRequest(resHandling, resource, request);
1455 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
1456 result = OC_STACK_CONTINUE;
1461 bool validatePlatformInfo(OCPlatformInfo info)
1464 if (!info.platformID)
1466 OC_LOG(ERROR, TAG, PCF("No platform ID found."));
1470 if (info.manufacturerName)
1472 size_t lenManufacturerName = strlen(info.manufacturerName);
1474 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1476 OC_LOG(ERROR, TAG, PCF("Manufacturer name fails length requirements."));
1482 OC_LOG(ERROR, TAG, PCF("No manufacturer name present"));
1486 if (info.manufacturerUrl)
1488 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1490 OC_LOG(ERROR, TAG, PCF("Manufacturer url fails length requirements."));
1497 //-----------------------------------------------------------------------------
1499 //-----------------------------------------------------------------------------
1501 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1506 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1509 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1511 if(stackState == OC_STACK_INITIALIZED)
1513 OC_LOG(INFO, TAG, PCF("Subsequent calls to OCInit() without calling \
1514 OCStop() between them are ignored."));
1518 OCStackResult result = OC_STACK_ERROR;
1519 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1522 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)))
1524 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1525 return OC_STACK_ERROR;
1529 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1530 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
1532 defaultDeviceHandler = NULL;
1533 defaultDeviceHandlerCallbackParameter = NULL;
1536 result = CAResultToOCResult(CAInitialize());
1537 VERIFY_SUCCESS(result, OC_STACK_OK);
1539 result = CAResultToOCResult(OCSelectNetwork());
1540 VERIFY_SUCCESS(result, OC_STACK_OK);
1542 switch (myStackMode)
1545 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1546 result = CAResultToOCResult(CAStartDiscoveryServer());
1547 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1550 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1551 result = CAResultToOCResult(CAStartListeningServer());
1552 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1554 case OC_CLIENT_SERVER:
1555 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1556 result = CAResultToOCResult(CAStartListeningServer());
1557 if(result == OC_STACK_OK)
1559 result = CAResultToOCResult(CAStartDiscoveryServer());
1563 VERIFY_SUCCESS(result, OC_STACK_OK);
1565 #ifdef WITH_PRESENCE
1566 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1567 #endif // WITH_PRESENCE
1569 //Update Stack state to initialized
1570 stackState = OC_STACK_INITIALIZED;
1572 // Initialize resource
1573 if(myStackMode != OC_CLIENT)
1575 result = initResources();
1578 // Initialize the SRM Policy Engine
1579 if(result == OC_STACK_OK)
1581 result = SRMInitPolicyEngine();
1582 // TODO after BeachHead delivery: consolidate into single SRMInit()
1586 if(result != OC_STACK_OK)
1588 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1589 deleteAllResources();
1591 stackState = OC_STACK_UNINITIALIZED;
1596 OCStackResult OCStop()
1598 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1600 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1602 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1605 else if (stackState != OC_STACK_INITIALIZED)
1607 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1608 return OC_STACK_ERROR;
1611 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1613 #ifdef WITH_PRESENCE
1614 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1615 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1616 presenceResource.presenceTTL = 0;
1617 #endif // WITH_PRESENCE
1619 // Free memory dynamically allocated for resources
1620 deleteAllResources();
1622 DeletePlatformInfo();
1624 // Remove all observers
1625 DeleteObserverList();
1626 // Remove all the client callbacks
1627 DeleteClientCBList();
1629 // De-init the SRM Policy Engine
1630 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
1631 SRMDeInitPolicyEngine();
1634 stackState = OC_STACK_UNINITIALIZED;
1638 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1643 return CA_MSG_CONFIRM;
1648 return CA_MSG_NONCONFIRM;
1652 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1656 query = strchr (inputUri, '?');
1660 if((query - inputUri) > MAX_URI_LENGTH)
1662 return OC_STACK_INVALID_URI;
1665 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1667 return OC_STACK_INVALID_QUERY;
1670 else if(uriLen > MAX_URI_LENGTH)
1672 return OC_STACK_INVALID_URI;
1678 * A request uri consists of the following components in order:
1680 * optional prefix "coap://"
1682 * IPv6 address "[1234::5678]"
1683 * IPv4 address "192.168.1.1"
1684 * optional port ":5683"
1685 * resource uri "/oc/core..."
1687 * for PRESENCE requests, extract resource type.
1689 static OCStackResult ParseRequestUri(const char *fullUri,
1690 OCTransportAdapter adapter,
1691 OCTransportFlags flags,
1692 OCDevAddr **devAddr,
1694 char **resourceType)
1696 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
1698 OCStackResult result = OC_STACK_OK;
1699 OCDevAddr *da = NULL;
1703 // provide defaults for all returned values
1710 *resourceUri = NULL;
1714 *resourceType = NULL;
1717 // delimit url prefix, if any
1718 const char *start = fullUri;
1719 char *slash2 = strstr(start, "//");
1724 char *slash = strchr(start, '/');
1727 return OC_STACK_INVALID_URI;
1730 // processs url prefix, if any
1731 size_t urlLen = slash - start;
1735 if (urlLen && devAddr)
1736 { // construct OCDevAddr
1737 if (OC_ADAPTER_IP == adapter)
1739 if (start[0] == '[')
1741 char *close = strchr(++start, ']');
1742 if (!close || close > slash)
1744 return OC_STACK_INVALID_URI;
1747 if (close[1] == ':')
1755 colon = strchr(start, ':');
1756 end = (colon && colon < slash) ? colon : slash;
1759 if (len >= sizeof(da->addr))
1761 return OC_STACK_INVALID_URI;
1763 // use standard multicast port
1764 if (colon && colon < slash)
1766 for (colon++; colon < slash; colon++)
1769 if (c < '0' || c > '9')
1771 return OC_STACK_INVALID_URI;
1773 port = 10 * port + c - '0';
1780 * This is for Non-IP adapters(EDR and BLE).
1781 * The address will be between "//" and "/" in the request URI.
1782 * [Ex. coap://AB:BC:CD:DE:EF:FG/resource_uri]
1788 if (len >= sizeof(da->addr))
1790 return OC_STACK_INVALID_URI;
1793 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
1796 return OC_STACK_NO_MEMORY;
1798 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
1800 da->adapter = adapter;
1802 if (!strncmp(fullUri, "coaps:", 6))
1804 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
1809 // process resource uri, if any
1811 { // request uri and query
1812 size_t ulen = strlen(slash); // resource uri length
1813 size_t tlen = 0; // resource type length
1816 static const char *strPresence = "/oc/presence?rt=";
1817 static const size_t lenPresence = 15; // = strlen(presence);
1818 if (!strncmp(slash, strPresence, lenPresence))
1820 type = slash + lenPresence;
1821 tlen = ulen - lenPresence;
1826 *resourceUri = (char *)OICMalloc(ulen + 1);
1829 result = OC_STACK_NO_MEMORY;
1832 strcpy(*resourceUri, slash);
1835 if (type && resourceType)
1837 *resourceType = (char *)OICMalloc(tlen + 1);
1840 result = OC_STACK_NO_MEMORY;
1843 strncpy(*resourceType, type, tlen);
1850 // free all returned values
1857 OICFree(*resourceUri);
1861 OICFree(*resourceType);
1866 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
1867 char *resourceUri, char **requestUri)
1869 char uri[CA_MAX_URI_LENGTH];
1871 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
1873 *requestUri = (char *)OICMalloc(strlen(uri) + 1);
1876 return OC_STACK_NO_MEMORY;
1879 strcpy(*requestUri, uri);
1884 * Discover or Perform requests on a specified resource
1886 OCStackResult OCDoResource(OCDoHandle *handle,
1888 const char *requestUri,
1889 const OCDevAddr *destination,
1891 OCConnectivityType connectivityType,
1892 OCQualityOfService qos,
1893 OCCallbackData *cbData,
1894 OCHeaderOption *options,
1897 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1899 // Validate input parameters
1900 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1901 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1902 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
1904 OCStackResult result = OC_STACK_ERROR;
1905 CAResult_t caResult;
1906 CAToken_t token = NULL;
1907 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
1908 ClientCB *clientCB = NULL;
1909 OCDoHandle resHandle = NULL;
1910 CAEndpoint_t *endpoint = NULL;
1911 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
1913 OCTransportAdapter adapter;
1914 OCTransportFlags flags;
1915 // the request contents are put here
1916 CARequestInfo_t requestInfo = { CA_GET };
1917 // requestUri will be parsed into the following three variables
1918 OCDevAddr *devAddr = NULL;
1919 char *resourceUri = NULL;
1920 char *resourceType = NULL;
1922 // To track if memory is allocated for additional header options
1923 uint8_t hdrOptionMemAlloc = 0;
1925 // This validation is broken, but doesn't cause harm
1926 size_t uriLen = strlen(requestUri );
1927 if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
1933 * Support original behavior with address on resourceUri argument.
1935 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
1936 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
1938 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
1940 if (result != OC_STACK_OK)
1942 OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
1949 case OC_REST_OBSERVE:
1950 case OC_REST_OBSERVE_ALL:
1951 case OC_REST_CANCEL_OBSERVE:
1952 requestInfo.method = CA_GET;
1955 requestInfo.method = CA_PUT;
1958 requestInfo.method = CA_POST;
1960 case OC_REST_DELETE:
1961 requestInfo.method = CA_DELETE;
1963 case OC_REST_DISCOVER:
1965 if (!destination && !devAddr)
1967 destination = &tmpDevAddr;
1969 // CA_DISCOVER will become GET and isMulticast
1970 requestInfo.method = CA_GET;
1971 requestInfo.isMulticast = true;
1973 #ifdef WITH_PRESENCE
1974 case OC_REST_PRESENCE:
1975 // Replacing method type with GET because "presence"
1976 // is a stack layer only implementation.
1977 requestInfo.method = CA_GET;
1981 result = OC_STACK_INVALID_METHOD;
1985 if (!devAddr && !destination)
1987 OC_LOG_V(DEBUG, TAG, "no devAddr and no destination");
1988 result = OC_STACK_INVALID_PARAM;
1992 /* If not original behavior, use destination argument */
1993 if (destination && !devAddr)
1995 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
1998 result = OC_STACK_NO_MEMORY;
2001 *devAddr = *destination;
2004 resHandle = GenerateInvocationHandle();
2007 result = OC_STACK_NO_MEMORY;
2011 caResult = CAGenerateToken(&token, tokenLength);
2012 if (caResult != CA_STATUS_OK)
2014 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2018 // fill in request data
2019 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2020 requestInfo.info.token = token;
2021 requestInfo.info.tokenLength = tokenLength;
2022 requestInfo.info.resourceUri = resourceUri;
2024 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2026 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2027 options, numOptions, OC_OBSERVE_REGISTER);
2028 if (result != OC_STACK_OK)
2032 hdrOptionMemAlloc = 1;
2033 requestInfo.info.numOptions = numOptions + 1;
2037 requestInfo.info.options = (CAHeaderOption_t*)options;
2038 requestInfo.info.numOptions = numOptions;
2041 // create remote endpoint
2042 result = OCCreateEndpoint(devAddr, &endpoint);
2046 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2049 OC_LOG(ERROR, TAG, PCF("Failed to create CBOR Payload"));
2055 requestInfo.info.payload = NULL;
2056 requestInfo.info.payloadSize = 0;
2061 if (result != OC_STACK_OK)
2063 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2067 // prepare for response
2068 #ifdef WITH_PRESENCE
2069 if (method == OC_REST_PRESENCE)
2071 char *presenceUri = NULL;
2072 result = OCPreparePresence(endpoint, resourceUri, &presenceUri);
2073 if (OC_STACK_OK != result)
2078 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2079 // Presence notification will form a canonical uri to
2080 // look for callbacks into the application.
2081 resourceUri = presenceUri;
2085 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2086 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2087 method, devAddr, resourceUri, resourceType, ttl);
2088 if (OC_STACK_OK != result)
2093 devAddr = NULL; // Client CB list entry now owns it
2094 resourceUri = NULL; // Client CB list entry now owns it
2095 resourceType = NULL; // Client CB list entry now owns it
2098 caResult = CASendRequest(endpoint, &requestInfo);
2099 if (caResult != CA_STATUS_OK)
2101 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
2102 result = OC_STACK_COMM_ERROR;
2108 *handle = resHandle;
2112 if (result != OC_STACK_OK)
2114 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
2115 FindAndDeleteClientCB(clientCB);
2116 CADestroyToken(token);
2124 // This is the owner of the payload object, so we free it
2125 OCPayloadDestroy(payload);
2127 OICFree(resourceUri);
2128 OICFree(resourceType);
2130 if (hdrOptionMemAlloc)
2132 OICFree(requestInfo.info.options);
2137 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2141 * This ftn is implemented one of two ways in the case of observation:
2143 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2144 * Remove the callback associated on client side.
2145 * When the next notification comes in from server,
2146 * reply with RESET message to server.
2147 * Keep in mind that the server will react to RESET only
2148 * if the last notification was sent as CON
2150 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2151 * and it is associated with an observe request
2152 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2153 * Send CON Observe request to server with
2154 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2155 * Remove the callback associated on client side.
2157 OCStackResult ret = OC_STACK_OK;
2158 CAEndpoint_t* endpoint = NULL;
2159 CAResult_t caResult;
2160 CAInfo_t requestData = {};
2161 CARequestInfo_t requestInfo = {};
2165 return OC_STACK_INVALID_PARAM;
2168 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2171 OC_LOG(ERROR, TAG, PCF("Client callback not found. Called OCCancel twice?"));
2175 switch (clientCB->method)
2177 case OC_REST_OBSERVE:
2178 case OC_REST_OBSERVE_ALL:
2179 OC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
2180 clientCB->requestUri);
2181 if (qos != OC_HIGH_QOS)
2183 FindAndDeleteClientCB(clientCB);
2188 OC_LOG(INFO, TAG, PCF("Cancelling observation as CONFIRMABLE"));
2191 requestData.type = qualityOfServiceToMessageType(qos);
2192 requestData.token = clientCB->token;
2193 requestData.tokenLength = clientCB->tokenLength;
2194 if (CreateObserveHeaderOption (&(requestData.options),
2195 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2197 return OC_STACK_ERROR;
2199 requestData.numOptions = numOptions + 1;
2200 requestData.resourceUri = OICStrdup (clientCB->requestUri);
2202 requestInfo.method = CA_GET;
2203 requestInfo.info = requestData;
2205 ret = OCCreateEndpoint(clientCB->devAddr, &endpoint);
2206 if (ret != OC_STACK_OK)
2208 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2213 caResult = CASendRequest(endpoint, &requestInfo);
2214 if (caResult != CA_STATUS_OK)
2216 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2217 ret = OC_STACK_ERROR;
2219 ret = CAResultToOCResult (caResult);
2222 #ifdef WITH_PRESENCE
2223 case OC_REST_PRESENCE:
2224 FindAndDeleteClientCB(clientCB);
2229 ret = OC_STACK_INVALID_METHOD;
2234 OCDestroyEndpoint(endpoint);
2235 if (requestData.numOptions > 0)
2237 OICFree(requestData.options);
2239 if (requestData.resourceUri)
2241 OICFree (requestData.resourceUri);
2248 * @brief Register Persistent storage callback.
2249 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2251 * OC_STACK_OK - No errors; Success
2252 * OC_STACK_INVALID_PARAM - Invalid parameter
2254 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2256 OC_LOG(INFO, TAG, PCF("RegisterPersistentStorageHandler !!"));
2257 if(!persistentStorageHandler)
2259 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2260 return OC_STACK_INVALID_PARAM;
2264 if( !persistentStorageHandler->open ||
2265 !persistentStorageHandler->close ||
2266 !persistentStorageHandler->read ||
2267 !persistentStorageHandler->unlink ||
2268 !persistentStorageHandler->write)
2270 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2271 return OC_STACK_INVALID_PARAM;
2274 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2277 #ifdef WITH_PRESENCE
2279 OCStackResult OCProcessPresence()
2281 OCStackResult result = OC_STACK_OK;
2283 // the following line floods the log with messages that are irrelevant
2284 // to most purposes. Uncomment as needed.
2285 //OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
2286 ClientCB* cbNode = NULL;
2287 OCClientResponse clientResponse;
2288 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2290 LL_FOREACH(cbList, cbNode)
2292 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2297 uint32_t now = GetTicks(0);
2298 OC_LOG_V(DEBUG, TAG, "this TTL level %d",
2299 cbNode->presence->TTLlevel);
2300 OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2302 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
2307 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2309 OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2310 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2313 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2315 OC_LOG(DEBUG, TAG, PCF("No more timeout ticks"));
2317 clientResponse.sequenceNumber = 0;
2318 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2319 clientResponse.devAddr = *cbNode->devAddr;
2320 FixUpClientResponse(&clientResponse);
2321 clientResponse.payload = NULL;
2323 // Increment the TTLLevel (going to a next state), so we don't keep
2324 // sending presence notification to client.
2325 cbNode->presence->TTLlevel++;
2326 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2327 cbNode->presence->TTLlevel);
2329 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2330 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2332 FindAndDeleteClientCB(cbNode);
2336 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2341 CAResult_t caResult = CA_STATUS_OK;
2342 CAEndpoint_t* endpoint = NULL;
2343 CAInfo_t requestData ={};
2344 CARequestInfo_t requestInfo = {};
2346 OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
2348 result = OCCreateEndpoint(cbNode->devAddr, &endpoint);
2349 if (result != OC_STACK_OK)
2351 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2355 requestData.type = CA_MSG_NONCONFIRM;
2356 requestData.token = cbNode->token;
2357 requestData.tokenLength = cbNode->tokenLength;
2358 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2359 requestInfo.method = CA_GET;
2360 requestInfo.info = requestData;
2362 caResult = CASendRequest(endpoint, &requestInfo);
2363 OCDestroyEndpoint(endpoint);
2365 if (caResult != CA_STATUS_OK)
2367 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2371 cbNode->presence->TTLlevel++;
2372 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2375 if (result != OC_STACK_OK)
2377 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2381 #endif // WITH_PRESENCE
2383 OCStackResult OCProcess()
2385 #ifdef WITH_PRESENCE
2386 OCProcessPresence();
2388 CAHandleRequestResponse();
2393 #ifdef WITH_PRESENCE
2394 OCStackResult OCStartPresence(const uint32_t ttl)
2396 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2397 OCChangeResourceProperty(
2398 &(((OCResource *)presenceResource.handle)->resourceProperties),
2401 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2403 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2404 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to max value"));
2408 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2409 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to default value"));
2413 presenceResource.presenceTTL = ttl;
2415 OC_LOG_V(DEBUG, TAG, "Presence TTL is %lu seconds", presenceResource.presenceTTL);
2417 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2419 presenceState = OC_PRESENCE_INITIALIZED;
2421 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2422 OICStrcpy(devAddr.addr, sizeof(devAddr.addr), OC_MULTICAST_IP);
2423 devAddr.port = OC_MULTICAST_PORT;
2425 CAToken_t caToken = NULL;
2426 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2427 if (caResult != CA_STATUS_OK)
2429 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2430 CADestroyToken(caToken);
2431 return OC_STACK_ERROR;
2434 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2435 (OCResource *)presenceResource.handle, OC_LOW_QOS, &devAddr);
2436 CADestroyToken(caToken);
2439 // Each time OCStartPresence is called
2440 // a different random 32-bit integer number is used
2441 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2443 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2444 OC_PRESENCE_TRIGGER_CREATE);
2447 OCStackResult OCStopPresence()
2449 OCStackResult result = OC_STACK_ERROR;
2451 if(presenceResource.handle)
2453 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2455 // make resource inactive
2456 result = OCChangeResourceProperty(
2457 &(((OCResource *) presenceResource.handle)->resourceProperties),
2461 if(result != OC_STACK_OK)
2464 PCF("Changing the presence resource properties to ACTIVE not successful"));
2468 return SendStopNotification();
2472 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
2473 void* callbackParameter)
2475 defaultDeviceHandler = entityHandler;
2476 defaultDeviceHandlerCallbackParameter = callbackParameter;
2481 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
2483 OC_LOG(INFO, TAG, PCF("Entering OCSetPlatformInfo"));
2485 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
2487 if (validatePlatformInfo(platformInfo))
2489 return SavePlatformInfo(platformInfo);
2493 return OC_STACK_INVALID_PARAM;
2498 return OC_STACK_ERROR;
2502 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2504 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2506 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
2508 OC_LOG(ERROR, TAG, PCF("Null or empty device name."));
2509 return OC_STACK_INVALID_PARAM;
2512 return SaveDeviceInfo(deviceInfo);
2515 OCStackResult OCCreateResource(OCResourceHandle *handle,
2516 const char *resourceTypeName,
2517 const char *resourceInterfaceName,
2518 const char *uri, OCEntityHandler entityHandler,
2519 void* callbackParam,
2520 uint8_t resourceProperties)
2523 OCResource *pointer = NULL;
2525 OCStackResult result = OC_STACK_ERROR;
2527 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2529 if(myStackMode == OC_CLIENT)
2531 return OC_STACK_INVALID_PARAM;
2533 // Validate parameters
2534 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2536 OC_LOG(ERROR, TAG, PCF("URI is empty or too long"));
2537 return OC_STACK_INVALID_URI;
2539 // Is it presented during resource discovery?
2540 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
2542 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2543 return OC_STACK_INVALID_PARAM;
2546 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2548 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2551 // Make sure resourceProperties bitmask has allowed properties specified
2552 if (resourceProperties
2553 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE))
2555 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2556 return OC_STACK_INVALID_PARAM;
2559 // If the headResource is NULL, then no resources have been created...
2560 pointer = headResource;
2563 // At least one resources is in the resource list, so we need to search for
2564 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2567 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
2569 OC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
2570 return OC_STACK_INVALID_PARAM;
2572 pointer = pointer->next;
2575 // Create the pointer and insert it into the resource list
2576 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
2579 result = OC_STACK_NO_MEMORY;
2582 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2584 insertResource(pointer);
2587 str = OICStrdup(uri);
2590 result = OC_STACK_NO_MEMORY;
2595 // Set properties. Set OC_ACTIVE
2596 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2599 // Add the resourcetype to the resource
2600 result = BindResourceTypeToResource(pointer, resourceTypeName);
2601 if (result != OC_STACK_OK)
2603 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2607 // Add the resourceinterface to the resource
2608 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2609 if (result != OC_STACK_OK)
2611 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2615 // If an entity handler has been passed, attach it to the newly created
2616 // resource. Otherwise, set the default entity handler.
2619 pointer->entityHandler = entityHandler;
2620 pointer->entityHandlerCallbackParam = callbackParam;
2624 pointer->entityHandler = defaultResourceEHandler;
2625 pointer->entityHandlerCallbackParam = NULL;
2629 result = OC_STACK_OK;
2631 #ifdef WITH_PRESENCE
2632 if(presenceResource.handle)
2634 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2635 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
2639 if (result != OC_STACK_OK)
2641 // Deep delete of resource and other dynamic elements that it contains
2642 deleteResource(pointer);
2649 OCStackResult OCBindResource(
2650 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2652 OCResource *resource = NULL;
2655 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2657 // Validate parameters
2658 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2659 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2660 // Container cannot contain itself
2661 if (collectionHandle == resourceHandle)
2663 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2664 return OC_STACK_INVALID_PARAM;
2667 // Use the handle to find the resource in the resource linked list
2668 resource = findResource((OCResource *) collectionHandle);
2671 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2672 return OC_STACK_INVALID_PARAM;
2675 // Look for an open slot to add add the child resource.
2676 // If found, add it and return success
2677 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2679 if (!resource->rsrcResources[i])
2681 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2682 OC_LOG(INFO, TAG, PCF("resource bound"));
2684 #ifdef WITH_PRESENCE
2685 if(presenceResource.handle)
2687 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2688 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2689 OC_PRESENCE_TRIGGER_CHANGE);
2697 // Unable to add resourceHandle, so return error
2698 return OC_STACK_ERROR;
2701 OCStackResult OCUnBindResource(
2702 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2704 OCResource *resource = NULL;
2707 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2709 // Validate parameters
2710 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2711 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2712 // Container cannot contain itself
2713 if (collectionHandle == resourceHandle)
2715 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2716 return OC_STACK_INVALID_PARAM;
2719 // Use the handle to find the resource in the resource linked list
2720 resource = findResource((OCResource *) collectionHandle);
2723 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2724 return OC_STACK_INVALID_PARAM;
2727 // Look for an open slot to add add the child resource.
2728 // If found, add it and return success
2729 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2731 if (resourceHandle == resource->rsrcResources[i])
2733 resource->rsrcResources[i] = (OCResource *) NULL;
2734 OC_LOG(INFO, TAG, PCF("resource unbound"));
2736 // Send notification when resource is unbounded successfully.
2737 #ifdef WITH_PRESENCE
2738 if(presenceResource.handle)
2740 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2741 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2742 OC_PRESENCE_TRIGGER_CHANGE);
2749 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2751 // Unable to add resourceHandle, so return error
2752 return OC_STACK_ERROR;
2755 OCStackResult BindResourceTypeToResource(OCResource* resource,
2756 const char *resourceTypeName)
2758 OCResourceType *pointer = NULL;
2760 OCStackResult result = OC_STACK_ERROR;
2762 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2764 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
2767 result = OC_STACK_NO_MEMORY;
2771 str = OICStrdup(resourceTypeName);
2774 result = OC_STACK_NO_MEMORY;
2777 pointer->resourcetypename = str;
2779 insertResourceType(resource, pointer);
2780 result = OC_STACK_OK;
2783 if (result != OC_STACK_OK)
2792 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2793 const char *resourceInterfaceName)
2795 OCResourceInterface *pointer = NULL;
2797 OCStackResult result = OC_STACK_ERROR;
2799 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2801 OC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
2803 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
2806 result = OC_STACK_NO_MEMORY;
2810 str = OICStrdup(resourceInterfaceName);
2813 result = OC_STACK_NO_MEMORY;
2816 pointer->name = str;
2818 // Bind the resourceinterface to the resource
2819 insertResourceInterface(resource, pointer);
2821 result = OC_STACK_OK;
2824 if (result != OC_STACK_OK)
2833 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2834 const char *resourceTypeName)
2837 OCStackResult result = OC_STACK_ERROR;
2838 OCResource *resource = NULL;
2840 resource = findResource((OCResource *) handle);
2843 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2844 return OC_STACK_ERROR;
2847 result = BindResourceTypeToResource(resource, resourceTypeName);
2849 #ifdef WITH_PRESENCE
2850 if(presenceResource.handle)
2852 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2853 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2860 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2861 const char *resourceInterfaceName)
2864 OCStackResult result = OC_STACK_ERROR;
2865 OCResource *resource = NULL;
2867 resource = findResource((OCResource *) handle);
2870 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2871 return OC_STACK_ERROR;
2874 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2876 #ifdef WITH_PRESENCE
2877 if(presenceResource.handle)
2879 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2880 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2887 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
2889 OCResource *pointer = headResource;
2891 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2895 *numResources = *numResources + 1;
2896 pointer = pointer->next;
2901 OCResourceHandle OCGetResourceHandle(uint8_t index)
2903 OCResource *pointer = headResource;
2905 for( uint8_t i = 0; i < index && pointer; ++i)
2907 pointer = pointer->next;
2909 return (OCResourceHandle) pointer;
2912 OCStackResult OCDeleteResource(OCResourceHandle handle)
2916 OC_LOG(ERROR, TAG, PCF("Invalid handle for deletion"));
2917 return OC_STACK_INVALID_PARAM;
2920 OCResource *resource = findResource((OCResource *) handle);
2921 if (resource == NULL)
2923 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2924 return OC_STACK_NO_RESOURCE;
2927 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
2929 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2930 return OC_STACK_ERROR;
2936 const char *OCGetResourceUri(OCResourceHandle handle)
2938 OCResource *resource = NULL;
2940 resource = findResource((OCResource *) handle);
2943 return resource->uri;
2945 return (const char *) NULL;
2948 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
2950 OCResource *resource = NULL;
2952 resource = findResource((OCResource *) handle);
2955 return resource->resourceProperties;
2957 return (OCResourceProperty)-1;
2960 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2961 uint8_t *numResourceTypes)
2963 OCResource *resource = NULL;
2964 OCResourceType *pointer = NULL;
2966 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2967 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2969 *numResourceTypes = 0;
2971 resource = findResource((OCResource *) handle);
2974 pointer = resource->rsrcType;
2977 *numResourceTypes = *numResourceTypes + 1;
2978 pointer = pointer->next;
2984 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
2986 OCResourceType *resourceType = NULL;
2988 resourceType = findResourceTypeAtIndex(handle, index);
2991 return resourceType->resourcetypename;
2993 return (const char *) NULL;
2996 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2997 uint8_t *numResourceInterfaces)
2999 OCResourceInterface *pointer = NULL;
3000 OCResource *resource = NULL;
3002 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3003 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3005 *numResourceInterfaces = 0;
3006 resource = findResource((OCResource *) handle);
3009 pointer = resource->rsrcInterface;
3012 *numResourceInterfaces = *numResourceInterfaces + 1;
3013 pointer = pointer->next;
3019 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3021 OCResourceInterface *resourceInterface = NULL;
3023 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3024 if (resourceInterface)
3026 return resourceInterface->name;
3028 return (const char *) NULL;
3031 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3034 OCResource *resource = NULL;
3036 if (index >= MAX_CONTAINED_RESOURCES)
3041 resource = findResource((OCResource *) collectionHandle);
3047 return resource->rsrcResources[index];
3050 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3051 OCEntityHandler entityHandler,
3052 void* callbackParam)
3054 OCResource *resource = NULL;
3056 // Validate parameters
3057 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3059 // Use the handle to find the resource in the resource linked list
3060 resource = findResource((OCResource *)handle);
3063 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3064 return OC_STACK_ERROR;
3068 resource->entityHandler = entityHandler;
3069 resource->entityHandlerCallbackParam = callbackParam;
3071 #ifdef WITH_PRESENCE
3072 if(presenceResource.handle)
3074 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3075 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3082 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3084 OCResource *resource = NULL;
3086 resource = findResource((OCResource *)handle);
3089 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3094 return resource->entityHandler;
3097 void incrementSequenceNumber(OCResource * resPtr)
3099 // Increment the sequence number
3100 resPtr->sequenceNum += 1;
3101 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3103 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3108 #ifdef WITH_PRESENCE
3109 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3110 OCPresenceTrigger trigger)
3112 OCResource *resPtr = NULL;
3113 OCStackResult result = OC_STACK_ERROR;
3114 OCMethod method = OC_REST_PRESENCE;
3115 uint32_t maxAge = 0;
3116 resPtr = findResource((OCResource *) presenceResource.handle);
3119 return OC_STACK_NO_RESOURCE;
3122 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3124 maxAge = presenceResource.presenceTTL;
3126 result = SendAllObserverNotification(method, resPtr, maxAge,
3127 trigger, resourceType, OC_LOW_QOS);
3133 OCStackResult SendStopNotification()
3135 OCResource *resPtr = NULL;
3136 OCStackResult result = OC_STACK_ERROR;
3137 OCMethod method = OC_REST_PRESENCE;
3138 resPtr = findResource((OCResource *) presenceResource.handle);
3141 return OC_STACK_NO_RESOURCE;
3144 // maxAge is 0. ResourceType is NULL.
3145 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3151 #endif // WITH_PRESENCE
3152 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3154 OCResource *resPtr = NULL;
3155 OCStackResult result = OC_STACK_ERROR;
3156 OCMethod method = OC_REST_NOMETHOD;
3157 uint32_t maxAge = 0;
3159 OC_LOG(INFO, TAG, PCF("Notifying all observers"));
3160 #ifdef WITH_PRESENCE
3161 if(handle == presenceResource.handle)
3165 #endif // WITH_PRESENCE
3166 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3168 // Verify that the resource exists
3169 resPtr = findResource ((OCResource *) handle);
3172 return OC_STACK_NO_RESOURCE;
3176 //only increment in the case of regular observing (not presence)
3177 incrementSequenceNumber(resPtr);
3178 method = OC_REST_OBSERVE;
3179 maxAge = MAX_OBSERVE_AGE;
3180 #ifdef WITH_PRESENCE
3181 result = SendAllObserverNotification (method, resPtr, maxAge,
3182 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3184 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3191 OCNotifyListOfObservers (OCResourceHandle handle,
3192 OCObservationId *obsIdList,
3193 uint8_t numberOfIds,
3194 const OCRepPayload *payload,
3195 OCQualityOfService qos)
3197 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3199 OCResource *resPtr = NULL;
3200 //TODO: we should allow the server to define this
3201 uint32_t maxAge = MAX_OBSERVE_AGE;
3203 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3204 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3205 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3207 resPtr = findResource ((OCResource *) handle);
3208 if (NULL == resPtr || myStackMode == OC_CLIENT)
3210 return OC_STACK_NO_RESOURCE;
3214 incrementSequenceNumber(resPtr);
3216 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3217 payload, maxAge, qos));
3220 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3222 OCStackResult result = OC_STACK_ERROR;
3223 OCServerRequest *serverRequest = NULL;
3225 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3227 // Validate input parameters
3228 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3229 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3232 // Get pointer to request info
3233 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3236 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3237 result = serverRequest->ehResponseHandler(ehResponse);
3243 //-----------------------------------------------------------------------------
3244 // Private internal function definitions
3245 //-----------------------------------------------------------------------------
3246 static OCDoHandle GenerateInvocationHandle()
3248 OCDoHandle handle = NULL;
3249 // Generate token here, it will be deleted when the transaction is deleted
3250 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3253 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3259 #ifdef WITH_PRESENCE
3260 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3261 OCResourceProperty resourceProperties, uint8_t enable)
3265 return OC_STACK_INVALID_PARAM;
3267 if (resourceProperties
3268 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3270 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3271 return OC_STACK_INVALID_PARAM;
3275 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3279 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3285 OCStackResult initResources()
3287 OCStackResult result = OC_STACK_OK;
3289 headResource = NULL;
3290 tailResource = NULL;
3291 // Init Virtual Resources
3292 #ifdef WITH_PRESENCE
3293 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3295 result = OCCreateResource(&presenceResource.handle,
3296 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3298 OC_RSRVD_PRESENCE_URI,
3302 //make resource inactive
3303 result = OCChangeResourceProperty(
3304 &(((OCResource *) presenceResource.handle)->resourceProperties),
3308 if (result == OC_STACK_OK)
3310 result = SRMInitSecureResources();
3316 void insertResource(OCResource *resource)
3320 headResource = resource;
3321 tailResource = resource;
3325 tailResource->next = resource;
3326 tailResource = resource;
3328 resource->next = NULL;
3331 OCResource *findResource(OCResource *resource)
3333 OCResource *pointer = headResource;
3337 if (pointer == resource)
3341 pointer = pointer->next;
3346 void deleteAllResources()
3348 OCResource *pointer = headResource;
3349 OCResource *temp = NULL;
3353 temp = pointer->next;
3354 #ifdef WITH_PRESENCE
3355 if(pointer != (OCResource *) presenceResource.handle)
3357 #endif // WITH_PRESENCE
3358 deleteResource(pointer);
3359 #ifdef WITH_PRESENCE
3361 #endif // WITH_PRESENCE
3365 SRMDeInitSecureResources();
3367 #ifdef WITH_PRESENCE
3368 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3369 // presence notification attributed to their deletion to be processed.
3370 deleteResource((OCResource *) presenceResource.handle);
3371 #endif // WITH_PRESENCE
3374 OCStackResult deleteResource(OCResource *resource)
3376 OCResource *prev = NULL;
3377 OCResource *temp = NULL;
3380 OC_LOG_V(DEBUG,TAG,"resource is NULL");
3381 return OC_STACK_INVALID_PARAM;
3384 OC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
3386 temp = headResource;
3389 if (temp == resource)
3391 // Invalidate all Resource Properties.
3392 resource->resourceProperties = (OCResourceProperty) 0;
3393 #ifdef WITH_PRESENCE
3394 if(resource != (OCResource *) presenceResource.handle)
3396 #endif // WITH_PRESENCE
3397 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3398 #ifdef WITH_PRESENCE
3401 if(presenceResource.handle)
3403 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3404 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
3407 // Only resource in list.
3408 if (temp == headResource && temp == tailResource)
3410 headResource = NULL;
3411 tailResource = NULL;
3414 else if (temp == headResource)
3416 headResource = temp->next;
3419 else if (temp == tailResource)
3421 tailResource = prev;
3422 tailResource->next = NULL;
3426 prev->next = temp->next;
3429 deleteResourceElements(temp);
3440 return OC_STACK_ERROR;
3443 void deleteResourceElements(OCResource *resource)
3450 OICFree(resource->uri);
3451 deleteResourceType(resource->rsrcType);
3452 deleteResourceInterface(resource->rsrcInterface);
3455 void deleteResourceType(OCResourceType *resourceType)
3457 OCResourceType *pointer = resourceType;
3458 OCResourceType *next = NULL;
3462 next = pointer->next;
3463 OICFree(pointer->resourcetypename);
3469 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3471 OCResourceInterface *pointer = resourceInterface;
3472 OCResourceInterface *next = NULL;
3476 next = pointer->next;
3477 OICFree(pointer->name);
3483 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3485 OCResourceType *pointer = NULL;
3486 OCResourceType *previous = NULL;
3487 if (!resource || !resourceType)
3491 // resource type list is empty.
3492 else if (!resource->rsrcType)
3494 resource->rsrcType = resourceType;
3498 pointer = resource->rsrcType;
3502 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
3504 OC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
3505 OICFree(resourceType->resourcetypename);
3506 OICFree(resourceType);
3510 pointer = pointer->next;
3512 previous->next = resourceType;
3514 resourceType->next = NULL;
3516 OC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
3519 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3521 OCResource *resource = NULL;
3522 OCResourceType *pointer = NULL;
3524 // Find the specified resource
3525 resource = findResource((OCResource *) handle);
3531 // Make sure a resource has a resourcetype
3532 if (!resource->rsrcType)
3537 // Iterate through the list
3538 pointer = resource->rsrcType;
3539 for(uint8_t i = 0; i< index && pointer; ++i)
3541 pointer = pointer->next;
3546 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3548 if(resourceTypeList && resourceTypeName)
3550 OCResourceType * rtPointer = resourceTypeList;
3551 while(resourceTypeName && rtPointer)
3553 if(rtPointer->resourcetypename &&
3554 strcmp(resourceTypeName, (const char *)
3555 (rtPointer->resourcetypename)) == 0)
3559 rtPointer = rtPointer->next;
3567 * Insert a new interface into interface linked list only if not already present.
3568 * If alredy present, 2nd arg is free'd.
3569 * Default interface will always be first if present.
3571 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
3573 OCResourceInterface *pointer = NULL;
3574 OCResourceInterface *previous = NULL;
3576 newInterface->next = NULL;
3578 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
3580 if (!*firstInterface)
3582 *firstInterface = newInterface;
3584 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3586 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3588 OICFree(newInterface->name);
3589 OICFree(newInterface);
3594 newInterface->next = *firstInterface;
3595 *firstInterface = newInterface;
3600 pointer = *firstInterface;
3603 if (strcmp(newInterface->name, pointer->name) == 0)
3605 OICFree(newInterface->name);
3606 OICFree(newInterface);
3610 pointer = pointer->next;
3612 previous->next = newInterface;
3616 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3619 OCResource *resource = NULL;
3620 OCResourceInterface *pointer = NULL;
3622 // Find the specified resource
3623 resource = findResource((OCResource *) handle);
3629 // Make sure a resource has a resourceinterface
3630 if (!resource->rsrcInterface)
3635 // Iterate through the list
3636 pointer = resource->rsrcInterface;
3638 for (uint8_t i = 0; i < index && pointer; ++i)
3640 pointer = pointer->next;
3646 * This function splits the uri using the '?' delimiter.
3647 * "uriWithoutQuery" is the block of characters between the beginning
3648 * till the delimiter or '\0' which ever comes first.
3649 * "query" is whatever is to the right of the delimiter if present.
3650 * No delimiter sets the query to NULL.
3651 * If either are present, they will be malloc'ed into the params 2, 3.
3652 * The first param, *uri is left untouched.
3654 * NOTE: This function does not account for whitespace at the end of the uri NOR
3655 * malformed uri's with '??'. Whitespace at the end will be assumed to be
3656 * part of the query.
3658 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
3662 return OC_STACK_INVALID_URI;
3664 if(!query || !uriWithoutQuery)
3666 return OC_STACK_INVALID_PARAM;
3670 *uriWithoutQuery = NULL;
3672 size_t uriWithoutQueryLen = 0;
3673 size_t queryLen = 0;
3674 size_t uriLen = strlen(uri);
3676 char *pointerToDelimiter = strstr(uri, "?");
3678 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : pointerToDelimiter - uri;
3679 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
3681 if (uriWithoutQueryLen)
3683 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
3684 if (!*uriWithoutQuery)
3688 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
3692 *query = (char *) OICCalloc(queryLen + 1, 1);
3695 OICFree(*uriWithoutQuery);
3696 *uriWithoutQuery = NULL;
3699 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
3705 return OC_STACK_NO_MEMORY;
3708 const uint8_t* OCGetServerInstanceID(void)
3710 static bool generated = false;
3711 static ServerID sid;
3717 if (OCGenerateUuid(sid) != RAND_UUID_OK)
3719 OC_LOG(FATAL, TAG, PCF("Generate UUID for Server Instance failed!"));
3726 const char* OCGetServerInstanceIDString(void)
3728 static bool generated = false;
3729 static char sidStr[UUID_STRING_SIZE];
3736 const uint8_t* sid = OCGetServerInstanceID();
3738 if(OCConvertUuidToString(sid, sidStr) != RAND_UUID_OK)
3740 OC_LOG(FATAL, TAG, PCF("Generate UUID String for Server Instance failed!"));
3748 CAResult_t OCSelectNetwork()
3750 CAResult_t retResult = CA_STATUS_FAILED;
3751 CAResult_t caResult = CA_STATUS_OK;
3753 CATransportAdapter_t connTypes[] = {
3755 CA_ADAPTER_RFCOMM_BTEDR,
3756 CA_ADAPTER_GATT_BTLE};
3757 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
3759 for(int i = 0; i<numConnTypes; i++)
3761 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
3762 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
3764 caResult = CASelectNetwork(connTypes[i]);
3765 if(caResult == CA_STATUS_OK)
3767 retResult = CA_STATUS_OK;
3772 if(retResult != CA_STATUS_OK)
3774 return caResult; // Returns error of appropriate transport that failed fatally.
3780 OCStackResult CAResultToOCResult(CAResult_t caResult)
3786 case CA_STATUS_INVALID_PARAM:
3787 return OC_STACK_INVALID_PARAM;
3788 case CA_ADAPTER_NOT_ENABLED:
3789 return OC_STACK_ADAPTER_NOT_ENABLED;
3790 case CA_SERVER_STARTED_ALREADY:
3792 case CA_SERVER_NOT_STARTED:
3793 return OC_STACK_ERROR;
3794 case CA_DESTINATION_NOT_REACHABLE:
3795 return OC_STACK_COMM_ERROR;
3796 case CA_SOCKET_OPERATION_FAILED:
3797 return OC_STACK_COMM_ERROR;
3798 case CA_SEND_FAILED:
3799 return OC_STACK_COMM_ERROR;
3800 case CA_RECEIVE_FAILED:
3801 return OC_STACK_COMM_ERROR;
3802 case CA_MEMORY_ALLOC_FAILED:
3803 return OC_STACK_NO_MEMORY;
3804 case CA_REQUEST_TIMEOUT:
3805 return OC_STACK_TIMEOUT;
3806 case CA_DESTINATION_DISCONNECTED:
3807 return OC_STACK_COMM_ERROR;
3808 case CA_STATUS_FAILED:
3809 return OC_STACK_ERROR;
3810 case CA_NOT_SUPPORTED:
3811 return OC_STACK_NOTIMPL;
3813 return OC_STACK_ERROR;