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 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
401 out->port = in->port;
402 out->interface = in->interface;
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 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
413 out->port = in->port;
414 out->interface = in->interface;
417 void FixUpClientResponse(OCClientResponse *cr)
419 VERIFY_NON_NULL_NR(cr, FATAL);
421 cr->addr = &cr->devAddr;
422 cr->connType = (OCConnectivityType)
423 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
426 //-----------------------------------------------------------------------------
427 // Internal API function
428 //-----------------------------------------------------------------------------
430 // This internal function is called to update the stack with the status of
431 // observers and communication failures
432 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
434 OCStackResult result = OC_STACK_ERROR;
435 ResourceObserver * observer = NULL;
436 OCEntityHandlerRequest ehRequest = {0};
440 case OC_OBSERVER_NOT_INTERESTED:
441 OC_LOG(DEBUG, TAG, PCF("observer not interested in our notifications"));
442 observer = GetObserverUsingToken (token, tokenLength);
445 result = FormOCEntityHandlerRequest(&ehRequest,
446 (OCRequestHandle)NULL,
449 (OCResourceHandle)NULL,
450 NULL, NULL, 0, 0, NULL,
451 OC_OBSERVE_DEREGISTER,
452 observer->observeId);
453 if(result != OC_STACK_OK)
457 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
458 observer->resource->entityHandlerCallbackParam);
461 result = DeleteObserverUsingToken (token, tokenLength);
462 if(result == OC_STACK_OK)
464 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
468 result = OC_STACK_OK;
469 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
473 case OC_OBSERVER_STILL_INTERESTED:
474 OC_LOG(DEBUG, TAG, PCF("observer still interested, reset the failedCount"));
475 observer = GetObserverUsingToken (token, tokenLength);
478 observer->forceHighQos = 0;
479 observer->failedCommCount = 0;
480 result = OC_STACK_OK;
484 result = OC_STACK_OBSERVER_NOT_FOUND;
488 case OC_OBSERVER_FAILED_COMM:
489 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
490 observer = GetObserverUsingToken (token, tokenLength);
493 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
495 result = FormOCEntityHandlerRequest(&ehRequest,
496 (OCRequestHandle)NULL,
499 (OCResourceHandle)NULL,
500 NULL, NULL, 0, 0, NULL,
501 OC_OBSERVE_DEREGISTER,
502 observer->observeId);
503 if(result != OC_STACK_OK)
505 return OC_STACK_ERROR;
507 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
508 observer->resource->entityHandlerCallbackParam);
510 result = DeleteObserverUsingToken (token, tokenLength);
511 if(result == OC_STACK_OK)
513 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
517 result = OC_STACK_OK;
518 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
523 observer->failedCommCount++;
524 result = OC_STACK_CONTINUE;
526 observer->forceHighQos = 1;
527 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
531 OC_LOG(ERROR, TAG, PCF("Unknown status"));
532 result = OC_STACK_ERROR;
537 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
539 OCStackResult ret = OC_STACK_ERROR;
547 ret = OC_STACK_RESOURCE_CREATED;
550 ret = OC_STACK_RESOURCE_DELETED;
553 ret = OC_STACK_INVALID_QUERY;
555 case CA_UNAUTHORIZED_REQ:
556 ret = OC_STACK_UNAUTHORIZED_REQ;
559 ret = OC_STACK_INVALID_OPTION;
562 ret = OC_STACK_NO_RESOURCE;
564 case CA_RETRANSMIT_TIMEOUT:
565 ret = OC_STACK_COMM_ERROR;
573 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode)
575 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
582 case OC_STACK_RESOURCE_CREATED:
585 case OC_STACK_RESOURCE_DELETED:
588 case OC_STACK_INVALID_QUERY:
591 case OC_STACK_INVALID_OPTION:
594 case OC_STACK_NO_RESOURCE:
597 case OC_STACK_COMM_ERROR:
598 ret = CA_RETRANSMIT_TIMEOUT;
600 case OC_STACK_UNAUTHORIZED_REQ:
601 ret = CA_UNAUTHORIZED_REQ;
609 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
611 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
613 // supply default behavior.
614 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
616 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
618 if ((caFlags & OC_MASK_SCOPE) == 0)
620 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
625 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
627 return (OCTransportFlags)caFlags;
630 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
632 uint32_t lowerBound = 0;
633 uint32_t higherBound = 0;
635 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
637 return OC_STACK_INVALID_PARAM;
640 OC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
642 cbNode->presence->TTL = maxAgeSeconds;
644 for (int index = 0; index < PresenceTimeOutSize; index++)
646 // Guard against overflow
647 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
650 lowerBound = GetTicks((PresenceTimeOut[index] *
651 cbNode->presence->TTL *
652 MILLISECONDS_PER_SECOND)/100);
656 lowerBound = GetTicks(UINT32_MAX);
659 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
662 higherBound = GetTicks((PresenceTimeOut[index + 1] *
663 cbNode->presence->TTL *
664 MILLISECONDS_PER_SECOND)/100);
668 higherBound = GetTicks(UINT32_MAX);
671 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
673 OC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
674 OC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
675 OC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
678 cbNode->presence->TTLlevel = 0;
680 OC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
684 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
686 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
688 return OC_RSRVD_TRIGGER_CREATE;
690 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
692 return OC_RSRVD_TRIGGER_CHANGE;
696 return OC_RSRVD_TRIGGER_DELETE;
700 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
704 return OC_PRESENCE_TRIGGER_CREATE;
706 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
708 return OC_PRESENCE_TRIGGER_CREATE;
710 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
712 return OC_PRESENCE_TRIGGER_CHANGE;
716 return OC_PRESENCE_TRIGGER_DELETE;
721 * The cononical presence allows constructed URIs to be string compared.
723 * requestUri must be a char array of size CA_MAX_URI_LENGTH
725 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
728 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
729 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
730 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
732 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
734 if (ep->adapter == CA_ADAPTER_IP)
736 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
738 if ('\0' == ep->addr[0]) // multicast
740 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
744 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
745 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
750 if ('\0' == ep->addr[0]) // multicast
752 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
753 ep->port = OC_MULTICAST_PORT;
755 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
756 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
760 // might work for other adapters (untested, but better than nothing)
761 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
762 OC_RSRVD_PRESENCE_URI);
766 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
767 const CAResponseInfo_t *responseInfo)
769 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
770 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
772 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
773 ClientCB * cbNode = NULL;
774 char *resourceTypeName = NULL;
775 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
776 OCStackResult result = OC_STACK_ERROR;
779 char presenceUri[CA_MAX_URI_LENGTH];
781 int presenceSubscribe = 0;
782 int multicastPresenceSubscribe = 0;
784 if (responseInfo->result != CA_SUCCESS)
786 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
787 return OC_STACK_ERROR;
790 // check for unicast presence
791 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
792 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
794 return OC_STACK_INVALID_URI;
797 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
800 presenceSubscribe = 1;
804 // check for multiicast presence
805 CAEndpoint_t ep = { .adapter = endpoint->adapter,
806 .flags = endpoint->flags };
808 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
810 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
813 multicastPresenceSubscribe = 1;
817 if (!presenceSubscribe && !multicastPresenceSubscribe)
819 OC_LOG(ERROR, TAG, PCF("Received a presence notification, but no callback, ignoring"));
823 response.payload = NULL;
824 response.result = OC_STACK_OK;
826 CopyEndpointToDevAddr(endpoint, &response.devAddr);
827 FixUpClientResponse(&response);
829 if (responseInfo->info.payload)
831 result = OCParsePayload(&response.payload, responseInfo->info.payload,
832 responseInfo->info.payloadSize);
834 if(result != OC_STACK_OK)
836 OC_LOG(ERROR, TAG, PCF("Presence parse failed"));
839 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
841 OC_LOG(ERROR, TAG, PCF("Presence payload was wrong type"));
842 result = OC_STACK_ERROR;
845 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
846 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
847 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
850 if (presenceSubscribe)
852 if(cbNode->sequenceNumber == response.sequenceNumber)
854 OC_LOG(INFO, TAG, PCF("No presence change"));
860 OC_LOG(INFO, TAG, PCF("Stopping presence"));
861 response.result = OC_STACK_PRESENCE_STOPPED;
864 OICFree(cbNode->presence->timeOut);
865 OICFree(cbNode->presence);
866 cbNode->presence = NULL;
871 if(!cbNode->presence)
873 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
875 if(!(cbNode->presence))
877 OC_LOG(ERROR, TAG, PCF("Could not allocate memory for cbNode->presence"));
878 result = OC_STACK_NO_MEMORY;
882 VERIFY_NON_NULL_V(cbNode->presence);
883 cbNode->presence->timeOut = NULL;
884 cbNode->presence->timeOut = (uint32_t *)
885 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
886 if(!(cbNode->presence->timeOut)){
888 PCF("Could not allocate memory for cbNode->presence->timeOut"));
889 OICFree(cbNode->presence);
890 result = OC_STACK_NO_MEMORY;
895 ResetPresenceTTL(cbNode, maxAge);
897 cbNode->sequenceNumber = response.sequenceNumber;
899 // Ensure that a filter is actually applied.
900 if( resourceTypeName && cbNode->filterResourceType)
902 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
911 // This is the multicast case
912 OCMulticastNode* mcNode = NULL;
913 mcNode = GetMCPresenceNode(presenceUri);
917 if(mcNode->nonce == response.sequenceNumber)
919 OC_LOG(INFO, TAG, PCF("No presence change (Multicast)"));
922 mcNode->nonce = response.sequenceNumber;
926 OC_LOG(INFO, TAG, PCF("Stopping presence"));
927 response.result = OC_STACK_PRESENCE_STOPPED;
932 char* uri = OICStrdup(presenceUri);
936 PCF("No Memory for URI to store in the presence node"));
937 result = OC_STACK_NO_MEMORY;
941 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
942 if(result == OC_STACK_NO_MEMORY)
945 PCF("No Memory for Multicast Presence Node"));
949 // presence node now owns uri
952 // Ensure that a filter is actually applied.
953 if(resourceTypeName && cbNode->filterResourceType)
955 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
962 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
964 if (cbResult == OC_STACK_DELETE_TRANSACTION)
966 FindAndDeleteClientCB(cbNode);
970 OCPayloadDestroy(response.payload);
974 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
976 VERIFY_NON_NULL_NR(endPoint, FATAL);
977 VERIFY_NON_NULL_NR(responseInfo, FATAL);
979 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
981 if(responseInfo->info.resourceUri &&
982 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
984 HandlePresenceResponse(endPoint, responseInfo);
988 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
989 responseInfo->info.tokenLength, NULL, NULL);
991 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
992 responseInfo->info.tokenLength);
996 OC_LOG(INFO, TAG, PCF("There is a cbNode associated with the response token"));
997 if(responseInfo->result == CA_EMPTY)
999 OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
1000 // We do not have a case for the client to receive a RESET
1001 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1003 //This is the case of receiving an ACK on a request to a slow resource!
1004 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
1005 //TODO: should we inform the client
1006 // app that at least the request was received at the server?
1009 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1011 OC_LOG(INFO, TAG, PCF("Receiving A Timeout for this token"));
1012 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1014 OCClientResponse response =
1015 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1016 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1017 FixUpClientResponse(&response);
1018 response.resourceUri = responseInfo->info.resourceUri;
1019 memcpy(response.identity.id, responseInfo->info.identity.id,
1020 sizeof (response.identity.id));
1021 response.identity.id_length = responseInfo->info.identity.id_length;
1023 response.result = CAToOCStackResult(responseInfo->result);
1024 cbNode->callBack(cbNode->context,
1025 cbNode->handle, &response);
1026 FindAndDeleteClientCB(cbNode);
1030 OC_LOG(INFO, TAG, PCF("This is a regular response, A client call back is found"));
1031 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1033 OCClientResponse response =
1034 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1035 response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1036 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1037 FixUpClientResponse(&response);
1038 response.resourceUri = responseInfo->info.resourceUri;
1039 memcpy(response.identity.id, responseInfo->info.identity.id,
1040 sizeof (response.identity.id));
1041 response.identity.id_length = responseInfo->info.identity.id_length;
1043 response.result = CAToOCStackResult(responseInfo->result);
1044 if(responseInfo->info.payload &&
1045 responseInfo->info.payloadSize &&
1046 OC_STACK_OK != OCParsePayload(&response.payload, responseInfo->info.payload,
1047 responseInfo->info.payloadSize))
1049 OC_LOG(ERROR, TAG, PCF("Error converting payload"));
1050 OCPayloadDestroy(response.payload);
1054 response.numRcvdVendorSpecificHeaderOptions = 0;
1055 if(responseInfo->info.numOptions > 0)
1058 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1059 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1061 memcpy (&(response.sequenceNumber),
1062 &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
1063 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1068 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1071 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1073 OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
1074 OCPayloadDestroy(response.payload);
1078 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1080 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1081 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1085 if (cbNode->method == OC_REST_OBSERVE &&
1086 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1087 response.sequenceNumber <= cbNode->sequenceNumber)
1089 OC_LOG_V(INFO, TAG, PCF("Received stale notification. Number :%d"),
1090 response.sequenceNumber);
1094 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1097 cbNode->sequenceNumber = response.sequenceNumber;
1099 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1101 FindAndDeleteClientCB(cbNode);
1105 // To keep discovery callbacks active.
1106 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1107 MILLISECONDS_PER_SECOND);
1111 //Need to send ACK when the response is CON
1112 if(responseInfo->info.type == CA_MSG_CONFIRM)
1114 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1115 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0);
1118 OCPayloadDestroy(response.payload);
1125 OC_LOG(INFO, TAG, PCF("There is an observer associated with the response token"));
1126 if(responseInfo->result == CA_EMPTY)
1128 OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
1129 if(responseInfo->info.type == CA_MSG_RESET)
1131 OC_LOG(INFO, TAG, PCF("This is a RESET"));
1132 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1133 OC_OBSERVER_NOT_INTERESTED);
1135 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1137 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
1138 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1139 OC_OBSERVER_STILL_INTERESTED);
1142 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1144 OC_LOG(INFO, TAG, PCF("Receiving Time Out for an observer"));
1145 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1146 OC_OBSERVER_FAILED_COMM);
1151 if(!cbNode && !observer)
1153 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER)
1155 OC_LOG(INFO, TAG, PCF("This is a client, but no cbNode was found for token"));
1156 if(responseInfo->result == CA_EMPTY)
1158 OC_LOG(INFO, TAG, PCF("Receiving CA_EMPTY in the ocstack"));
1162 OC_LOG(INFO, TAG, PCF("Received a message without callbacks. Sending RESET"));
1163 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1164 CA_MSG_RESET, 0, NULL, NULL, 0);
1168 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
1170 OC_LOG(INFO, TAG, PCF("This is a server, but no observer was found for token"));
1171 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1173 OC_LOG_V(INFO, TAG, PCF("Received ACK at server for messageId : %d"),
1174 responseInfo->info.messageId);
1176 if (responseInfo->info.type == CA_MSG_RESET)
1178 OC_LOG_V(INFO, TAG, PCF("Received RESET at server for messageId : %d"),
1179 responseInfo->info.messageId);
1186 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
1190 * This function handles error response from CA
1191 * code shall be added to handle the errors
1193 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1195 OC_LOG(INFO, TAG, PCF("Enter HandleCAErrorResponse"));
1197 if(NULL == endPoint)
1199 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1203 if(NULL == errrorInfo)
1205 OC_LOG(ERROR, TAG, PCF("errrorInfo is NULL"));
1208 OC_LOG(INFO, TAG, PCF("Exit HandleCAErrorResponse"));
1212 * This function sends out Direct Stack Responses. These are responses that are not coming
1213 * from the application entity handler. These responses have no payload and are usually ACKs,
1214 * RESETs or some error conditions that were caught by the stack.
1216 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1217 const CAResponseResult_t responseResult, const CAMessageType_t type,
1218 const uint8_t numOptions, const CAHeaderOption_t *options,
1219 CAToken_t token, uint8_t tokenLength)
1221 CAResponseInfo_t respInfo = {
1222 .result = responseResult
1224 respInfo.info.messageId = coapID;
1225 respInfo.info.numOptions = numOptions;
1226 respInfo.info.options = (CAHeaderOption_t*)options;
1227 respInfo.info.payload = NULL;
1228 respInfo.info.token = token;
1229 respInfo.info.tokenLength = tokenLength;
1230 respInfo.info.type = type;
1232 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1233 if(caResult != CA_STATUS_OK)
1235 OC_LOG(ERROR, TAG, PCF("CASendResponse error"));
1236 return OC_STACK_ERROR;
1241 //This function will be called back by CA layer when a request is received
1242 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1244 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
1247 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1253 OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
1257 OCStackResult requestResult = OC_STACK_ERROR;
1259 if(myStackMode == OC_CLIENT)
1261 //TODO: should the client be responding to requests?
1265 OCServerProtocolRequest serverRequest = {0};
1267 OC_LOG_V(INFO, TAG, PCF("Endpoint URI : %s"), requestInfo->info.resourceUri);
1269 char * uriWithoutQuery = NULL;
1270 char * query = NULL;
1272 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1274 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1276 OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1279 OC_LOG_V(INFO, TAG, PCF("URI without query: %s"), uriWithoutQuery);
1280 OC_LOG_V(INFO, TAG, PCF("Query : %s"), query);
1282 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1284 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1285 OICFree(uriWithoutQuery);
1289 OC_LOG(ERROR, TAG, PCF("URI length exceeds MAX_URI_LENGTH."));
1290 OICFree(uriWithoutQuery);
1297 if(strlen(query) < MAX_QUERY_LENGTH)
1299 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1304 OC_LOG(ERROR, TAG, PCF("Query length exceeds MAX_QUERY_LENGTH."));
1310 if (requestInfo->info.payload)
1312 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1313 memcpy (&(serverRequest.payload), requestInfo->info.payload,
1314 requestInfo->info.payloadSize);
1318 serverRequest.reqTotalSize = 0;
1321 switch (requestInfo->method)
1324 serverRequest.method = OC_REST_GET;
1327 serverRequest.method = OC_REST_PUT;
1330 serverRequest.method = OC_REST_POST;
1333 serverRequest.method = OC_REST_DELETE;
1336 OC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1337 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1338 requestInfo->info.type, requestInfo->info.numOptions,
1339 requestInfo->info.options, requestInfo->info.token,
1340 requestInfo->info.tokenLength);
1344 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1345 requestInfo->info.tokenLength);
1346 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1347 serverRequest.tokenLength = requestInfo->info.tokenLength;
1349 if (!serverRequest.requestToken)
1351 OC_LOG(FATAL, TAG, "Allocation for token failed.");
1352 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1353 requestInfo->info.type, requestInfo->info.numOptions,
1354 requestInfo->info.options, requestInfo->info.token,
1355 requestInfo->info.tokenLength);
1358 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1360 if (requestInfo->info.type == CA_MSG_CONFIRM)
1362 serverRequest.qos = OC_HIGH_QOS;
1366 serverRequest.qos = OC_LOW_QOS;
1368 // CA does not need the following field
1369 // Are we sure CA does not need them? how is it responding to multicast
1370 serverRequest.delayedResNeeded = 0;
1372 serverRequest.coapID = requestInfo->info.messageId;
1374 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1376 // copy vendor specific header options
1377 uint8_t tempNum = (requestInfo->info.numOptions);
1378 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1379 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1382 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
1383 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1384 requestInfo->info.type, requestInfo->info.numOptions,
1385 requestInfo->info.options, requestInfo->info.token,
1386 requestInfo->info.tokenLength);
1387 OICFree(serverRequest.requestToken);
1390 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1391 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1393 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1394 sizeof(CAHeaderOption_t)*tempNum);
1397 requestResult = HandleStackRequests (&serverRequest);
1399 // Send ACK to client as precursor to slow response
1400 if(requestResult == OC_STACK_SLOW_RESOURCE)
1402 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1403 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0);
1405 else if(requestResult != OC_STACK_OK)
1407 OC_LOG_V(ERROR, TAG, PCF("HandleStackRequests failed. error: %d"), requestResult);
1409 CAResponseResult_t stackResponse = OCToCAStackResult(requestResult);
1411 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1412 requestInfo->info.type, requestInfo->info.numOptions,
1413 requestInfo->info.options, requestInfo->info.token,
1414 requestInfo->info.tokenLength);
1416 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1417 // The token is copied in there, and is thus still owned by this function.
1418 OICFree(serverRequest.requestToken);
1419 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
1422 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1424 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
1425 OCStackResult result = OC_STACK_ERROR;
1426 ResourceHandling resHandling;
1427 OCResource *resource;
1428 if(!protocolRequest)
1430 OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
1431 return OC_STACK_INVALID_PARAM;
1434 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1435 protocolRequest->tokenLength);
1438 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
1439 result = AddServerRequest(&request, protocolRequest->coapID,
1440 protocolRequest->delayedResNeeded, 0,
1441 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
1442 protocolRequest->observationOption, protocolRequest->qos,
1443 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1444 protocolRequest->payload, protocolRequest->requestToken,
1445 protocolRequest->tokenLength,
1446 protocolRequest->resourceUrl, protocolRequest->reqTotalSize,
1447 &protocolRequest->devAddr);
1448 if (OC_STACK_OK != result)
1450 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
1456 OC_LOG(ERROR, TAG, PCF("Out of Memory"));
1457 return OC_STACK_NO_MEMORY;
1460 if(!protocolRequest->reqMorePacket)
1462 request->requestComplete = 1;
1467 OC_LOG(INFO, TAG, PCF("This is either a repeated or blocked Server Request"));
1470 if(request->requestComplete)
1472 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
1473 result = DetermineResourceHandling (request, &resHandling, &resource);
1474 if (result == OC_STACK_OK)
1476 result = ProcessRequest(resHandling, resource, request);
1481 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
1482 result = OC_STACK_CONTINUE;
1487 bool validatePlatformInfo(OCPlatformInfo info)
1490 if (!info.platformID)
1492 OC_LOG(ERROR, TAG, PCF("No platform ID found."));
1496 if (info.manufacturerName)
1498 size_t lenManufacturerName = strlen(info.manufacturerName);
1500 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1502 OC_LOG(ERROR, TAG, PCF("Manufacturer name fails length requirements."));
1508 OC_LOG(ERROR, TAG, PCF("No manufacturer name present"));
1512 if (info.manufacturerUrl)
1514 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1516 OC_LOG(ERROR, TAG, PCF("Manufacturer url fails length requirements."));
1523 //-----------------------------------------------------------------------------
1525 //-----------------------------------------------------------------------------
1527 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1530 !raInfo->username ||
1531 !raInfo->hostname ||
1532 !raInfo->xmpp_domain)
1535 return OC_STACK_INVALID_PARAM;
1537 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1538 gRASetInfo = (result == OC_STACK_OK)? true : false;
1544 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1548 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1551 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1553 if(stackState == OC_STACK_INITIALIZED)
1555 OC_LOG(INFO, TAG, PCF("Subsequent calls to OCInit() without calling \
1556 OCStop() between them are ignored."));
1563 OC_LOG(ERROR, TAG, PCF("Need to call OCSetRAInfo before calling OCInit"));
1564 return OC_STACK_ERROR;
1568 OCStackResult result = OC_STACK_ERROR;
1569 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1572 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)))
1574 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1575 return OC_STACK_ERROR;
1579 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER)
1581 caglobals.client = true;
1583 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER)
1585 caglobals.server = true;
1588 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1589 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
1591 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
1593 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
1594 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
1596 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
1599 defaultDeviceHandler = NULL;
1600 defaultDeviceHandlerCallbackParameter = NULL;
1603 result = CAResultToOCResult(CAInitialize());
1604 VERIFY_SUCCESS(result, OC_STACK_OK);
1606 result = CAResultToOCResult(OCSelectNetwork());
1607 VERIFY_SUCCESS(result, OC_STACK_OK);
1609 switch (myStackMode)
1612 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1613 result = CAResultToOCResult(CAStartDiscoveryServer());
1614 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1617 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1618 result = CAResultToOCResult(CAStartListeningServer());
1619 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1621 case OC_CLIENT_SERVER:
1622 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1623 result = CAResultToOCResult(CAStartListeningServer());
1624 if(result == OC_STACK_OK)
1626 result = CAResultToOCResult(CAStartDiscoveryServer());
1630 VERIFY_SUCCESS(result, OC_STACK_OK);
1632 #ifdef WITH_PRESENCE
1633 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
1634 #endif // WITH_PRESENCE
1636 //Update Stack state to initialized
1637 stackState = OC_STACK_INITIALIZED;
1639 // Initialize resource
1640 if(myStackMode != OC_CLIENT)
1642 result = initResources();
1645 // Initialize the SRM Policy Engine
1646 if(result == OC_STACK_OK)
1648 result = SRMInitPolicyEngine();
1649 // TODO after BeachHead delivery: consolidate into single SRMInit()
1653 if(result != OC_STACK_OK)
1655 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1656 deleteAllResources();
1658 stackState = OC_STACK_UNINITIALIZED;
1663 OCStackResult OCStop()
1665 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1667 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1669 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1672 else if (stackState != OC_STACK_INITIALIZED)
1674 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1675 return OC_STACK_ERROR;
1678 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1680 #ifdef WITH_PRESENCE
1681 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1682 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1683 presenceResource.presenceTTL = 0;
1684 #endif // WITH_PRESENCE
1686 // Free memory dynamically allocated for resources
1687 deleteAllResources();
1689 DeletePlatformInfo();
1691 // Remove all observers
1692 DeleteObserverList();
1693 // Remove all the client callbacks
1694 DeleteClientCBList();
1696 // De-init the SRM Policy Engine
1697 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
1698 SRMDeInitPolicyEngine();
1701 stackState = OC_STACK_UNINITIALIZED;
1705 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1710 return CA_MSG_CONFIRM;
1715 return CA_MSG_NONCONFIRM;
1719 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1723 query = strchr (inputUri, '?');
1727 if((query - inputUri) > MAX_URI_LENGTH)
1729 return OC_STACK_INVALID_URI;
1732 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1734 return OC_STACK_INVALID_QUERY;
1737 else if(uriLen > MAX_URI_LENGTH)
1739 return OC_STACK_INVALID_URI;
1745 * A request uri consists of the following components in order:
1747 * optional prefix "coap://"
1749 * IPv6 address "[1234::5678]"
1750 * IPv4 address "192.168.1.1"
1751 * optional port ":5683"
1752 * resource uri "/oc/core..."
1754 * for PRESENCE requests, extract resource type.
1756 static OCStackResult ParseRequestUri(const char *fullUri,
1757 OCTransportAdapter adapter,
1758 OCTransportFlags flags,
1759 OCDevAddr **devAddr,
1761 char **resourceType)
1763 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
1765 OCStackResult result = OC_STACK_OK;
1766 OCDevAddr *da = NULL;
1770 // provide defaults for all returned values
1777 *resourceUri = NULL;
1781 *resourceType = NULL;
1784 // delimit url prefix, if any
1785 const char *start = fullUri;
1786 char *slash2 = strstr(start, "//");
1791 char *slash = strchr(start, '/');
1794 return OC_STACK_INVALID_URI;
1797 // processs url prefix, if any
1798 size_t urlLen = slash - start;
1802 if (urlLen && devAddr)
1803 { // construct OCDevAddr
1804 if (start[0] == '[')
1806 char *close = strchr(++start, ']');
1807 if (!close || close > slash)
1809 return OC_STACK_INVALID_URI;
1812 if (close[1] == ':')
1816 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
1817 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
1821 char *dot = strchr(start, '.');
1822 if (dot && dot < slash)
1824 colon = strchr(start, ':');
1825 end = (colon && colon < slash) ? colon : slash;
1826 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
1827 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
1835 if (len >= sizeof(da->addr))
1837 return OC_STACK_INVALID_URI;
1839 // collect port, if any
1840 if (colon && colon < slash)
1842 for (colon++; colon < slash; colon++)
1845 if (c < '0' || c > '9')
1847 return OC_STACK_INVALID_URI;
1849 port = 10 * port + c - '0';
1854 if (len >= sizeof(da->addr))
1856 return OC_STACK_INVALID_URI;
1859 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
1862 return OC_STACK_NO_MEMORY;
1864 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
1866 da->adapter = adapter;
1868 if (!strncmp(fullUri, "coaps:", 6))
1870 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
1875 // process resource uri, if any
1877 { // request uri and query
1878 size_t ulen = strlen(slash); // resource uri length
1879 size_t tlen = 0; // resource type length
1882 static const char strPresence[] = "/oic/ad?rt=";
1883 static const size_t lenPresence = sizeof(strPresence) - 1;
1884 if (!strncmp(slash, strPresence, lenPresence))
1886 type = slash + lenPresence;
1887 tlen = ulen - lenPresence;
1892 *resourceUri = (char *)OICMalloc(ulen + 1);
1895 result = OC_STACK_NO_MEMORY;
1898 strcpy(*resourceUri, slash);
1901 if (type && resourceType)
1903 *resourceType = (char *)OICMalloc(tlen + 1);
1906 result = OC_STACK_NO_MEMORY;
1910 OICStrcpy(*resourceType, (tlen+1), type);
1917 // free all returned values
1924 OICFree(*resourceUri);
1928 OICFree(*resourceType);
1933 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
1934 char *resourceUri, char **requestUri)
1936 char uri[CA_MAX_URI_LENGTH];
1938 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
1940 *requestUri = OICStrdup(uri);
1943 return OC_STACK_NO_MEMORY;
1950 * Discover or Perform requests on a specified resource
1952 OCStackResult OCDoResource(OCDoHandle *handle,
1954 const char *requestUri,
1955 const OCDevAddr *destination,
1957 OCConnectivityType connectivityType,
1958 OCQualityOfService qos,
1959 OCCallbackData *cbData,
1960 OCHeaderOption *options,
1963 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1965 // Validate input parameters
1966 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1967 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1968 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
1970 OCStackResult result = OC_STACK_ERROR;
1971 CAResult_t caResult;
1972 CAToken_t token = NULL;
1973 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
1974 ClientCB *clientCB = NULL;
1975 OCDoHandle resHandle = NULL;
1976 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
1977 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
1979 OCTransportAdapter adapter;
1980 OCTransportFlags flags;
1981 // the request contents are put here
1982 CARequestInfo_t requestInfo = {.method = CA_GET};
1983 // requestUri will be parsed into the following three variables
1984 OCDevAddr *devAddr = NULL;
1985 char *resourceUri = NULL;
1986 char *resourceType = NULL;
1988 // To track if memory is allocated for additional header options
1989 uint8_t hdrOptionMemAlloc = 0;
1991 // This validation is broken, but doesn't cause harm
1992 size_t uriLen = strlen(requestUri );
1993 if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
1999 * Support original behavior with address on resourceUri argument.
2001 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2002 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2004 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2006 if (result != OC_STACK_OK)
2008 OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2015 case OC_REST_OBSERVE:
2016 case OC_REST_OBSERVE_ALL:
2017 case OC_REST_CANCEL_OBSERVE:
2018 requestInfo.method = CA_GET;
2021 requestInfo.method = CA_PUT;
2024 requestInfo.method = CA_POST;
2026 case OC_REST_DELETE:
2027 requestInfo.method = CA_DELETE;
2029 case OC_REST_DISCOVER:
2031 if (destination || devAddr)
2033 requestInfo.isMulticast = false;
2037 tmpDevAddr.adapter = adapter;
2038 tmpDevAddr.flags = flags;
2039 destination = &tmpDevAddr;
2040 requestInfo.isMulticast = true;
2042 // CA_DISCOVER will become GET and isMulticast
2043 requestInfo.method = CA_GET;
2045 #ifdef WITH_PRESENCE
2046 case OC_REST_PRESENCE:
2047 // Replacing method type with GET because "presence"
2048 // is a stack layer only implementation.
2049 requestInfo.method = CA_GET;
2053 result = OC_STACK_INVALID_METHOD;
2057 if (!devAddr && !destination)
2059 OC_LOG_V(DEBUG, TAG, "no devAddr and no destination");
2060 result = OC_STACK_INVALID_PARAM;
2064 /* If not original behavior, use destination argument */
2065 if (destination && !devAddr)
2067 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2070 result = OC_STACK_NO_MEMORY;
2073 *devAddr = *destination;
2076 resHandle = GenerateInvocationHandle();
2079 result = OC_STACK_NO_MEMORY;
2083 caResult = CAGenerateToken(&token, tokenLength);
2084 if (caResult != CA_STATUS_OK)
2086 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2087 result= OC_STACK_ERROR;
2091 // fill in request data
2092 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2093 requestInfo.info.token = token;
2094 requestInfo.info.tokenLength = tokenLength;
2095 requestInfo.info.resourceUri = resourceUri;
2097 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2099 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2100 options, numOptions, OC_OBSERVE_REGISTER);
2101 if (result != OC_STACK_OK)
2105 hdrOptionMemAlloc = 1;
2106 requestInfo.info.numOptions = numOptions + 1;
2110 requestInfo.info.options = (CAHeaderOption_t*)options;
2111 requestInfo.info.numOptions = numOptions;
2114 CopyDevAddrToEndpoint(devAddr, &endpoint);
2119 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2122 OC_LOG(ERROR, TAG, PCF("Failed to create CBOR Payload"));
2128 requestInfo.info.payload = NULL;
2129 requestInfo.info.payloadSize = 0;
2132 if (result != OC_STACK_OK)
2134 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2138 // prepare for response
2139 #ifdef WITH_PRESENCE
2140 if (method == OC_REST_PRESENCE)
2142 char *presenceUri = NULL;
2143 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2144 if (OC_STACK_OK != result)
2149 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2150 // Presence notification will form a canonical uri to
2151 // look for callbacks into the application.
2152 resourceUri = presenceUri;
2156 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2157 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2158 method, devAddr, resourceUri, resourceType, ttl);
2159 if (OC_STACK_OK != result)
2164 devAddr = NULL; // Client CB list entry now owns it
2165 resourceUri = NULL; // Client CB list entry now owns it
2166 resourceType = NULL; // Client CB list entry now owns it
2169 caResult = CASendRequest(&endpoint, &requestInfo);
2170 if (caResult != CA_STATUS_OK)
2172 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
2173 result = OC_STACK_COMM_ERROR;
2179 *handle = resHandle;
2183 if (result != OC_STACK_OK)
2185 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
2186 FindAndDeleteClientCB(clientCB);
2187 CADestroyToken(token);
2195 // This is the owner of the payload object, so we free it
2196 OCPayloadDestroy(payload);
2197 OICFree(requestInfo.info.payload);
2199 OICFree(resourceUri);
2200 OICFree(resourceType);
2201 if (hdrOptionMemAlloc)
2203 OICFree(requestInfo.info.options);
2208 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2212 * This ftn is implemented one of two ways in the case of observation:
2214 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2215 * Remove the callback associated on client side.
2216 * When the next notification comes in from server,
2217 * reply with RESET message to server.
2218 * Keep in mind that the server will react to RESET only
2219 * if the last notification was sent as CON
2221 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2222 * and it is associated with an observe request
2223 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2224 * Send CON Observe request to server with
2225 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2226 * Remove the callback associated on client side.
2228 OCStackResult ret = OC_STACK_OK;
2229 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2230 CAResult_t caResult;
2231 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2232 CARequestInfo_t requestInfo = {.method = CA_GET};
2236 return OC_STACK_INVALID_PARAM;
2239 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2242 OC_LOG(ERROR, TAG, PCF("Client callback not found. Called OCCancel twice?"));
2246 switch (clientCB->method)
2248 case OC_REST_OBSERVE:
2249 case OC_REST_OBSERVE_ALL:
2250 OC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
2251 clientCB->requestUri);
2252 if (qos != OC_HIGH_QOS)
2254 FindAndDeleteClientCB(clientCB);
2259 OC_LOG(INFO, TAG, PCF("Cancelling observation as CONFIRMABLE"));
2262 requestData.type = qualityOfServiceToMessageType(qos);
2263 requestData.token = clientCB->token;
2264 requestData.tokenLength = clientCB->tokenLength;
2265 if (CreateObserveHeaderOption (&(requestData.options),
2266 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2268 return OC_STACK_ERROR;
2270 requestData.numOptions = numOptions + 1;
2271 requestData.resourceUri = OICStrdup (clientCB->requestUri);
2273 requestInfo.method = CA_GET;
2274 requestInfo.info = requestData;
2276 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2279 caResult = CASendRequest(&endpoint, &requestInfo);
2280 if (caResult != CA_STATUS_OK)
2282 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2283 ret = OC_STACK_ERROR;
2285 ret = CAResultToOCResult (caResult);
2288 #ifdef WITH_PRESENCE
2289 case OC_REST_PRESENCE:
2290 FindAndDeleteClientCB(clientCB);
2295 ret = OC_STACK_INVALID_METHOD;
2300 if (requestData.numOptions > 0)
2302 OICFree(requestData.options);
2304 if (requestData.resourceUri)
2306 OICFree (requestData.resourceUri);
2312 * @brief Register Persistent storage callback.
2313 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2315 * OC_STACK_OK - No errors; Success
2316 * OC_STACK_INVALID_PARAM - Invalid parameter
2318 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2320 OC_LOG(INFO, TAG, PCF("RegisterPersistentStorageHandler !!"));
2321 if(!persistentStorageHandler)
2323 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2324 return OC_STACK_INVALID_PARAM;
2328 if( !persistentStorageHandler->open ||
2329 !persistentStorageHandler->close ||
2330 !persistentStorageHandler->read ||
2331 !persistentStorageHandler->unlink ||
2332 !persistentStorageHandler->write)
2334 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2335 return OC_STACK_INVALID_PARAM;
2338 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2341 #ifdef WITH_PRESENCE
2343 OCStackResult OCProcessPresence()
2345 OCStackResult result = OC_STACK_OK;
2347 // the following line floods the log with messages that are irrelevant
2348 // to most purposes. Uncomment as needed.
2349 //OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
2350 ClientCB* cbNode = NULL;
2351 OCClientResponse clientResponse;
2352 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2354 LL_FOREACH(cbList, cbNode)
2356 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2361 uint32_t now = GetTicks(0);
2362 OC_LOG_V(DEBUG, TAG, "this TTL level %d",
2363 cbNode->presence->TTLlevel);
2364 OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2366 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2371 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2373 OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2374 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2376 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2378 OC_LOG(DEBUG, TAG, PCF("No more timeout ticks"));
2380 clientResponse.sequenceNumber = 0;
2381 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2382 clientResponse.devAddr = *cbNode->devAddr;
2383 FixUpClientResponse(&clientResponse);
2384 clientResponse.payload = NULL;
2386 // Increment the TTLLevel (going to a next state), so we don't keep
2387 // sending presence notification to client.
2388 cbNode->presence->TTLlevel++;
2389 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2390 cbNode->presence->TTLlevel);
2392 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2393 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2395 FindAndDeleteClientCB(cbNode);
2399 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2404 CAResult_t caResult = CA_STATUS_OK;
2405 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2406 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2407 CARequestInfo_t requestInfo = {.method = CA_GET};
2409 OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
2411 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2413 requestData.type = CA_MSG_NONCONFIRM;
2414 requestData.token = cbNode->token;
2415 requestData.tokenLength = cbNode->tokenLength;
2416 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2417 requestInfo.method = CA_GET;
2418 requestInfo.info = requestData;
2420 caResult = CASendRequest(&endpoint, &requestInfo);
2422 if (caResult != CA_STATUS_OK)
2424 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2428 cbNode->presence->TTLlevel++;
2429 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2432 if (result != OC_STACK_OK)
2434 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2439 #endif // WITH_PRESENCE
2441 OCStackResult OCProcess()
2443 #ifdef WITH_PRESENCE
2444 OCProcessPresence();
2446 CAHandleRequestResponse();
2451 #ifdef WITH_PRESENCE
2452 OCStackResult OCStartPresence(const uint32_t ttl)
2454 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2455 OCChangeResourceProperty(
2456 &(((OCResource *)presenceResource.handle)->resourceProperties),
2459 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2461 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2462 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to max value"));
2466 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2467 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to default value"));
2471 presenceResource.presenceTTL = ttl;
2473 OC_LOG_V(DEBUG, TAG, "Presence TTL is %lu seconds", presenceResource.presenceTTL);
2475 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2477 presenceState = OC_PRESENCE_INITIALIZED;
2479 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2481 CAToken_t caToken = NULL;
2482 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2483 if (caResult != CA_STATUS_OK)
2485 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2486 CADestroyToken(caToken);
2487 return OC_STACK_ERROR;
2490 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2491 (OCResource *)presenceResource.handle, OC_LOW_QOS, &devAddr);
2492 CADestroyToken(caToken);
2495 // Each time OCStartPresence is called
2496 // a different random 32-bit integer number is used
2497 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2499 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2500 OC_PRESENCE_TRIGGER_CREATE);
2503 OCStackResult OCStopPresence()
2505 OCStackResult result = OC_STACK_ERROR;
2507 if(presenceResource.handle)
2509 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2511 // make resource inactive
2512 result = OCChangeResourceProperty(
2513 &(((OCResource *) presenceResource.handle)->resourceProperties),
2517 if(result != OC_STACK_OK)
2520 PCF("Changing the presence resource properties to ACTIVE not successful"));
2524 return SendStopNotification();
2528 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
2529 void* callbackParameter)
2531 defaultDeviceHandler = entityHandler;
2532 defaultDeviceHandlerCallbackParameter = callbackParameter;
2537 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
2539 OC_LOG(INFO, TAG, PCF("Entering OCSetPlatformInfo"));
2541 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
2543 if (validatePlatformInfo(platformInfo))
2545 return SavePlatformInfo(platformInfo);
2549 return OC_STACK_INVALID_PARAM;
2554 return OC_STACK_ERROR;
2558 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2560 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2562 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
2564 OC_LOG(ERROR, TAG, PCF("Null or empty device name."));
2565 return OC_STACK_INVALID_PARAM;
2568 return SaveDeviceInfo(deviceInfo);
2571 OCStackResult OCCreateResource(OCResourceHandle *handle,
2572 const char *resourceTypeName,
2573 const char *resourceInterfaceName,
2574 const char *uri, OCEntityHandler entityHandler,
2575 void* callbackParam,
2576 uint8_t resourceProperties)
2579 OCResource *pointer = NULL;
2581 OCStackResult result = OC_STACK_ERROR;
2583 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2585 if(myStackMode == OC_CLIENT)
2587 return OC_STACK_INVALID_PARAM;
2589 // Validate parameters
2590 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2592 OC_LOG(ERROR, TAG, PCF("URI is empty or too long"));
2593 return OC_STACK_INVALID_URI;
2595 // Is it presented during resource discovery?
2596 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
2598 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2599 return OC_STACK_INVALID_PARAM;
2602 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2604 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2607 // Make sure resourceProperties bitmask has allowed properties specified
2608 if (resourceProperties
2609 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
2610 OC_EXPLICIT_DISCOVERABLE))
2612 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2613 return OC_STACK_INVALID_PARAM;
2616 // If the headResource is NULL, then no resources have been created...
2617 pointer = headResource;
2620 // At least one resources is in the resource list, so we need to search for
2621 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2624 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
2626 OC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
2627 return OC_STACK_INVALID_PARAM;
2629 pointer = pointer->next;
2632 // Create the pointer and insert it into the resource list
2633 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
2636 result = OC_STACK_NO_MEMORY;
2639 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2641 insertResource(pointer);
2644 str = OICStrdup(uri);
2647 result = OC_STACK_NO_MEMORY;
2652 // Set properties. Set OC_ACTIVE
2653 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2656 // Add the resourcetype to the resource
2657 result = BindResourceTypeToResource(pointer, resourceTypeName);
2658 if (result != OC_STACK_OK)
2660 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2664 // Add the resourceinterface to the resource
2665 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2666 if (result != OC_STACK_OK)
2668 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2672 // If an entity handler has been passed, attach it to the newly created
2673 // resource. Otherwise, set the default entity handler.
2676 pointer->entityHandler = entityHandler;
2677 pointer->entityHandlerCallbackParam = callbackParam;
2681 pointer->entityHandler = defaultResourceEHandler;
2682 pointer->entityHandlerCallbackParam = NULL;
2686 result = OC_STACK_OK;
2688 #ifdef WITH_PRESENCE
2689 if(presenceResource.handle)
2691 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2692 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
2696 if (result != OC_STACK_OK)
2698 // Deep delete of resource and other dynamic elements that it contains
2699 deleteResource(pointer);
2706 OCStackResult OCBindResource(
2707 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2709 OCResource *resource = NULL;
2712 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2714 // Validate parameters
2715 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2716 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2717 // Container cannot contain itself
2718 if (collectionHandle == resourceHandle)
2720 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2721 return OC_STACK_INVALID_PARAM;
2724 // Use the handle to find the resource in the resource linked list
2725 resource = findResource((OCResource *) collectionHandle);
2728 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2729 return OC_STACK_INVALID_PARAM;
2732 // Look for an open slot to add add the child resource.
2733 // If found, add it and return success
2734 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2736 if (!resource->rsrcResources[i])
2738 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2739 OC_LOG(INFO, TAG, PCF("resource bound"));
2741 #ifdef WITH_PRESENCE
2742 if(presenceResource.handle)
2744 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2745 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2746 OC_PRESENCE_TRIGGER_CHANGE);
2754 // Unable to add resourceHandle, so return error
2755 return OC_STACK_ERROR;
2758 OCStackResult OCUnBindResource(
2759 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2761 OCResource *resource = NULL;
2764 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2766 // Validate parameters
2767 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2768 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2769 // Container cannot contain itself
2770 if (collectionHandle == resourceHandle)
2772 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2773 return OC_STACK_INVALID_PARAM;
2776 // Use the handle to find the resource in the resource linked list
2777 resource = findResource((OCResource *) collectionHandle);
2780 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2781 return OC_STACK_INVALID_PARAM;
2784 // Look for an open slot to add add the child resource.
2785 // If found, add it and return success
2786 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2788 if (resourceHandle == resource->rsrcResources[i])
2790 resource->rsrcResources[i] = (OCResource *) NULL;
2791 OC_LOG(INFO, TAG, PCF("resource unbound"));
2793 // Send notification when resource is unbounded successfully.
2794 #ifdef WITH_PRESENCE
2795 if(presenceResource.handle)
2797 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2798 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2799 OC_PRESENCE_TRIGGER_CHANGE);
2806 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2808 // Unable to add resourceHandle, so return error
2809 return OC_STACK_ERROR;
2812 OCStackResult BindResourceTypeToResource(OCResource* resource,
2813 const char *resourceTypeName)
2815 OCResourceType *pointer = NULL;
2817 OCStackResult result = OC_STACK_ERROR;
2819 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2821 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
2824 result = OC_STACK_NO_MEMORY;
2828 str = OICStrdup(resourceTypeName);
2831 result = OC_STACK_NO_MEMORY;
2834 pointer->resourcetypename = str;
2836 insertResourceType(resource, pointer);
2837 result = OC_STACK_OK;
2840 if (result != OC_STACK_OK)
2849 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2850 const char *resourceInterfaceName)
2852 OCResourceInterface *pointer = NULL;
2854 OCStackResult result = OC_STACK_ERROR;
2856 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2858 OC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
2860 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
2863 result = OC_STACK_NO_MEMORY;
2867 str = OICStrdup(resourceInterfaceName);
2870 result = OC_STACK_NO_MEMORY;
2873 pointer->name = str;
2875 // Bind the resourceinterface to the resource
2876 insertResourceInterface(resource, pointer);
2878 result = OC_STACK_OK;
2881 if (result != OC_STACK_OK)
2890 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2891 const char *resourceTypeName)
2894 OCStackResult result = OC_STACK_ERROR;
2895 OCResource *resource = NULL;
2897 resource = findResource((OCResource *) handle);
2900 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2901 return OC_STACK_ERROR;
2904 result = BindResourceTypeToResource(resource, resourceTypeName);
2906 #ifdef WITH_PRESENCE
2907 if(presenceResource.handle)
2909 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2910 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2917 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2918 const char *resourceInterfaceName)
2921 OCStackResult result = OC_STACK_ERROR;
2922 OCResource *resource = NULL;
2924 resource = findResource((OCResource *) handle);
2927 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2928 return OC_STACK_ERROR;
2931 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2933 #ifdef WITH_PRESENCE
2934 if(presenceResource.handle)
2936 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2937 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2944 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
2946 OCResource *pointer = headResource;
2948 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2952 *numResources = *numResources + 1;
2953 pointer = pointer->next;
2958 OCResourceHandle OCGetResourceHandle(uint8_t index)
2960 OCResource *pointer = headResource;
2962 for( uint8_t i = 0; i < index && pointer; ++i)
2964 pointer = pointer->next;
2966 return (OCResourceHandle) pointer;
2969 OCStackResult OCDeleteResource(OCResourceHandle handle)
2973 OC_LOG(ERROR, TAG, PCF("Invalid handle for deletion"));
2974 return OC_STACK_INVALID_PARAM;
2977 OCResource *resource = findResource((OCResource *) handle);
2978 if (resource == NULL)
2980 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2981 return OC_STACK_NO_RESOURCE;
2984 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
2986 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2987 return OC_STACK_ERROR;
2993 const char *OCGetResourceUri(OCResourceHandle handle)
2995 OCResource *resource = NULL;
2997 resource = findResource((OCResource *) handle);
3000 return resource->uri;
3002 return (const char *) NULL;
3005 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3007 OCResource *resource = NULL;
3009 resource = findResource((OCResource *) handle);
3012 return resource->resourceProperties;
3014 return (OCResourceProperty)-1;
3017 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3018 uint8_t *numResourceTypes)
3020 OCResource *resource = NULL;
3021 OCResourceType *pointer = NULL;
3023 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3024 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3026 *numResourceTypes = 0;
3028 resource = findResource((OCResource *) handle);
3031 pointer = resource->rsrcType;
3034 *numResourceTypes = *numResourceTypes + 1;
3035 pointer = pointer->next;
3041 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3043 OCResourceType *resourceType = NULL;
3045 resourceType = findResourceTypeAtIndex(handle, index);
3048 return resourceType->resourcetypename;
3050 return (const char *) NULL;
3053 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3054 uint8_t *numResourceInterfaces)
3056 OCResourceInterface *pointer = NULL;
3057 OCResource *resource = NULL;
3059 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3060 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3062 *numResourceInterfaces = 0;
3063 resource = findResource((OCResource *) handle);
3066 pointer = resource->rsrcInterface;
3069 *numResourceInterfaces = *numResourceInterfaces + 1;
3070 pointer = pointer->next;
3076 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3078 OCResourceInterface *resourceInterface = NULL;
3080 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3081 if (resourceInterface)
3083 return resourceInterface->name;
3085 return (const char *) NULL;
3088 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3091 OCResource *resource = NULL;
3093 if (index >= MAX_CONTAINED_RESOURCES)
3098 resource = findResource((OCResource *) collectionHandle);
3104 return resource->rsrcResources[index];
3107 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3108 OCEntityHandler entityHandler,
3109 void* callbackParam)
3111 OCResource *resource = NULL;
3113 // Validate parameters
3114 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3116 // Use the handle to find the resource in the resource linked list
3117 resource = findResource((OCResource *)handle);
3120 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3121 return OC_STACK_ERROR;
3125 resource->entityHandler = entityHandler;
3126 resource->entityHandlerCallbackParam = callbackParam;
3128 #ifdef WITH_PRESENCE
3129 if(presenceResource.handle)
3131 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3132 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3139 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3141 OCResource *resource = NULL;
3143 resource = findResource((OCResource *)handle);
3146 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3151 return resource->entityHandler;
3154 void incrementSequenceNumber(OCResource * resPtr)
3156 // Increment the sequence number
3157 resPtr->sequenceNum += 1;
3158 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3160 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3165 #ifdef WITH_PRESENCE
3166 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3167 OCPresenceTrigger trigger)
3169 OCResource *resPtr = NULL;
3170 OCStackResult result = OC_STACK_ERROR;
3171 OCMethod method = OC_REST_PRESENCE;
3172 uint32_t maxAge = 0;
3173 resPtr = findResource((OCResource *) presenceResource.handle);
3176 return OC_STACK_NO_RESOURCE;
3179 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3181 maxAge = presenceResource.presenceTTL;
3183 result = SendAllObserverNotification(method, resPtr, maxAge,
3184 trigger, resourceType, OC_LOW_QOS);
3190 OCStackResult SendStopNotification()
3192 OCResource *resPtr = NULL;
3193 OCStackResult result = OC_STACK_ERROR;
3194 OCMethod method = OC_REST_PRESENCE;
3195 resPtr = findResource((OCResource *) presenceResource.handle);
3198 return OC_STACK_NO_RESOURCE;
3201 // maxAge is 0. ResourceType is NULL.
3202 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3208 #endif // WITH_PRESENCE
3209 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3211 OCResource *resPtr = NULL;
3212 OCStackResult result = OC_STACK_ERROR;
3213 OCMethod method = OC_REST_NOMETHOD;
3214 uint32_t maxAge = 0;
3216 OC_LOG(INFO, TAG, PCF("Notifying all observers"));
3217 #ifdef WITH_PRESENCE
3218 if(handle == presenceResource.handle)
3222 #endif // WITH_PRESENCE
3223 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3225 // Verify that the resource exists
3226 resPtr = findResource ((OCResource *) handle);
3229 return OC_STACK_NO_RESOURCE;
3233 //only increment in the case of regular observing (not presence)
3234 incrementSequenceNumber(resPtr);
3235 method = OC_REST_OBSERVE;
3236 maxAge = MAX_OBSERVE_AGE;
3237 #ifdef WITH_PRESENCE
3238 result = SendAllObserverNotification (method, resPtr, maxAge,
3239 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3241 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3248 OCNotifyListOfObservers (OCResourceHandle handle,
3249 OCObservationId *obsIdList,
3250 uint8_t numberOfIds,
3251 const OCRepPayload *payload,
3252 OCQualityOfService qos)
3254 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3256 OCResource *resPtr = NULL;
3257 //TODO: we should allow the server to define this
3258 uint32_t maxAge = MAX_OBSERVE_AGE;
3260 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3261 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3262 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3264 resPtr = findResource ((OCResource *) handle);
3265 if (NULL == resPtr || myStackMode == OC_CLIENT)
3267 return OC_STACK_NO_RESOURCE;
3271 incrementSequenceNumber(resPtr);
3273 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3274 payload, maxAge, qos));
3277 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3279 OCStackResult result = OC_STACK_ERROR;
3280 OCServerRequest *serverRequest = NULL;
3282 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3284 // Validate input parameters
3285 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3286 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3289 // Get pointer to request info
3290 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3293 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3294 result = serverRequest->ehResponseHandler(ehResponse);
3300 //-----------------------------------------------------------------------------
3301 // Private internal function definitions
3302 //-----------------------------------------------------------------------------
3303 static OCDoHandle GenerateInvocationHandle()
3305 OCDoHandle handle = NULL;
3306 // Generate token here, it will be deleted when the transaction is deleted
3307 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3310 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3316 #ifdef WITH_PRESENCE
3317 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3318 OCResourceProperty resourceProperties, uint8_t enable)
3322 return OC_STACK_INVALID_PARAM;
3324 if (resourceProperties
3325 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3327 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3328 return OC_STACK_INVALID_PARAM;
3332 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3336 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3342 OCStackResult initResources()
3344 OCStackResult result = OC_STACK_OK;
3346 headResource = NULL;
3347 tailResource = NULL;
3348 // Init Virtual Resources
3349 #ifdef WITH_PRESENCE
3350 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3352 result = OCCreateResource(&presenceResource.handle,
3353 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3355 OC_RSRVD_PRESENCE_URI,
3359 //make resource inactive
3360 result = OCChangeResourceProperty(
3361 &(((OCResource *) presenceResource.handle)->resourceProperties),
3365 if (result == OC_STACK_OK)
3367 result = SRMInitSecureResources();
3373 void insertResource(OCResource *resource)
3377 headResource = resource;
3378 tailResource = resource;
3382 tailResource->next = resource;
3383 tailResource = resource;
3385 resource->next = NULL;
3388 OCResource *findResource(OCResource *resource)
3390 OCResource *pointer = headResource;
3394 if (pointer == resource)
3398 pointer = pointer->next;
3403 void deleteAllResources()
3405 OCResource *pointer = headResource;
3406 OCResource *temp = NULL;
3410 temp = pointer->next;
3411 #ifdef WITH_PRESENCE
3412 if(pointer != (OCResource *) presenceResource.handle)
3414 #endif // WITH_PRESENCE
3415 deleteResource(pointer);
3416 #ifdef WITH_PRESENCE
3418 #endif // WITH_PRESENCE
3422 SRMDeInitSecureResources();
3424 #ifdef WITH_PRESENCE
3425 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3426 // presence notification attributed to their deletion to be processed.
3427 deleteResource((OCResource *) presenceResource.handle);
3428 #endif // WITH_PRESENCE
3431 OCStackResult deleteResource(OCResource *resource)
3433 OCResource *prev = NULL;
3434 OCResource *temp = NULL;
3437 OC_LOG_V(DEBUG,TAG,"resource is NULL");
3438 return OC_STACK_INVALID_PARAM;
3441 OC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
3443 temp = headResource;
3446 if (temp == resource)
3448 // Invalidate all Resource Properties.
3449 resource->resourceProperties = (OCResourceProperty) 0;
3450 #ifdef WITH_PRESENCE
3451 if(resource != (OCResource *) presenceResource.handle)
3453 #endif // WITH_PRESENCE
3454 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3455 #ifdef WITH_PRESENCE
3458 if(presenceResource.handle)
3460 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3461 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
3464 // Only resource in list.
3465 if (temp == headResource && temp == tailResource)
3467 headResource = NULL;
3468 tailResource = NULL;
3471 else if (temp == headResource)
3473 headResource = temp->next;
3476 else if (temp == tailResource)
3478 tailResource = prev;
3479 tailResource->next = NULL;
3483 prev->next = temp->next;
3486 deleteResourceElements(temp);
3497 return OC_STACK_ERROR;
3500 void deleteResourceElements(OCResource *resource)
3507 OICFree(resource->uri);
3508 deleteResourceType(resource->rsrcType);
3509 deleteResourceInterface(resource->rsrcInterface);
3512 void deleteResourceType(OCResourceType *resourceType)
3514 OCResourceType *pointer = resourceType;
3515 OCResourceType *next = NULL;
3519 next = pointer->next;
3520 OICFree(pointer->resourcetypename);
3526 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3528 OCResourceInterface *pointer = resourceInterface;
3529 OCResourceInterface *next = NULL;
3533 next = pointer->next;
3534 OICFree(pointer->name);
3540 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3542 OCResourceType *pointer = NULL;
3543 OCResourceType *previous = NULL;
3544 if (!resource || !resourceType)
3548 // resource type list is empty.
3549 else if (!resource->rsrcType)
3551 resource->rsrcType = resourceType;
3555 pointer = resource->rsrcType;
3559 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
3561 OC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
3562 OICFree(resourceType->resourcetypename);
3563 OICFree(resourceType);
3567 pointer = pointer->next;
3569 previous->next = resourceType;
3571 resourceType->next = NULL;
3573 OC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
3576 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3578 OCResource *resource = NULL;
3579 OCResourceType *pointer = NULL;
3581 // Find the specified resource
3582 resource = findResource((OCResource *) handle);
3588 // Make sure a resource has a resourcetype
3589 if (!resource->rsrcType)
3594 // Iterate through the list
3595 pointer = resource->rsrcType;
3596 for(uint8_t i = 0; i< index && pointer; ++i)
3598 pointer = pointer->next;
3603 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3605 if(resourceTypeList && resourceTypeName)
3607 OCResourceType * rtPointer = resourceTypeList;
3608 while(resourceTypeName && rtPointer)
3610 if(rtPointer->resourcetypename &&
3611 strcmp(resourceTypeName, (const char *)
3612 (rtPointer->resourcetypename)) == 0)
3616 rtPointer = rtPointer->next;
3624 * Insert a new interface into interface linked list only if not already present.
3625 * If alredy present, 2nd arg is free'd.
3626 * Default interface will always be first if present.
3628 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
3630 OCResourceInterface *pointer = NULL;
3631 OCResourceInterface *previous = NULL;
3633 newInterface->next = NULL;
3635 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
3637 if (!*firstInterface)
3639 *firstInterface = newInterface;
3641 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3643 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3645 OICFree(newInterface->name);
3646 OICFree(newInterface);
3651 newInterface->next = *firstInterface;
3652 *firstInterface = newInterface;
3657 pointer = *firstInterface;
3660 if (strcmp(newInterface->name, pointer->name) == 0)
3662 OICFree(newInterface->name);
3663 OICFree(newInterface);
3667 pointer = pointer->next;
3669 previous->next = newInterface;
3673 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3676 OCResource *resource = NULL;
3677 OCResourceInterface *pointer = NULL;
3679 // Find the specified resource
3680 resource = findResource((OCResource *) handle);
3686 // Make sure a resource has a resourceinterface
3687 if (!resource->rsrcInterface)
3692 // Iterate through the list
3693 pointer = resource->rsrcInterface;
3695 for (uint8_t i = 0; i < index && pointer; ++i)
3697 pointer = pointer->next;
3703 * This function splits the uri using the '?' delimiter.
3704 * "uriWithoutQuery" is the block of characters between the beginning
3705 * till the delimiter or '\0' which ever comes first.
3706 * "query" is whatever is to the right of the delimiter if present.
3707 * No delimiter sets the query to NULL.
3708 * If either are present, they will be malloc'ed into the params 2, 3.
3709 * The first param, *uri is left untouched.
3711 * NOTE: This function does not account for whitespace at the end of the uri NOR
3712 * malformed uri's with '??'. Whitespace at the end will be assumed to be
3713 * part of the query.
3715 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
3719 return OC_STACK_INVALID_URI;
3721 if(!query || !uriWithoutQuery)
3723 return OC_STACK_INVALID_PARAM;
3727 *uriWithoutQuery = NULL;
3729 size_t uriWithoutQueryLen = 0;
3730 size_t queryLen = 0;
3731 size_t uriLen = strlen(uri);
3733 char *pointerToDelimiter = strstr(uri, "?");
3735 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
3736 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
3738 if (uriWithoutQueryLen)
3740 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
3741 if (!*uriWithoutQuery)
3745 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
3749 *query = (char *) OICCalloc(queryLen + 1, 1);
3752 OICFree(*uriWithoutQuery);
3753 *uriWithoutQuery = NULL;
3756 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
3762 return OC_STACK_NO_MEMORY;
3765 const uint8_t* OCGetServerInstanceID(void)
3767 static bool generated = false;
3768 static ServerID sid;
3774 if (OCGenerateUuid(sid) != RAND_UUID_OK)
3776 OC_LOG(FATAL, TAG, PCF("Generate UUID for Server Instance failed!"));
3783 const char* OCGetServerInstanceIDString(void)
3785 static bool generated = false;
3786 static char sidStr[UUID_STRING_SIZE];
3793 const uint8_t* sid = OCGetServerInstanceID();
3795 if(OCConvertUuidToString(sid, sidStr) != RAND_UUID_OK)
3797 OC_LOG(FATAL, TAG, PCF("Generate UUID String for Server Instance failed!"));
3805 CAResult_t OCSelectNetwork()
3807 CAResult_t retResult = CA_STATUS_FAILED;
3808 CAResult_t caResult = CA_STATUS_OK;
3810 CATransportAdapter_t connTypes[] = {
3812 CA_ADAPTER_RFCOMM_BTEDR,
3813 CA_ADAPTER_GATT_BTLE
3816 ,CA_ADAPTER_REMOTE_ACCESS
3819 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
3821 for(int i = 0; i<numConnTypes; i++)
3823 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
3824 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
3826 caResult = CASelectNetwork(connTypes[i]);
3827 if(caResult == CA_STATUS_OK)
3829 retResult = CA_STATUS_OK;
3834 if(retResult != CA_STATUS_OK)
3836 return caResult; // Returns error of appropriate transport that failed fatally.
3842 OCStackResult CAResultToOCResult(CAResult_t caResult)
3848 case CA_STATUS_INVALID_PARAM:
3849 return OC_STACK_INVALID_PARAM;
3850 case CA_ADAPTER_NOT_ENABLED:
3851 return OC_STACK_ADAPTER_NOT_ENABLED;
3852 case CA_SERVER_STARTED_ALREADY:
3854 case CA_SERVER_NOT_STARTED:
3855 return OC_STACK_ERROR;
3856 case CA_DESTINATION_NOT_REACHABLE:
3857 return OC_STACK_COMM_ERROR;
3858 case CA_SOCKET_OPERATION_FAILED:
3859 return OC_STACK_COMM_ERROR;
3860 case CA_SEND_FAILED:
3861 return OC_STACK_COMM_ERROR;
3862 case CA_RECEIVE_FAILED:
3863 return OC_STACK_COMM_ERROR;
3864 case CA_MEMORY_ALLOC_FAILED:
3865 return OC_STACK_NO_MEMORY;
3866 case CA_REQUEST_TIMEOUT:
3867 return OC_STACK_TIMEOUT;
3868 case CA_DESTINATION_DISCONNECTED:
3869 return OC_STACK_COMM_ERROR;
3870 case CA_STATUS_FAILED:
3871 return OC_STACK_ERROR;
3872 case CA_NOT_SUPPORTED:
3873 return OC_STACK_NOTIMPL;
3875 return OC_STACK_ERROR;