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;
102 //TODO: revisit this design
103 static bool gRASetInfo = false;
105 OCDeviceEntityHandler defaultDeviceHandler;
106 void* defaultDeviceHandlerCallbackParameter = NULL;
108 //-----------------------------------------------------------------------------
110 //-----------------------------------------------------------------------------
111 #define TAG PCF("OCStack")
112 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
113 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
114 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
115 TAG, PCF(#arg " is NULL")); return (retVal); } }
116 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OC_LOG((logLevel), \
117 TAG, PCF(#arg " is NULL")); return; } }
118 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
121 //TODO: we should allow the server to define this
122 #define MAX_OBSERVE_AGE (0x2FFFFUL)
124 #define MILLISECONDS_PER_SECOND (1000)
126 //-----------------------------------------------------------------------------
127 // Private internal function prototypes
128 //-----------------------------------------------------------------------------
131 * Generate handle of OCDoResource invocation for callback management.
133 * @return Generated OCDoResource handle.
135 static OCDoHandle GenerateInvocationHandle();
138 * Initialize resource data structures, variables, etc.
140 * @return ::OC_STACK_OK on success, some other value upon failure.
142 static OCStackResult initResources();
145 * Add a resource to the end of the linked list of resources.
147 * @param resource Resource to be added
149 static void insertResource(OCResource *resource);
152 * Find a resource in the linked list of resources.
154 * @param resource Resource to be found.
155 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
158 static OCResource *findResource(OCResource *resource);
161 * Insert a resource type into a resource's resource type linked list.
162 * If resource type already exists, it will not be inserted and the
163 * resourceType will be free'd.
164 * resourceType->next should be null to avoid memory leaks.
165 * Function returns silently for null args.
167 * @param resource Resource where resource type is to be inserted.
168 * @param resourceType Resource type to be inserted.
170 static void insertResourceType(OCResource *resource,
171 OCResourceType *resourceType);
174 * Get a resource type at the specified index within a resource.
176 * @param handle Handle of resource.
177 * @param index Index of resource type.
179 * @return Pointer to resource type if found, NULL otherwise.
181 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
185 * Insert a resource interface into a resource's resource interface linked list.
186 * If resource interface already exists, it will not be inserted and the
187 * resourceInterface will be free'd.
188 * resourceInterface->next should be null to avoid memory leaks.
190 * @param resource Resource where resource interface is to be inserted.
191 * @param resourceInterface Resource interface to be inserted.
193 static void insertResourceInterface(OCResource *resource,
194 OCResourceInterface *resourceInterface);
197 * Get a resource interface at the specified index within a resource.
199 * @param handle Handle of resource.
200 * @param index Index of resource interface.
202 * @return Pointer to resource interface if found, NULL otherwise.
204 static OCResourceInterface *findResourceInterfaceAtIndex(
205 OCResourceHandle handle, uint8_t index);
208 * Delete all of the dynamically allocated elements that were created for the resource type.
210 * @param resourceType Specified resource type.
212 static void deleteResourceType(OCResourceType *resourceType);
215 * Delete all of the dynamically allocated elements that were created for the resource interface.
217 * @param resourceInterface Specified resource interface.
219 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
222 * Delete all of the dynamically allocated elements that were created for the resource.
224 * @param resource Specified resource.
226 static void deleteResourceElements(OCResource *resource);
229 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
232 * @param handle Handle of resource to be deleted.
234 * @return ::OC_STACK_OK on success, some other value upon failure.
236 static OCStackResult deleteResource(OCResource *resource);
239 * Delete all of the resources in the resource list.
241 static void deleteAllResources();
244 * Increment resource sequence number. Handles rollover.
246 * @param resPtr Pointer to resource.
248 static void incrementSequenceNumber(OCResource * resPtr);
251 * Verify the lengths of the URI and the query separately.
253 * @param inputUri Input URI and query.
254 * @param uriLen The length of the initial URI with query.
255 * @return ::OC_STACK_OK on success, some other value upon failure.
257 static OCStackResult verifyUriQueryLength(const char * inputUri,
261 * Attempts to initialize every network interface that the CA Layer might have compiled in.
263 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
264 * return something other than @ref CA_STATUS_OK, then this function fails.
266 * @return ::CA_STATUS_OK on success, some other value upon failure.
268 static CAResult_t OCSelectNetwork();
271 * Get the CoAP ticks after the specified number of milli-seconds.
273 * @param afterMilliSeconds Milli-seconds.
277 static uint32_t GetTicks(uint32_t afterMilliSeconds);
280 * Convert CAResponseResult_t to OCStackResult.
282 * @param caCode CAResponseResult_t code.
283 * @return ::OC_STACK_OK on success, some other value upon failure.
285 static OCStackResult CAToOCStackResult(CAResponseResult_t caCode);
288 * Convert OCStackResult to CAResponseResult_t.
290 * @param caCode OCStackResult code.
291 * @return ::CA_SUCCESS on success, some other value upon failure.
293 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode);
296 * Convert OCTransportFlags_t to CATransportModifiers_t.
298 * @param ocConType OCTransportFlags_t input.
299 * @return CATransportFlags
301 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
304 * Convert CATransportFlags_t to OCTransportModifiers_t.
306 * @param caConType CATransportFlags_t input.
307 * @return OCTransportFlags
309 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
312 * Handle response from presence request.
314 * @param endPoint CA remote endpoint.
315 * @param responseInfo CA response info.
316 * @return ::OC_STACK_OK on success, some other value upon failure.
318 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
319 const CAResponseInfo_t *responseInfo);
322 * This function will be called back by CA layer when a response is received.
324 * @param endPoint CA remote endpoint.
325 * @param responseInfo CA response info.
327 static void HandleCAResponses(const CAEndpoint_t* endPoint,
328 const CAResponseInfo_t* responseInfo);
331 * This function will be called back by CA layer when a request is received.
333 * @param endPoint CA remote endpoint.
334 * @param requestInfo CA request info.
336 static void HandleCARequests(const CAEndpoint_t* endPoint,
337 const CARequestInfo_t* requestInfo);
340 * Extract query from a URI.
342 * @param uri Full URI with query.
343 * @param query Pointer to string that will contain query.
344 * @param newURI Pointer to string that will contain URI.
345 * @return ::OC_STACK_OK on success, some other value upon failure.
347 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
350 * Finds a resource type in an OCResourceType link-list.
352 * @param resourceTypeList The link-list to be searched through.
353 * @param resourceTypeName The key to search for.
355 * @return Resource type that matches the key (ie. resourceTypeName) or
356 * NULL if there is either an invalid parameter or this function was unable to find the key.
358 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
359 const char * resourceTypeName);
362 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
363 * TTL will be set to maxAge.
365 * @param cbNode Callback Node for which presence ttl is to be reset.
366 * @param maxAge New value of ttl in seconds.
368 * @return ::OC_STACK_OK on success, some other value upon failure.
370 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
372 //-----------------------------------------------------------------------------
373 // Internal functions
374 //-----------------------------------------------------------------------------
376 uint32_t GetTicks(uint32_t afterMilliSeconds)
381 // Guard against overflow of uint32_t
382 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
383 COAP_TICKS_PER_SECOND)
385 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
393 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
395 VERIFY_NON_NULL_NR(in, FATAL);
396 VERIFY_NON_NULL_NR(out, FATAL);
398 out->adapter = (OCTransportAdapter)in->adapter;
399 out->flags = CAToOCTransportFlags(in->flags);
400 strncpy(out->addr, in->addr, MAX_ADDR_STR_SIZE);
401 out->addr[MAX_ADDR_STR_SIZE - 1] = '\0';
402 out->port = in->port;
405 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
407 VERIFY_NON_NULL_NR(in, FATAL);
408 VERIFY_NON_NULL_NR(out, FATAL);
410 out->adapter = (CATransportAdapter_t)in->adapter;
411 out->flags = OCToCATransportFlags(in->flags);
412 strncpy(out->addr, in->addr, MAX_ADDR_STR_SIZE);
413 out->port = in->port;
416 static OCStackResult OCCreateEndpoint(OCDevAddr *devAddr, CAEndpoint_t **endpoint)
418 VERIFY_NON_NULL(devAddr, FATAL, OC_STACK_INVALID_PARAM);
419 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
421 CAEndpoint_t *ep = (CAEndpoint_t *)OICMalloc(sizeof (CAEndpoint_t));
424 return OC_STACK_NO_MEMORY;
427 ep->adapter = (CATransportAdapter_t)devAddr->adapter;
430 ep->adapter = CA_ADAPTER_IP;
432 ep->flags = OCToCATransportFlags(devAddr->flags);
433 strncpy(ep->addr, devAddr->addr, MAX_ADDR_STR_SIZE_CA);
434 ep->port = devAddr->port;
441 static void OCDestroyEndpoint(CAEndpoint_t *endpoint)
446 void FixUpClientResponse(OCClientResponse *cr)
448 VERIFY_NON_NULL_NR(cr, FATAL);
450 cr->addr = &cr->devAddr;
451 cr->connType = (OCConnectivityType)
452 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
455 //-----------------------------------------------------------------------------
456 // Internal API function
457 //-----------------------------------------------------------------------------
459 // This internal function is called to update the stack with the status of
460 // observers and communication failures
461 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
463 OCStackResult result = OC_STACK_ERROR;
464 ResourceObserver * observer = NULL;
465 OCEntityHandlerRequest ehRequest = {};
469 case OC_OBSERVER_NOT_INTERESTED:
470 OC_LOG(DEBUG, TAG, PCF("observer not interested in our notifications"));
471 observer = GetObserverUsingToken (token, tokenLength);
474 result = FormOCEntityHandlerRequest(&ehRequest,
475 (OCRequestHandle)NULL,
478 (OCResourceHandle)NULL,
479 NULL, NULL, 0, 0, NULL,
480 OC_OBSERVE_DEREGISTER,
481 observer->observeId);
482 if(result != OC_STACK_OK)
486 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
487 observer->resource->entityHandlerCallbackParam);
490 result = DeleteObserverUsingToken (token, tokenLength);
491 if(result == OC_STACK_OK)
493 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
497 result = OC_STACK_OK;
498 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
502 case OC_OBSERVER_STILL_INTERESTED:
503 OC_LOG(DEBUG, TAG, PCF("observer still interested, reset the failedCount"));
504 observer = GetObserverUsingToken (token, tokenLength);
507 observer->forceHighQos = 0;
508 observer->failedCommCount = 0;
509 result = OC_STACK_OK;
513 result = OC_STACK_OBSERVER_NOT_FOUND;
517 case OC_OBSERVER_FAILED_COMM:
518 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
519 observer = GetObserverUsingToken (token, tokenLength);
522 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
524 result = FormOCEntityHandlerRequest(&ehRequest,
525 (OCRequestHandle)NULL,
528 (OCResourceHandle)NULL,
529 NULL, NULL, 0, 0, NULL,
530 OC_OBSERVE_DEREGISTER,
531 observer->observeId);
532 if(result != OC_STACK_OK)
534 return OC_STACK_ERROR;
536 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
537 observer->resource->entityHandlerCallbackParam);
539 result = DeleteObserverUsingToken (token, tokenLength);
540 if(result == OC_STACK_OK)
542 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
546 result = OC_STACK_OK;
547 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
552 observer->failedCommCount++;
553 result = OC_STACK_CONTINUE;
555 observer->forceHighQos = 1;
556 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
560 OC_LOG(ERROR, TAG, PCF("Unknown status"));
561 result = OC_STACK_ERROR;
566 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
568 OCStackResult ret = OC_STACK_ERROR;
576 ret = OC_STACK_RESOURCE_CREATED;
579 ret = OC_STACK_RESOURCE_DELETED;
582 ret = OC_STACK_INVALID_QUERY;
584 case CA_UNAUTHORIZED_REQ:
585 ret = OC_STACK_UNAUTHORIZED_REQ;
588 ret = OC_STACK_INVALID_OPTION;
591 ret = OC_STACK_NO_RESOURCE;
593 case CA_RETRANSMIT_TIMEOUT:
594 ret = OC_STACK_COMM_ERROR;
602 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode)
604 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
611 case OC_STACK_RESOURCE_CREATED:
614 case OC_STACK_RESOURCE_DELETED:
617 case OC_STACK_INVALID_QUERY:
620 case OC_STACK_INVALID_OPTION:
623 case OC_STACK_NO_RESOURCE:
626 case OC_STACK_COMM_ERROR:
627 ret = CA_RETRANSMIT_TIMEOUT;
629 case OC_STACK_UNAUTHORIZED_REQ:
630 ret = CA_UNAUTHORIZED_REQ;
638 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
640 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
642 // supply default behavior.
643 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
645 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
647 if ((caFlags & OC_MASK_SCOPE) == 0)
649 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
654 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
656 return (OCTransportFlags)caFlags;
659 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
661 uint32_t lowerBound = 0;
662 uint32_t higherBound = 0;
664 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
666 return OC_STACK_INVALID_PARAM;
669 OC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
671 cbNode->presence->TTL = maxAgeSeconds;
673 for(int index = 0; index < PresenceTimeOutSize; index++)
675 // Guard against overflow
676 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
679 lowerBound = GetTicks((PresenceTimeOut[index] *
680 cbNode->presence->TTL *
681 MILLISECONDS_PER_SECOND)/100);
685 lowerBound = GetTicks(UINT32_MAX);
688 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
691 higherBound = GetTicks((PresenceTimeOut[index + 1] *
692 cbNode->presence->TTL *
693 MILLISECONDS_PER_SECOND)/100);
697 higherBound = GetTicks(UINT32_MAX);
700 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
702 OC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
703 OC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
704 OC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
707 cbNode->presence->TTLlevel = 0;
709 OC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
713 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
715 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
717 return OC_RSRVD_TRIGGER_CREATE;
719 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
721 return OC_RSRVD_TRIGGER_CHANGE;
725 return OC_RSRVD_TRIGGER_DELETE;
729 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
731 if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
733 return OC_PRESENCE_TRIGGER_CREATE;
735 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
737 return OC_PRESENCE_TRIGGER_CHANGE;
741 return OC_PRESENCE_TRIGGER_DELETE;
746 * The cononical presence allows constructed URIs to be string compared.
748 * requestUri must be a char array of size CA_MAX_URI_LENGTH
750 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
753 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
754 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
755 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
758 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
760 if (ep->adapter == CA_ADAPTER_IP)
762 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
764 if ('\0' == ep->addr[0]) // multicast
766 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
770 format = "coap://[%s]:%u%s";
775 if ('\0' == ep->addr[0]) // multicast
777 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
778 ep->port = OC_MULTICAST_PORT;
780 format = "coap://%s:%u%s";
782 return snprintf(presenceUri, CA_MAX_URI_LENGTH, format, ep->addr,
783 ep->port, OC_RSRVD_PRESENCE_URI);
786 // might work for other adapters (untested, but better than nothing)
787 format = "coap://%s%s";
788 return snprintf(presenceUri, CA_MAX_URI_LENGTH, format, ep->addr,
789 OC_RSRVD_PRESENCE_URI);
793 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
794 const CAResponseInfo_t *responseInfo)
796 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
797 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
799 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
800 ClientCB * cbNode = NULL;
801 char *resourceTypeName = NULL;
802 OCClientResponse response;
803 OCStackResult result = OC_STACK_ERROR;
806 char presenceUri[CA_MAX_URI_LENGTH];
808 int presenceSubscribe = 0;
809 int multicastPresenceSubscribe = 0;
811 if (responseInfo->result != CA_SUCCESS)
813 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
814 return OC_STACK_ERROR;
817 // check for unicast presence
818 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
819 if (uriLen < 0 || uriLen >= sizeof (presenceUri))
821 return OC_STACK_INVALID_URI;
824 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
827 presenceSubscribe = 1;
831 // check for multiicast presence
832 CAEndpoint_t ep = { endpoint->adapter, endpoint->flags };
833 OICStrcpy(ep.addr, sizeof(ep.addr), OC_MULTICAST_IP);
834 ep.port = OC_MULTICAST_PORT;
836 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
838 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
841 multicastPresenceSubscribe = 1;
845 if (!presenceSubscribe && !multicastPresenceSubscribe)
847 OC_LOG(ERROR, TAG, PCF("Received a presence notification, but no callback, ignoring"));
851 response.payload = NULL;
852 response.result = OC_STACK_OK;
854 CopyEndpointToDevAddr(endpoint, &response.devAddr);
855 FixUpClientResponse(&response);
857 if (responseInfo->info.payload)
859 result = OCParsePayload(&response.payload, responseInfo->info.payload,
860 responseInfo->info.payloadSize);
862 if(result != OC_STACK_OK || response.payload->type != PAYLOAD_TYPE_PRESENCE)
864 OC_LOG(ERROR, TAG, PCF("Presence parse failed"));
867 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
868 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
869 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
872 if (presenceSubscribe)
874 if(cbNode->sequenceNumber == response.sequenceNumber)
876 OC_LOG(INFO, TAG, PCF("No presence change"));
882 OC_LOG(INFO, TAG, PCF("Stopping presence"));
883 response.result = OC_STACK_PRESENCE_STOPPED;
886 OICFree(cbNode->presence->timeOut);
887 OICFree(cbNode->presence);
888 cbNode->presence = NULL;
893 if(!cbNode->presence)
895 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
897 if(!(cbNode->presence))
899 OC_LOG(ERROR, TAG, PCF("Could not allocate memory for cbNode->presence"));
900 result = OC_STACK_NO_MEMORY;
904 VERIFY_NON_NULL_V(cbNode->presence);
905 cbNode->presence->timeOut = NULL;
906 cbNode->presence->timeOut = (uint32_t *)
907 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
908 if(!(cbNode->presence->timeOut)){
910 PCF("Could not allocate memory for cbNode->presence->timeOut"));
911 OICFree(cbNode->presence);
912 result = OC_STACK_NO_MEMORY;
917 ResetPresenceTTL(cbNode, maxAge);
919 cbNode->sequenceNumber = response.sequenceNumber;
921 // Ensure that a filter is actually applied.
922 if( resourceTypeName && cbNode->filterResourceType)
924 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
933 // This is the multicast case
934 OCMulticastNode* mcNode = NULL;
935 mcNode = GetMCPresenceNode(presenceUri);
939 if(mcNode->nonce == response.sequenceNumber)
941 OC_LOG(INFO, TAG, PCF("No presence change (Multicast)"));
944 mcNode->nonce = response.sequenceNumber;
948 OC_LOG(INFO, TAG, PCF("Stopping presence"));
949 response.result = OC_STACK_PRESENCE_STOPPED;
954 char* uri = OICStrdup(presenceUri);
958 PCF("No Memory for URI to store in the presence node"));
959 result = OC_STACK_NO_MEMORY;
963 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
964 if(result == OC_STACK_NO_MEMORY)
967 PCF("No Memory for Multicast Presence Node"));
971 // presence node now owns uri
974 // Ensure that a filter is actually applied.
975 if(resourceTypeName && cbNode->filterResourceType)
977 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
984 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
986 if (cbResult == OC_STACK_DELETE_TRANSACTION)
988 FindAndDeleteClientCB(cbNode);
992 OICFree(resourceTypeName);
996 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
998 VERIFY_NON_NULL_NR(endPoint, FATAL);
999 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1000 VERIFY_NON_NULL_NR(responseInfo->info.resourceUri, FATAL);
1001 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
1003 if(strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1005 HandlePresenceResponse(endPoint, responseInfo);
1009 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1010 responseInfo->info.tokenLength, NULL, NULL);
1012 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1013 responseInfo->info.tokenLength);
1017 OC_LOG(INFO, TAG, PCF("There is a cbNode associated with the response token"));
1018 if(responseInfo->result == CA_EMPTY)
1020 OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
1021 // We do not have a case for the client to receive a RESET
1022 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1024 //This is the case of receiving an ACK on a request to a slow resource!
1025 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
1026 //TODO: should we inform the client
1027 // app that at least the request was received at the server?
1030 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1032 OC_LOG(INFO, TAG, PCF("Receiving A Timeout for this token"));
1033 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1035 OCClientResponse response = {};
1036 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1037 FixUpClientResponse(&response);
1038 response.resourceUri = responseInfo->info.resourceUri;
1040 response.result = CAToOCStackResult(responseInfo->result);
1041 cbNode->callBack(cbNode->context,
1042 cbNode->handle, &response);
1043 FindAndDeleteClientCB(cbNode);
1047 OC_LOG(INFO, TAG, PCF("This is a regular response, A client call back is found"));
1048 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1050 OCClientResponse response = {};
1051 response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1052 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1053 FixUpClientResponse(&response);
1054 response.resourceUri = responseInfo->info.resourceUri;
1056 response.result = CAToOCStackResult(responseInfo->result);
1057 if(responseInfo->info.payload &&
1058 responseInfo->info.payloadSize &&
1059 OC_STACK_OK != OCParsePayload(&response.payload, responseInfo->info.payload,
1060 responseInfo->info.payloadSize))
1062 OC_LOG(ERROR, TAG, PCF("Error converting payload"));
1066 response.numRcvdVendorSpecificHeaderOptions = 0;
1067 if(responseInfo->info.numOptions > 0)
1070 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1071 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1073 memcpy (&(response.sequenceNumber),
1074 &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
1075 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1080 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1083 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1085 OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
1089 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1091 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1092 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1096 if (cbNode->method == OC_REST_OBSERVE &&
1097 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1098 response.sequenceNumber <= cbNode->sequenceNumber)
1100 OC_LOG_V(INFO, TAG, PCF("Received stale notification. Number :%d"),
1101 response.sequenceNumber);
1105 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1108 cbNode->sequenceNumber = response.sequenceNumber;
1110 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1112 FindAndDeleteClientCB(cbNode);
1116 // To keep discovery callbacks active.
1117 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1118 MILLISECONDS_PER_SECOND);
1120 OCPayloadDestroy(response.payload);
1123 //Need to send ACK when the response is CON
1124 if(responseInfo->info.type == CA_MSG_CONFIRM)
1126 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1127 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0);
1135 OC_LOG(INFO, TAG, PCF("There is an observer associated with the response token"));
1136 if(responseInfo->result == CA_EMPTY)
1138 OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
1139 if(responseInfo->info.type == CA_MSG_RESET)
1141 OC_LOG(INFO, TAG, PCF("This is a RESET"));
1142 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1143 OC_OBSERVER_NOT_INTERESTED);
1145 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1147 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
1148 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1149 OC_OBSERVER_STILL_INTERESTED);
1152 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1154 OC_LOG(INFO, TAG, PCF("Receiving Time Out for an observer"));
1155 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1156 OC_OBSERVER_FAILED_COMM);
1161 if(!cbNode && !observer)
1163 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER)
1165 OC_LOG(INFO, TAG, PCF("This is a client, but no cbNode was found for token"));
1166 if(responseInfo->result == CA_EMPTY)
1168 OC_LOG(INFO, TAG, PCF("Receiving CA_EMPTY in the ocstack"));
1172 OC_LOG(INFO, TAG, PCF("Received a response or notification,\
1173 but I do not have callback. Sending RESET"));
1174 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1175 CA_MSG_RESET, 0, NULL, NULL, 0);
1179 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
1181 OC_LOG(INFO, TAG, PCF("This is a server, but no observer was found for token"));
1182 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1184 OC_LOG_V(INFO, TAG, PCF("Received ACK at server for messageId : %d"),
1185 responseInfo->info.messageId);
1187 if (responseInfo->info.type == CA_MSG_RESET)
1189 OC_LOG_V(INFO, TAG, PCF("Received RESET at server for messageId : %d"),
1190 responseInfo->info.messageId);
1196 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
1200 * This function handles error response from CA
1201 * code shall be added to handle the errors
1203 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1205 OC_LOG(INFO, TAG, PCF("Enter HandleCAErrorResponse"));
1207 if(NULL == endPoint)
1209 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1213 if(NULL == errrorInfo)
1215 OC_LOG(ERROR, TAG, PCF("errrorInfo is NULL"));
1218 OC_LOG(INFO, TAG, PCF("Exit HandleCAErrorResponse"));
1222 * This function sends out Direct Stack Responses. These are responses that are not coming
1223 * from the application entity handler. These responses have no payload and are usually ACKs,
1224 * RESETs or some error conditions that were caught by the stack.
1226 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1227 const CAResponseResult_t responseResult, const CAMessageType_t type,
1228 const uint8_t numOptions, const CAHeaderOption_t *options,
1229 CAToken_t token, uint8_t tokenLength)
1231 CAResponseInfo_t respInfo = {};
1232 respInfo.result = responseResult;
1233 respInfo.info.messageId = coapID;
1234 respInfo.info.numOptions = numOptions;
1235 respInfo.info.options = (CAHeaderOption_t*)options;
1236 respInfo.info.payload = NULL;
1237 respInfo.info.token = token;
1238 respInfo.info.tokenLength = tokenLength;
1239 respInfo.info.type = type;
1241 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1242 if(caResult != CA_STATUS_OK)
1244 OC_LOG(ERROR, TAG, PCF("CASendResponse error"));
1245 return OC_STACK_ERROR;
1250 //This function will be called back by CA layer when a request is received
1251 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1253 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
1256 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1262 OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
1266 OCStackResult requestResult = OC_STACK_ERROR;
1268 if(myStackMode == OC_CLIENT)
1270 //TODO: should the client be responding to requests?
1274 OCServerProtocolRequest serverRequest = {};
1276 OC_LOG_V(INFO, TAG, PCF("Endpoint URI : %s"), requestInfo->info.resourceUri);
1278 char * uriWithoutQuery = NULL;
1279 char * query = NULL;
1281 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1283 if (requestResult != OC_STACK_OK)
1285 OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1288 OC_LOG_V(INFO, TAG, PCF("URI without query: %s"), uriWithoutQuery);
1289 OC_LOG_V(INFO, TAG, PCF("Query : %s"), query);
1291 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1293 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1294 OICFree(uriWithoutQuery);
1298 OC_LOG(ERROR, TAG, PCF("URI length exceeds MAX_URI_LENGTH."));
1299 OICFree(uriWithoutQuery);
1306 if(strlen(query) < MAX_QUERY_LENGTH)
1308 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1313 OC_LOG(ERROR, TAG, PCF("Query length exceeds MAX_QUERY_LENGTH."));
1319 if (requestInfo->info.payload)
1321 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1322 memcpy (&(serverRequest.payload), requestInfo->info.payload,
1323 requestInfo->info.payloadSize);
1327 serverRequest.reqTotalSize = 0;
1330 switch (requestInfo->method)
1333 serverRequest.method = OC_REST_GET;
1336 serverRequest.method = OC_REST_PUT;
1339 serverRequest.method = OC_REST_POST;
1342 serverRequest.method = OC_REST_DELETE;
1345 OC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1346 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1347 requestInfo->info.type, requestInfo->info.numOptions,
1348 requestInfo->info.options, requestInfo->info.token,
1349 requestInfo->info.tokenLength);
1353 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1354 requestInfo->info.tokenLength);
1355 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1356 serverRequest.tokenLength = requestInfo->info.tokenLength;
1358 if (!serverRequest.requestToken)
1360 OC_LOG(FATAL, TAG, "Allocation for token failed.");
1361 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1362 requestInfo->info.type, requestInfo->info.numOptions,
1363 requestInfo->info.options, requestInfo->info.token,
1364 requestInfo->info.tokenLength);
1367 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1369 if (requestInfo->info.type == CA_MSG_CONFIRM)
1371 serverRequest.qos = OC_HIGH_QOS;
1375 serverRequest.qos = OC_LOW_QOS;
1377 // CA does not need the following field
1378 // Are we sure CA does not need them? how is it responding to multicast
1379 serverRequest.delayedResNeeded = 0;
1381 serverRequest.coapID = requestInfo->info.messageId;
1383 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1385 // copy vendor specific header options
1386 uint8_t tempNum = (requestInfo->info.numOptions);
1387 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1388 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1391 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
1392 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1393 requestInfo->info.type, requestInfo->info.numOptions,
1394 requestInfo->info.options, requestInfo->info.token,
1395 requestInfo->info.tokenLength);
1396 OICFree(serverRequest.requestToken);
1399 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1400 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1402 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1403 sizeof(CAHeaderOption_t)*tempNum);
1406 requestResult = HandleStackRequests (&serverRequest);
1408 // Send ACK to client as precursor to slow response
1409 if(requestResult == OC_STACK_SLOW_RESOURCE)
1411 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1412 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0);
1414 else if(requestResult != OC_STACK_OK)
1416 OC_LOG_V(ERROR, TAG, PCF("HandleStackRequests failed. error: %d"), requestResult);
1418 CAResponseResult_t stackResponse = OCToCAStackResult(requestResult);
1420 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1421 requestInfo->info.type, requestInfo->info.numOptions,
1422 requestInfo->info.options, requestInfo->info.token,
1423 requestInfo->info.tokenLength);
1425 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1426 // The token is copied in there, and is thus still owned by this function.
1427 OICFree(serverRequest.requestToken);
1428 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
1431 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1433 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
1434 OCStackResult result = OC_STACK_ERROR;
1435 ResourceHandling resHandling;
1436 OCResource *resource;
1437 if(!protocolRequest)
1439 OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
1440 return OC_STACK_INVALID_PARAM;
1443 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1444 protocolRequest->tokenLength);
1447 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
1448 result = AddServerRequest(&request, protocolRequest->coapID,
1449 protocolRequest->delayedResNeeded, 0,
1450 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
1451 protocolRequest->observationOption, protocolRequest->qos,
1452 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1453 protocolRequest->payload, protocolRequest->requestToken,
1454 protocolRequest->tokenLength,
1455 protocolRequest->resourceUrl, protocolRequest->reqTotalSize,
1456 &protocolRequest->devAddr);
1457 if (OC_STACK_OK != result)
1459 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
1465 OC_LOG(ERROR, TAG, PCF("Out of Memory"));
1466 return OC_STACK_NO_MEMORY;
1469 if(!protocolRequest->reqMorePacket)
1471 request->requestComplete = 1;
1476 OC_LOG(INFO, TAG, PCF("This is either a repeated or blocked Server Request"));
1479 if(request->requestComplete)
1481 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
1482 result = DetermineResourceHandling (request, &resHandling, &resource);
1483 if (result == OC_STACK_OK)
1485 result = ProcessRequest(resHandling, resource, request);
1490 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
1491 result = OC_STACK_CONTINUE;
1496 bool validatePlatformInfo(OCPlatformInfo info)
1499 if (!info.platformID)
1501 OC_LOG(ERROR, TAG, PCF("No platform ID found."));
1505 if (info.manufacturerName)
1507 size_t lenManufacturerName = strlen(info.manufacturerName);
1509 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1511 OC_LOG(ERROR, TAG, PCF("Manufacturer name fails length requirements."));
1517 OC_LOG(ERROR, TAG, PCF("No manufacturer name present"));
1521 if (info.manufacturerUrl)
1523 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1525 OC_LOG(ERROR, TAG, PCF("Manufacturer url fails length requirements."));
1532 //-----------------------------------------------------------------------------
1534 //-----------------------------------------------------------------------------
1536 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1539 !raInfo->username ||
1540 !raInfo->hostname ||
1541 !raInfo->xmpp_domain)
1544 return OC_STACK_INVALID_PARAM;
1546 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1547 gRASetInfo = (result == OC_STACK_OK)? true : false;
1553 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1560 OC_LOG(ERROR, TAG, PCF("Need to call OCSetRAInfo before calling OCInit"));
1561 return OC_STACK_ERROR;
1564 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1567 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1569 if(stackState == OC_STACK_INITIALIZED)
1571 OC_LOG(INFO, TAG, PCF("Subsequent calls to OCInit() without calling \
1572 OCStop() between them are ignored."));
1576 OCStackResult result = OC_STACK_ERROR;
1577 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1580 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)))
1582 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1583 return OC_STACK_ERROR;
1587 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER)
1589 caglobals.client = true;
1591 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER)
1593 caglobals.server = true;
1596 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1597 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
1599 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4);
1601 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
1602 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
1604 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4);
1607 defaultDeviceHandler = NULL;
1608 defaultDeviceHandlerCallbackParameter = NULL;
1611 result = CAResultToOCResult(CAInitialize());
1612 VERIFY_SUCCESS(result, OC_STACK_OK);
1614 result = CAResultToOCResult(OCSelectNetwork());
1615 VERIFY_SUCCESS(result, OC_STACK_OK);
1617 switch (myStackMode)
1620 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1621 result = CAResultToOCResult(CAStartDiscoveryServer());
1622 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1625 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1626 result = CAResultToOCResult(CAStartListeningServer());
1627 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1629 case OC_CLIENT_SERVER:
1630 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1631 result = CAResultToOCResult(CAStartListeningServer());
1632 if(result == OC_STACK_OK)
1634 result = CAResultToOCResult(CAStartDiscoveryServer());
1638 VERIFY_SUCCESS(result, OC_STACK_OK);
1640 #ifdef WITH_PRESENCE
1641 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1642 #endif // WITH_PRESENCE
1644 //Update Stack state to initialized
1645 stackState = OC_STACK_INITIALIZED;
1647 // Initialize resource
1648 if(myStackMode != OC_CLIENT)
1650 result = initResources();
1653 // Initialize the SRM Policy Engine
1654 if(result == OC_STACK_OK)
1656 result = SRMInitPolicyEngine();
1657 // TODO after BeachHead delivery: consolidate into single SRMInit()
1661 if(result != OC_STACK_OK)
1663 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1664 deleteAllResources();
1666 stackState = OC_STACK_UNINITIALIZED;
1671 OCStackResult OCStop()
1673 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1675 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1677 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1680 else if (stackState != OC_STACK_INITIALIZED)
1682 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1683 return OC_STACK_ERROR;
1686 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1688 #ifdef WITH_PRESENCE
1689 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1690 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1691 presenceResource.presenceTTL = 0;
1692 #endif // WITH_PRESENCE
1694 // Free memory dynamically allocated for resources
1695 deleteAllResources();
1697 DeletePlatformInfo();
1699 // Remove all observers
1700 DeleteObserverList();
1701 // Remove all the client callbacks
1702 DeleteClientCBList();
1704 // De-init the SRM Policy Engine
1705 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
1706 SRMDeInitPolicyEngine();
1709 stackState = OC_STACK_UNINITIALIZED;
1713 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1718 return CA_MSG_CONFIRM;
1723 return CA_MSG_NONCONFIRM;
1727 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1731 query = strchr (inputUri, '?');
1735 if((query - inputUri) > MAX_URI_LENGTH)
1737 return OC_STACK_INVALID_URI;
1740 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1742 return OC_STACK_INVALID_QUERY;
1745 else if(uriLen > MAX_URI_LENGTH)
1747 return OC_STACK_INVALID_URI;
1753 * A request uri consists of the following components in order:
1755 * optional prefix "coap://"
1757 * IPv6 address "[1234::5678]"
1758 * IPv4 address "192.168.1.1"
1759 * optional port ":5683"
1760 * resource uri "/oc/core..."
1762 * for PRESENCE requests, extract resource type.
1764 static OCStackResult ParseRequestUri(const char *fullUri,
1765 OCTransportAdapter adapter,
1766 OCTransportFlags flags,
1767 OCDevAddr **devAddr,
1769 char **resourceType)
1771 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
1773 OCStackResult result = OC_STACK_OK;
1774 OCDevAddr *da = NULL;
1778 // provide defaults for all returned values
1785 *resourceUri = NULL;
1789 *resourceType = NULL;
1792 // delimit url prefix, if any
1793 const char *start = fullUri;
1794 char *slash2 = strstr(start, "//");
1799 char *slash = strchr(start, '/');
1802 return OC_STACK_INVALID_URI;
1805 // processs url prefix, if any
1806 size_t urlLen = slash - start;
1810 if (urlLen && devAddr)
1811 { // construct OCDevAddr
1812 if (OC_ADAPTER_IP == adapter)
1814 if (start[0] == '[')
1816 char *close = strchr(++start, ']');
1817 if (!close || close > slash)
1819 return OC_STACK_INVALID_URI;
1822 if (close[1] == ':')
1830 colon = strchr(start, ':');
1831 end = (colon && colon < slash) ? colon : slash;
1834 if (len >= sizeof(da->addr))
1836 return OC_STACK_INVALID_URI;
1838 // use standard multicast port
1839 if (colon && colon < slash)
1841 for (colon++; colon < slash; colon++)
1844 if (c < '0' || c > '9')
1846 return OC_STACK_INVALID_URI;
1848 port = 10 * port + c - '0';
1855 * This is for Non-IP adapters(EDR and BLE).
1856 * The address will be between "//" and "/" in the request URI.
1857 * [Ex. coap://AB:BC:CD:DE:EF:FG/resource_uri]
1863 if (len >= sizeof(da->addr))
1865 return OC_STACK_INVALID_URI;
1868 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
1871 return OC_STACK_NO_MEMORY;
1873 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
1875 da->adapter = adapter;
1877 if (!strncmp(fullUri, "coaps:", 6))
1879 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
1884 // process resource uri, if any
1886 { // request uri and query
1887 size_t ulen = strlen(slash); // resource uri length
1888 size_t tlen = 0; // resource type length
1891 static const char strPresence[] = "/oic/ad?rt=";
1892 static const size_t lenPresence = sizeof(strPresence) - 1;
1893 if (!strncmp(slash, strPresence, lenPresence))
1895 type = slash + lenPresence;
1896 tlen = ulen - lenPresence;
1901 *resourceUri = (char *)OICMalloc(ulen + 1);
1904 result = OC_STACK_NO_MEMORY;
1907 strcpy(*resourceUri, slash);
1910 if (type && resourceType)
1912 *resourceType = (char *)OICMalloc(tlen + 1);
1915 result = OC_STACK_NO_MEMORY;
1919 OICStrcpy(*resourceType, (tlen+1), type);
1926 // free all returned values
1933 OICFree(*resourceUri);
1937 OICFree(*resourceType);
1942 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
1943 char *resourceUri, char **requestUri)
1945 char uri[CA_MAX_URI_LENGTH];
1947 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
1949 *requestUri = (char *)OICMalloc(strlen(uri) + 1);
1952 return OC_STACK_NO_MEMORY;
1955 strcpy(*requestUri, uri);
1960 * Discover or Perform requests on a specified resource
1962 OCStackResult OCDoResource(OCDoHandle *handle,
1964 const char *requestUri,
1965 const OCDevAddr *destination,
1967 OCConnectivityType connectivityType,
1968 OCQualityOfService qos,
1969 OCCallbackData *cbData,
1970 OCHeaderOption *options,
1973 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1975 // Validate input parameters
1976 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1977 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1978 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
1980 OCStackResult result = OC_STACK_ERROR;
1981 CAResult_t caResult;
1982 CAToken_t token = NULL;
1983 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
1984 ClientCB *clientCB = NULL;
1985 OCDoHandle resHandle = NULL;
1986 CAEndpoint_t *endpoint = NULL;
1987 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
1989 OCTransportAdapter adapter;
1990 OCTransportFlags flags;
1991 // the request contents are put here
1992 CARequestInfo_t requestInfo = { CA_GET };
1993 // requestUri will be parsed into the following three variables
1994 OCDevAddr *devAddr = NULL;
1995 char *resourceUri = NULL;
1996 char *resourceType = NULL;
1998 // To track if memory is allocated for additional header options
1999 uint8_t hdrOptionMemAlloc = 0;
2001 // This validation is broken, but doesn't cause harm
2002 size_t uriLen = strlen(requestUri );
2003 if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
2009 * Support original behavior with address on resourceUri argument.
2011 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2012 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2014 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2016 if (result != OC_STACK_OK)
2018 OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2025 case OC_REST_OBSERVE:
2026 case OC_REST_OBSERVE_ALL:
2027 case OC_REST_CANCEL_OBSERVE:
2028 requestInfo.method = CA_GET;
2031 requestInfo.method = CA_PUT;
2034 requestInfo.method = CA_POST;
2036 case OC_REST_DELETE:
2037 requestInfo.method = CA_DELETE;
2039 case OC_REST_DISCOVER:
2041 if (!destination && !devAddr)
2043 destination = &tmpDevAddr;
2045 // CA_DISCOVER will become GET and isMulticast
2046 requestInfo.method = CA_GET;
2047 requestInfo.isMulticast = true;
2049 #ifdef WITH_PRESENCE
2050 case OC_REST_PRESENCE:
2051 // Replacing method type with GET because "presence"
2052 // is a stack layer only implementation.
2053 requestInfo.method = CA_GET;
2057 result = OC_STACK_INVALID_METHOD;
2061 if (!devAddr && !destination)
2063 OC_LOG_V(DEBUG, TAG, "no devAddr and no destination");
2064 result = OC_STACK_INVALID_PARAM;
2068 /* If not original behavior, use destination argument */
2069 if (destination && !devAddr)
2071 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2074 result = OC_STACK_NO_MEMORY;
2077 *devAddr = *destination;
2080 resHandle = GenerateInvocationHandle();
2083 result = OC_STACK_NO_MEMORY;
2087 caResult = CAGenerateToken(&token, tokenLength);
2088 if (caResult != CA_STATUS_OK)
2090 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2094 // fill in request data
2095 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2096 requestInfo.info.token = token;
2097 requestInfo.info.tokenLength = tokenLength;
2098 requestInfo.info.resourceUri = resourceUri;
2100 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2102 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2103 options, numOptions, OC_OBSERVE_REGISTER);
2104 if (result != OC_STACK_OK)
2108 hdrOptionMemAlloc = 1;
2109 requestInfo.info.numOptions = numOptions + 1;
2113 requestInfo.info.options = (CAHeaderOption_t*)options;
2114 requestInfo.info.numOptions = numOptions;
2117 // create remote endpoint
2118 result = OCCreateEndpoint(devAddr, &endpoint);
2122 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2125 OC_LOG(ERROR, TAG, PCF("Failed to create CBOR Payload"));
2131 requestInfo.info.payload = NULL;
2132 requestInfo.info.payloadSize = 0;
2137 if (result != OC_STACK_OK)
2139 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2143 // prepare for response
2144 #ifdef WITH_PRESENCE
2145 if (method == OC_REST_PRESENCE)
2147 char *presenceUri = NULL;
2148 result = OCPreparePresence(endpoint, resourceUri, &presenceUri);
2149 if (OC_STACK_OK != result)
2154 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2155 // Presence notification will form a canonical uri to
2156 // look for callbacks into the application.
2157 resourceUri = presenceUri;
2161 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2162 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2163 method, devAddr, resourceUri, resourceType, ttl);
2164 if (OC_STACK_OK != result)
2169 devAddr = NULL; // Client CB list entry now owns it
2170 resourceUri = NULL; // Client CB list entry now owns it
2171 resourceType = NULL; // Client CB list entry now owns it
2174 caResult = CASendRequest(endpoint, &requestInfo);
2175 if (caResult != CA_STATUS_OK)
2177 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
2178 result = OC_STACK_COMM_ERROR;
2184 *handle = resHandle;
2188 if (result != OC_STACK_OK)
2190 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
2191 FindAndDeleteClientCB(clientCB);
2192 CADestroyToken(token);
2200 // This is the owner of the payload object, so we free it
2201 OCPayloadDestroy(payload);
2202 OICFree(requestInfo.info.payload);
2204 OICFree(resourceUri);
2205 OICFree(resourceType);
2207 if (hdrOptionMemAlloc)
2209 OICFree(requestInfo.info.options);
2214 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2218 * This ftn is implemented one of two ways in the case of observation:
2220 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2221 * Remove the callback associated on client side.
2222 * When the next notification comes in from server,
2223 * reply with RESET message to server.
2224 * Keep in mind that the server will react to RESET only
2225 * if the last notification was sent as CON
2227 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2228 * and it is associated with an observe request
2229 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2230 * Send CON Observe request to server with
2231 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2232 * Remove the callback associated on client side.
2234 OCStackResult ret = OC_STACK_OK;
2235 CAEndpoint_t* endpoint = NULL;
2236 CAResult_t caResult;
2237 CAInfo_t requestData = {};
2238 CARequestInfo_t requestInfo = {};
2242 return OC_STACK_INVALID_PARAM;
2245 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2248 OC_LOG(ERROR, TAG, PCF("Client callback not found. Called OCCancel twice?"));
2252 switch (clientCB->method)
2254 case OC_REST_OBSERVE:
2255 case OC_REST_OBSERVE_ALL:
2256 OC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
2257 clientCB->requestUri);
2258 if (qos != OC_HIGH_QOS)
2260 FindAndDeleteClientCB(clientCB);
2265 OC_LOG(INFO, TAG, PCF("Cancelling observation as CONFIRMABLE"));
2268 requestData.type = qualityOfServiceToMessageType(qos);
2269 requestData.token = clientCB->token;
2270 requestData.tokenLength = clientCB->tokenLength;
2271 if (CreateObserveHeaderOption (&(requestData.options),
2272 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2274 return OC_STACK_ERROR;
2276 requestData.numOptions = numOptions + 1;
2277 requestData.resourceUri = OICStrdup (clientCB->requestUri);
2279 requestInfo.method = CA_GET;
2280 requestInfo.info = requestData;
2282 ret = OCCreateEndpoint(clientCB->devAddr, &endpoint);
2283 if (ret != OC_STACK_OK)
2285 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2290 caResult = CASendRequest(endpoint, &requestInfo);
2291 if (caResult != CA_STATUS_OK)
2293 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2294 ret = OC_STACK_ERROR;
2296 ret = CAResultToOCResult (caResult);
2299 #ifdef WITH_PRESENCE
2300 case OC_REST_PRESENCE:
2301 FindAndDeleteClientCB(clientCB);
2306 ret = OC_STACK_INVALID_METHOD;
2311 OCDestroyEndpoint(endpoint);
2312 if (requestData.numOptions > 0)
2314 OICFree(requestData.options);
2316 if (requestData.resourceUri)
2318 OICFree (requestData.resourceUri);
2325 * @brief Register Persistent storage callback.
2326 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2328 * OC_STACK_OK - No errors; Success
2329 * OC_STACK_INVALID_PARAM - Invalid parameter
2331 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2333 OC_LOG(INFO, TAG, PCF("RegisterPersistentStorageHandler !!"));
2334 if(!persistentStorageHandler)
2336 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2337 return OC_STACK_INVALID_PARAM;
2341 if( !persistentStorageHandler->open ||
2342 !persistentStorageHandler->close ||
2343 !persistentStorageHandler->read ||
2344 !persistentStorageHandler->unlink ||
2345 !persistentStorageHandler->write)
2347 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2348 return OC_STACK_INVALID_PARAM;
2351 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2354 #ifdef WITH_PRESENCE
2356 OCStackResult OCProcessPresence()
2358 OCStackResult result = OC_STACK_OK;
2360 // the following line floods the log with messages that are irrelevant
2361 // to most purposes. Uncomment as needed.
2362 //OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
2363 ClientCB* cbNode = NULL;
2364 OCClientResponse clientResponse;
2365 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2367 LL_FOREACH(cbList, cbNode)
2369 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2374 uint32_t now = GetTicks(0);
2375 OC_LOG_V(DEBUG, TAG, "this TTL level %d",
2376 cbNode->presence->TTLlevel);
2377 OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2379 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
2384 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2386 OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2387 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2390 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2392 OC_LOG(DEBUG, TAG, PCF("No more timeout ticks"));
2394 clientResponse.sequenceNumber = 0;
2395 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2396 clientResponse.devAddr = *cbNode->devAddr;
2397 FixUpClientResponse(&clientResponse);
2398 clientResponse.payload = NULL;
2400 // Increment the TTLLevel (going to a next state), so we don't keep
2401 // sending presence notification to client.
2402 cbNode->presence->TTLlevel++;
2403 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2404 cbNode->presence->TTLlevel);
2406 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2407 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2409 FindAndDeleteClientCB(cbNode);
2413 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2418 CAResult_t caResult = CA_STATUS_OK;
2419 CAEndpoint_t* endpoint = NULL;
2420 CAInfo_t requestData ={};
2421 CARequestInfo_t requestInfo = {};
2423 OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
2425 result = OCCreateEndpoint(cbNode->devAddr, &endpoint);
2426 if (result != OC_STACK_OK)
2428 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2432 requestData.type = CA_MSG_NONCONFIRM;
2433 requestData.token = cbNode->token;
2434 requestData.tokenLength = cbNode->tokenLength;
2435 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2436 requestInfo.method = CA_GET;
2437 requestInfo.info = requestData;
2439 caResult = CASendRequest(endpoint, &requestInfo);
2440 OCDestroyEndpoint(endpoint);
2442 if (caResult != CA_STATUS_OK)
2444 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2448 cbNode->presence->TTLlevel++;
2449 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2452 if (result != OC_STACK_OK)
2454 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2458 #endif // WITH_PRESENCE
2460 OCStackResult OCProcess()
2462 #ifdef WITH_PRESENCE
2463 OCProcessPresence();
2465 CAHandleRequestResponse();
2470 #ifdef WITH_PRESENCE
2471 OCStackResult OCStartPresence(const uint32_t ttl)
2473 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2474 OCChangeResourceProperty(
2475 &(((OCResource *)presenceResource.handle)->resourceProperties),
2478 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2480 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2481 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to max value"));
2485 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2486 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to default value"));
2490 presenceResource.presenceTTL = ttl;
2492 OC_LOG_V(DEBUG, TAG, "Presence TTL is %lu seconds", presenceResource.presenceTTL);
2494 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2496 presenceState = OC_PRESENCE_INITIALIZED;
2498 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2499 OICStrcpy(devAddr.addr, sizeof(devAddr.addr), OC_MULTICAST_IP);
2500 devAddr.port = OC_MULTICAST_PORT;
2502 CAToken_t caToken = NULL;
2503 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2504 if (caResult != CA_STATUS_OK)
2506 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2507 CADestroyToken(caToken);
2508 return OC_STACK_ERROR;
2511 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2512 (OCResource *)presenceResource.handle, OC_LOW_QOS, &devAddr);
2513 CADestroyToken(caToken);
2516 // Each time OCStartPresence is called
2517 // a different random 32-bit integer number is used
2518 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2520 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2521 OC_PRESENCE_TRIGGER_CREATE);
2524 OCStackResult OCStopPresence()
2526 OCStackResult result = OC_STACK_ERROR;
2528 if(presenceResource.handle)
2530 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2532 // make resource inactive
2533 result = OCChangeResourceProperty(
2534 &(((OCResource *) presenceResource.handle)->resourceProperties),
2538 if(result != OC_STACK_OK)
2541 PCF("Changing the presence resource properties to ACTIVE not successful"));
2545 return SendStopNotification();
2549 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
2550 void* callbackParameter)
2552 defaultDeviceHandler = entityHandler;
2553 defaultDeviceHandlerCallbackParameter = callbackParameter;
2558 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
2560 OC_LOG(INFO, TAG, PCF("Entering OCSetPlatformInfo"));
2562 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
2564 if (validatePlatformInfo(platformInfo))
2566 return SavePlatformInfo(platformInfo);
2570 return OC_STACK_INVALID_PARAM;
2575 return OC_STACK_ERROR;
2579 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2581 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2583 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
2585 OC_LOG(ERROR, TAG, PCF("Null or empty device name."));
2586 return OC_STACK_INVALID_PARAM;
2589 return SaveDeviceInfo(deviceInfo);
2592 OCStackResult OCCreateResource(OCResourceHandle *handle,
2593 const char *resourceTypeName,
2594 const char *resourceInterfaceName,
2595 const char *uri, OCEntityHandler entityHandler,
2596 void* callbackParam,
2597 uint8_t resourceProperties)
2600 OCResource *pointer = NULL;
2602 OCStackResult result = OC_STACK_ERROR;
2604 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2606 if(myStackMode == OC_CLIENT)
2608 return OC_STACK_INVALID_PARAM;
2610 // Validate parameters
2611 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2613 OC_LOG(ERROR, TAG, PCF("URI is empty or too long"));
2614 return OC_STACK_INVALID_URI;
2616 // Is it presented during resource discovery?
2617 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
2619 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2620 return OC_STACK_INVALID_PARAM;
2623 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2625 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2628 // Make sure resourceProperties bitmask has allowed properties specified
2629 if (resourceProperties
2630 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
2631 OC_EXPLICIT_DISCOVERABLE))
2633 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2634 return OC_STACK_INVALID_PARAM;
2637 // If the headResource is NULL, then no resources have been created...
2638 pointer = headResource;
2641 // At least one resources is in the resource list, so we need to search for
2642 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2645 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
2647 OC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
2648 return OC_STACK_INVALID_PARAM;
2650 pointer = pointer->next;
2653 // Create the pointer and insert it into the resource list
2654 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
2657 result = OC_STACK_NO_MEMORY;
2660 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2662 insertResource(pointer);
2665 str = OICStrdup(uri);
2668 result = OC_STACK_NO_MEMORY;
2673 // Set properties. Set OC_ACTIVE
2674 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2677 // Add the resourcetype to the resource
2678 result = BindResourceTypeToResource(pointer, resourceTypeName);
2679 if (result != OC_STACK_OK)
2681 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2685 // Add the resourceinterface to the resource
2686 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2687 if (result != OC_STACK_OK)
2689 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2693 // If an entity handler has been passed, attach it to the newly created
2694 // resource. Otherwise, set the default entity handler.
2697 pointer->entityHandler = entityHandler;
2698 pointer->entityHandlerCallbackParam = callbackParam;
2702 pointer->entityHandler = defaultResourceEHandler;
2703 pointer->entityHandlerCallbackParam = NULL;
2707 result = OC_STACK_OK;
2709 #ifdef WITH_PRESENCE
2710 if(presenceResource.handle)
2712 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2713 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
2717 if (result != OC_STACK_OK)
2719 // Deep delete of resource and other dynamic elements that it contains
2720 deleteResource(pointer);
2727 OCStackResult OCBindResource(
2728 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2730 OCResource *resource = NULL;
2733 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2735 // Validate parameters
2736 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2737 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2738 // Container cannot contain itself
2739 if (collectionHandle == resourceHandle)
2741 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2742 return OC_STACK_INVALID_PARAM;
2745 // Use the handle to find the resource in the resource linked list
2746 resource = findResource((OCResource *) collectionHandle);
2749 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2750 return OC_STACK_INVALID_PARAM;
2753 // Look for an open slot to add add the child resource.
2754 // If found, add it and return success
2755 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2757 if (!resource->rsrcResources[i])
2759 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2760 OC_LOG(INFO, TAG, PCF("resource bound"));
2762 #ifdef WITH_PRESENCE
2763 if(presenceResource.handle)
2765 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2766 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2767 OC_PRESENCE_TRIGGER_CHANGE);
2775 // Unable to add resourceHandle, so return error
2776 return OC_STACK_ERROR;
2779 OCStackResult OCUnBindResource(
2780 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2782 OCResource *resource = NULL;
2785 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2787 // Validate parameters
2788 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2789 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2790 // Container cannot contain itself
2791 if (collectionHandle == resourceHandle)
2793 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2794 return OC_STACK_INVALID_PARAM;
2797 // Use the handle to find the resource in the resource linked list
2798 resource = findResource((OCResource *) collectionHandle);
2801 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2802 return OC_STACK_INVALID_PARAM;
2805 // Look for an open slot to add add the child resource.
2806 // If found, add it and return success
2807 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2809 if (resourceHandle == resource->rsrcResources[i])
2811 resource->rsrcResources[i] = (OCResource *) NULL;
2812 OC_LOG(INFO, TAG, PCF("resource unbound"));
2814 // Send notification when resource is unbounded successfully.
2815 #ifdef WITH_PRESENCE
2816 if(presenceResource.handle)
2818 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2819 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2820 OC_PRESENCE_TRIGGER_CHANGE);
2827 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2829 // Unable to add resourceHandle, so return error
2830 return OC_STACK_ERROR;
2833 OCStackResult BindResourceTypeToResource(OCResource* resource,
2834 const char *resourceTypeName)
2836 OCResourceType *pointer = NULL;
2838 OCStackResult result = OC_STACK_ERROR;
2840 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2842 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
2845 result = OC_STACK_NO_MEMORY;
2849 str = OICStrdup(resourceTypeName);
2852 result = OC_STACK_NO_MEMORY;
2855 pointer->resourcetypename = str;
2857 insertResourceType(resource, pointer);
2858 result = OC_STACK_OK;
2861 if (result != OC_STACK_OK)
2870 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2871 const char *resourceInterfaceName)
2873 OCResourceInterface *pointer = NULL;
2875 OCStackResult result = OC_STACK_ERROR;
2877 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2879 OC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
2881 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
2884 result = OC_STACK_NO_MEMORY;
2888 str = OICStrdup(resourceInterfaceName);
2891 result = OC_STACK_NO_MEMORY;
2894 pointer->name = str;
2896 // Bind the resourceinterface to the resource
2897 insertResourceInterface(resource, pointer);
2899 result = OC_STACK_OK;
2902 if (result != OC_STACK_OK)
2911 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2912 const char *resourceTypeName)
2915 OCStackResult result = OC_STACK_ERROR;
2916 OCResource *resource = NULL;
2918 resource = findResource((OCResource *) handle);
2921 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2922 return OC_STACK_ERROR;
2925 result = BindResourceTypeToResource(resource, resourceTypeName);
2927 #ifdef WITH_PRESENCE
2928 if(presenceResource.handle)
2930 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2931 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2938 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2939 const char *resourceInterfaceName)
2942 OCStackResult result = OC_STACK_ERROR;
2943 OCResource *resource = NULL;
2945 resource = findResource((OCResource *) handle);
2948 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2949 return OC_STACK_ERROR;
2952 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2954 #ifdef WITH_PRESENCE
2955 if(presenceResource.handle)
2957 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2958 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2965 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
2967 OCResource *pointer = headResource;
2969 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2973 *numResources = *numResources + 1;
2974 pointer = pointer->next;
2979 OCResourceHandle OCGetResourceHandle(uint8_t index)
2981 OCResource *pointer = headResource;
2983 for( uint8_t i = 0; i < index && pointer; ++i)
2985 pointer = pointer->next;
2987 return (OCResourceHandle) pointer;
2990 OCStackResult OCDeleteResource(OCResourceHandle handle)
2994 OC_LOG(ERROR, TAG, PCF("Invalid handle for deletion"));
2995 return OC_STACK_INVALID_PARAM;
2998 OCResource *resource = findResource((OCResource *) handle);
2999 if (resource == NULL)
3001 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3002 return OC_STACK_NO_RESOURCE;
3005 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3007 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
3008 return OC_STACK_ERROR;
3014 const char *OCGetResourceUri(OCResourceHandle handle)
3016 OCResource *resource = NULL;
3018 resource = findResource((OCResource *) handle);
3021 return resource->uri;
3023 return (const char *) NULL;
3026 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3028 OCResource *resource = NULL;
3030 resource = findResource((OCResource *) handle);
3033 return resource->resourceProperties;
3035 return (OCResourceProperty)-1;
3038 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3039 uint8_t *numResourceTypes)
3041 OCResource *resource = NULL;
3042 OCResourceType *pointer = NULL;
3044 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3045 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3047 *numResourceTypes = 0;
3049 resource = findResource((OCResource *) handle);
3052 pointer = resource->rsrcType;
3055 *numResourceTypes = *numResourceTypes + 1;
3056 pointer = pointer->next;
3062 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3064 OCResourceType *resourceType = NULL;
3066 resourceType = findResourceTypeAtIndex(handle, index);
3069 return resourceType->resourcetypename;
3071 return (const char *) NULL;
3074 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3075 uint8_t *numResourceInterfaces)
3077 OCResourceInterface *pointer = NULL;
3078 OCResource *resource = NULL;
3080 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3081 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3083 *numResourceInterfaces = 0;
3084 resource = findResource((OCResource *) handle);
3087 pointer = resource->rsrcInterface;
3090 *numResourceInterfaces = *numResourceInterfaces + 1;
3091 pointer = pointer->next;
3097 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3099 OCResourceInterface *resourceInterface = NULL;
3101 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3102 if (resourceInterface)
3104 return resourceInterface->name;
3106 return (const char *) NULL;
3109 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3112 OCResource *resource = NULL;
3114 if (index >= MAX_CONTAINED_RESOURCES)
3119 resource = findResource((OCResource *) collectionHandle);
3125 return resource->rsrcResources[index];
3128 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3129 OCEntityHandler entityHandler,
3130 void* callbackParam)
3132 OCResource *resource = NULL;
3134 // Validate parameters
3135 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3137 // Use the handle to find the resource in the resource linked list
3138 resource = findResource((OCResource *)handle);
3141 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3142 return OC_STACK_ERROR;
3146 resource->entityHandler = entityHandler;
3147 resource->entityHandlerCallbackParam = callbackParam;
3149 #ifdef WITH_PRESENCE
3150 if(presenceResource.handle)
3152 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3153 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3160 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3162 OCResource *resource = NULL;
3164 resource = findResource((OCResource *)handle);
3167 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3172 return resource->entityHandler;
3175 void incrementSequenceNumber(OCResource * resPtr)
3177 // Increment the sequence number
3178 resPtr->sequenceNum += 1;
3179 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3181 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3186 #ifdef WITH_PRESENCE
3187 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3188 OCPresenceTrigger trigger)
3190 OCResource *resPtr = NULL;
3191 OCStackResult result = OC_STACK_ERROR;
3192 OCMethod method = OC_REST_PRESENCE;
3193 uint32_t maxAge = 0;
3194 resPtr = findResource((OCResource *) presenceResource.handle);
3197 return OC_STACK_NO_RESOURCE;
3200 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3202 maxAge = presenceResource.presenceTTL;
3204 result = SendAllObserverNotification(method, resPtr, maxAge,
3205 trigger, resourceType, OC_LOW_QOS);
3211 OCStackResult SendStopNotification()
3213 OCResource *resPtr = NULL;
3214 OCStackResult result = OC_STACK_ERROR;
3215 OCMethod method = OC_REST_PRESENCE;
3216 resPtr = findResource((OCResource *) presenceResource.handle);
3219 return OC_STACK_NO_RESOURCE;
3222 // maxAge is 0. ResourceType is NULL.
3223 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3229 #endif // WITH_PRESENCE
3230 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3232 OCResource *resPtr = NULL;
3233 OCStackResult result = OC_STACK_ERROR;
3234 OCMethod method = OC_REST_NOMETHOD;
3235 uint32_t maxAge = 0;
3237 OC_LOG(INFO, TAG, PCF("Notifying all observers"));
3238 #ifdef WITH_PRESENCE
3239 if(handle == presenceResource.handle)
3243 #endif // WITH_PRESENCE
3244 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3246 // Verify that the resource exists
3247 resPtr = findResource ((OCResource *) handle);
3250 return OC_STACK_NO_RESOURCE;
3254 //only increment in the case of regular observing (not presence)
3255 incrementSequenceNumber(resPtr);
3256 method = OC_REST_OBSERVE;
3257 maxAge = MAX_OBSERVE_AGE;
3258 #ifdef WITH_PRESENCE
3259 result = SendAllObserverNotification (method, resPtr, maxAge,
3260 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3262 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3269 OCNotifyListOfObservers (OCResourceHandle handle,
3270 OCObservationId *obsIdList,
3271 uint8_t numberOfIds,
3272 const OCRepPayload *payload,
3273 OCQualityOfService qos)
3275 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3277 OCResource *resPtr = NULL;
3278 //TODO: we should allow the server to define this
3279 uint32_t maxAge = MAX_OBSERVE_AGE;
3281 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3282 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3283 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3285 resPtr = findResource ((OCResource *) handle);
3286 if (NULL == resPtr || myStackMode == OC_CLIENT)
3288 return OC_STACK_NO_RESOURCE;
3292 incrementSequenceNumber(resPtr);
3294 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3295 payload, maxAge, qos));
3298 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3300 OCStackResult result = OC_STACK_ERROR;
3301 OCServerRequest *serverRequest = NULL;
3303 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3305 // Validate input parameters
3306 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3307 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3310 // Get pointer to request info
3311 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3314 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3315 result = serverRequest->ehResponseHandler(ehResponse);
3321 //-----------------------------------------------------------------------------
3322 // Private internal function definitions
3323 //-----------------------------------------------------------------------------
3324 static OCDoHandle GenerateInvocationHandle()
3326 OCDoHandle handle = NULL;
3327 // Generate token here, it will be deleted when the transaction is deleted
3328 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3331 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3337 #ifdef WITH_PRESENCE
3338 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3339 OCResourceProperty resourceProperties, uint8_t enable)
3343 return OC_STACK_INVALID_PARAM;
3345 if (resourceProperties
3346 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3348 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3349 return OC_STACK_INVALID_PARAM;
3353 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3357 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3363 OCStackResult initResources()
3365 OCStackResult result = OC_STACK_OK;
3367 headResource = NULL;
3368 tailResource = NULL;
3369 // Init Virtual Resources
3370 #ifdef WITH_PRESENCE
3371 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3373 result = OCCreateResource(&presenceResource.handle,
3374 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3376 OC_RSRVD_PRESENCE_URI,
3380 //make resource inactive
3381 result = OCChangeResourceProperty(
3382 &(((OCResource *) presenceResource.handle)->resourceProperties),
3386 if (result == OC_STACK_OK)
3388 result = SRMInitSecureResources();
3394 void insertResource(OCResource *resource)
3398 headResource = resource;
3399 tailResource = resource;
3403 tailResource->next = resource;
3404 tailResource = resource;
3406 resource->next = NULL;
3409 OCResource *findResource(OCResource *resource)
3411 OCResource *pointer = headResource;
3415 if (pointer == resource)
3419 pointer = pointer->next;
3424 void deleteAllResources()
3426 OCResource *pointer = headResource;
3427 OCResource *temp = NULL;
3431 temp = pointer->next;
3432 #ifdef WITH_PRESENCE
3433 if(pointer != (OCResource *) presenceResource.handle)
3435 #endif // WITH_PRESENCE
3436 deleteResource(pointer);
3437 #ifdef WITH_PRESENCE
3439 #endif // WITH_PRESENCE
3443 SRMDeInitSecureResources();
3445 #ifdef WITH_PRESENCE
3446 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3447 // presence notification attributed to their deletion to be processed.
3448 deleteResource((OCResource *) presenceResource.handle);
3449 #endif // WITH_PRESENCE
3452 OCStackResult deleteResource(OCResource *resource)
3454 OCResource *prev = NULL;
3455 OCResource *temp = NULL;
3458 OC_LOG_V(DEBUG,TAG,"resource is NULL");
3459 return OC_STACK_INVALID_PARAM;
3462 OC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
3464 temp = headResource;
3467 if (temp == resource)
3469 // Invalidate all Resource Properties.
3470 resource->resourceProperties = (OCResourceProperty) 0;
3471 #ifdef WITH_PRESENCE
3472 if(resource != (OCResource *) presenceResource.handle)
3474 #endif // WITH_PRESENCE
3475 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3476 #ifdef WITH_PRESENCE
3479 if(presenceResource.handle)
3481 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3482 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
3485 // Only resource in list.
3486 if (temp == headResource && temp == tailResource)
3488 headResource = NULL;
3489 tailResource = NULL;
3492 else if (temp == headResource)
3494 headResource = temp->next;
3497 else if (temp == tailResource)
3499 tailResource = prev;
3500 tailResource->next = NULL;
3504 prev->next = temp->next;
3507 deleteResourceElements(temp);
3518 return OC_STACK_ERROR;
3521 void deleteResourceElements(OCResource *resource)
3528 OICFree(resource->uri);
3529 deleteResourceType(resource->rsrcType);
3530 deleteResourceInterface(resource->rsrcInterface);
3533 void deleteResourceType(OCResourceType *resourceType)
3535 OCResourceType *pointer = resourceType;
3536 OCResourceType *next = NULL;
3540 next = pointer->next;
3541 OICFree(pointer->resourcetypename);
3547 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3549 OCResourceInterface *pointer = resourceInterface;
3550 OCResourceInterface *next = NULL;
3554 next = pointer->next;
3555 OICFree(pointer->name);
3561 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3563 OCResourceType *pointer = NULL;
3564 OCResourceType *previous = NULL;
3565 if (!resource || !resourceType)
3569 // resource type list is empty.
3570 else if (!resource->rsrcType)
3572 resource->rsrcType = resourceType;
3576 pointer = resource->rsrcType;
3580 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
3582 OC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
3583 OICFree(resourceType->resourcetypename);
3584 OICFree(resourceType);
3588 pointer = pointer->next;
3590 previous->next = resourceType;
3592 resourceType->next = NULL;
3594 OC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
3597 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3599 OCResource *resource = NULL;
3600 OCResourceType *pointer = NULL;
3602 // Find the specified resource
3603 resource = findResource((OCResource *) handle);
3609 // Make sure a resource has a resourcetype
3610 if (!resource->rsrcType)
3615 // Iterate through the list
3616 pointer = resource->rsrcType;
3617 for(uint8_t i = 0; i< index && pointer; ++i)
3619 pointer = pointer->next;
3624 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3626 if(resourceTypeList && resourceTypeName)
3628 OCResourceType * rtPointer = resourceTypeList;
3629 while(resourceTypeName && rtPointer)
3631 if(rtPointer->resourcetypename &&
3632 strcmp(resourceTypeName, (const char *)
3633 (rtPointer->resourcetypename)) == 0)
3637 rtPointer = rtPointer->next;
3645 * Insert a new interface into interface linked list only if not already present.
3646 * If alredy present, 2nd arg is free'd.
3647 * Default interface will always be first if present.
3649 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
3651 OCResourceInterface *pointer = NULL;
3652 OCResourceInterface *previous = NULL;
3654 newInterface->next = NULL;
3656 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
3658 if (!*firstInterface)
3660 *firstInterface = newInterface;
3662 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3664 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3666 OICFree(newInterface->name);
3667 OICFree(newInterface);
3672 newInterface->next = *firstInterface;
3673 *firstInterface = newInterface;
3678 pointer = *firstInterface;
3681 if (strcmp(newInterface->name, pointer->name) == 0)
3683 OICFree(newInterface->name);
3684 OICFree(newInterface);
3688 pointer = pointer->next;
3690 previous->next = newInterface;
3694 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3697 OCResource *resource = NULL;
3698 OCResourceInterface *pointer = NULL;
3700 // Find the specified resource
3701 resource = findResource((OCResource *) handle);
3707 // Make sure a resource has a resourceinterface
3708 if (!resource->rsrcInterface)
3713 // Iterate through the list
3714 pointer = resource->rsrcInterface;
3716 for (uint8_t i = 0; i < index && pointer; ++i)
3718 pointer = pointer->next;
3724 * This function splits the uri using the '?' delimiter.
3725 * "uriWithoutQuery" is the block of characters between the beginning
3726 * till the delimiter or '\0' which ever comes first.
3727 * "query" is whatever is to the right of the delimiter if present.
3728 * No delimiter sets the query to NULL.
3729 * If either are present, they will be malloc'ed into the params 2, 3.
3730 * The first param, *uri is left untouched.
3732 * NOTE: This function does not account for whitespace at the end of the uri NOR
3733 * malformed uri's with '??'. Whitespace at the end will be assumed to be
3734 * part of the query.
3736 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
3740 return OC_STACK_INVALID_URI;
3742 if(!query || !uriWithoutQuery)
3744 return OC_STACK_INVALID_PARAM;
3748 *uriWithoutQuery = NULL;
3750 size_t uriWithoutQueryLen = 0;
3751 size_t queryLen = 0;
3752 size_t uriLen = strlen(uri);
3754 char *pointerToDelimiter = strstr(uri, "?");
3756 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : pointerToDelimiter - uri;
3757 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
3759 if (uriWithoutQueryLen)
3761 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
3762 if (!*uriWithoutQuery)
3766 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
3770 *query = (char *) OICCalloc(queryLen + 1, 1);
3773 OICFree(*uriWithoutQuery);
3774 *uriWithoutQuery = NULL;
3777 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
3783 return OC_STACK_NO_MEMORY;
3786 const uint8_t* OCGetServerInstanceID(void)
3788 static bool generated = false;
3789 static ServerID sid;
3795 if (OCGenerateUuid(sid) != RAND_UUID_OK)
3797 OC_LOG(FATAL, TAG, PCF("Generate UUID for Server Instance failed!"));
3804 const char* OCGetServerInstanceIDString(void)
3806 static bool generated = false;
3807 static char sidStr[UUID_STRING_SIZE];
3814 const uint8_t* sid = OCGetServerInstanceID();
3816 if(OCConvertUuidToString(sid, sidStr) != RAND_UUID_OK)
3818 OC_LOG(FATAL, TAG, PCF("Generate UUID String for Server Instance failed!"));
3826 CAResult_t OCSelectNetwork()
3828 CAResult_t retResult = CA_STATUS_FAILED;
3829 CAResult_t caResult = CA_STATUS_OK;
3831 CATransportAdapter_t connTypes[] = {
3833 CA_ADAPTER_RFCOMM_BTEDR,
3834 CA_ADAPTER_GATT_BTLE
3837 ,CA_ADAPTER_REMOTE_ACCESS
3840 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
3842 for(int i = 0; i<numConnTypes; i++)
3844 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
3845 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
3847 caResult = CASelectNetwork(connTypes[i]);
3848 if(caResult == CA_STATUS_OK)
3850 retResult = CA_STATUS_OK;
3855 if(retResult != CA_STATUS_OK)
3857 return caResult; // Returns error of appropriate transport that failed fatally.
3863 OCStackResult CAResultToOCResult(CAResult_t caResult)
3869 case CA_STATUS_INVALID_PARAM:
3870 return OC_STACK_INVALID_PARAM;
3871 case CA_ADAPTER_NOT_ENABLED:
3872 return OC_STACK_ADAPTER_NOT_ENABLED;
3873 case CA_SERVER_STARTED_ALREADY:
3875 case CA_SERVER_NOT_STARTED:
3876 return OC_STACK_ERROR;
3877 case CA_DESTINATION_NOT_REACHABLE:
3878 return OC_STACK_COMM_ERROR;
3879 case CA_SOCKET_OPERATION_FAILED:
3880 return OC_STACK_COMM_ERROR;
3881 case CA_SEND_FAILED:
3882 return OC_STACK_COMM_ERROR;
3883 case CA_RECEIVE_FAILED:
3884 return OC_STACK_COMM_ERROR;
3885 case CA_MEMORY_ALLOC_FAILED:
3886 return OC_STACK_NO_MEMORY;
3887 case CA_REQUEST_TIMEOUT:
3888 return OC_STACK_TIMEOUT;
3889 case CA_DESTINATION_DISCONNECTED:
3890 return OC_STACK_COMM_ERROR;
3891 case CA_STATUS_FAILED:
3892 return OC_STACK_ERROR;
3893 case CA_NOT_SUPPORTED:
3894 return OC_STACK_NOTIMPL;
3896 return OC_STACK_ERROR;