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) && (0 < requestInfo->info.payloadSize))
1312 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1313 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1314 memcpy (serverRequest.payload, requestInfo->info.payload,
1315 requestInfo->info.payloadSize);
1319 serverRequest.reqTotalSize = 0;
1322 switch (requestInfo->method)
1325 serverRequest.method = OC_REST_GET;
1328 serverRequest.method = OC_REST_PUT;
1331 serverRequest.method = OC_REST_POST;
1334 serverRequest.method = OC_REST_DELETE;
1337 OC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1338 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1339 requestInfo->info.type, requestInfo->info.numOptions,
1340 requestInfo->info.options, requestInfo->info.token,
1341 requestInfo->info.tokenLength);
1342 OICFree(serverRequest.payload);
1346 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1347 requestInfo->info.tokenLength);
1348 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1349 serverRequest.tokenLength = requestInfo->info.tokenLength;
1351 if (!serverRequest.requestToken)
1353 OC_LOG(FATAL, TAG, "Allocation for token failed.");
1354 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1355 requestInfo->info.type, requestInfo->info.numOptions,
1356 requestInfo->info.options, requestInfo->info.token,
1357 requestInfo->info.tokenLength);
1358 OICFree(serverRequest.payload);
1361 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1363 if (requestInfo->info.type == CA_MSG_CONFIRM)
1365 serverRequest.qos = OC_HIGH_QOS;
1369 serverRequest.qos = OC_LOW_QOS;
1371 // CA does not need the following field
1372 // Are we sure CA does not need them? how is it responding to multicast
1373 serverRequest.delayedResNeeded = 0;
1375 serverRequest.coapID = requestInfo->info.messageId;
1377 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1379 // copy vendor specific header options
1380 uint8_t tempNum = (requestInfo->info.numOptions);
1381 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1382 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1385 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
1386 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1387 requestInfo->info.type, requestInfo->info.numOptions,
1388 requestInfo->info.options, requestInfo->info.token,
1389 requestInfo->info.tokenLength);
1390 OICFree(serverRequest.payload);
1391 OICFree(serverRequest.requestToken);
1394 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1395 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1397 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1398 sizeof(CAHeaderOption_t)*tempNum);
1401 requestResult = HandleStackRequests (&serverRequest);
1403 // Send ACK to client as precursor to slow response
1404 if(requestResult == OC_STACK_SLOW_RESOURCE)
1406 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1407 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0);
1409 else if(requestResult != OC_STACK_OK)
1411 OC_LOG_V(ERROR, TAG, PCF("HandleStackRequests failed. error: %d"), requestResult);
1413 CAResponseResult_t stackResponse = OCToCAStackResult(requestResult);
1415 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1416 requestInfo->info.type, requestInfo->info.numOptions,
1417 requestInfo->info.options, requestInfo->info.token,
1418 requestInfo->info.tokenLength);
1420 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1421 // The token is copied in there, and is thus still owned by this function.
1422 OICFree(serverRequest.payload);
1423 OICFree(serverRequest.requestToken);
1424 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
1427 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1429 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
1430 OCStackResult result = OC_STACK_ERROR;
1431 ResourceHandling resHandling;
1432 OCResource *resource;
1433 if(!protocolRequest)
1435 OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
1436 return OC_STACK_INVALID_PARAM;
1439 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1440 protocolRequest->tokenLength);
1443 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
1444 result = AddServerRequest(&request, protocolRequest->coapID,
1445 protocolRequest->delayedResNeeded, 0,
1446 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
1447 protocolRequest->observationOption, protocolRequest->qos,
1448 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1449 protocolRequest->payload, protocolRequest->requestToken,
1450 protocolRequest->tokenLength,
1451 protocolRequest->resourceUrl, protocolRequest->reqTotalSize,
1452 &protocolRequest->devAddr);
1453 if (OC_STACK_OK != result)
1455 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
1461 OC_LOG(ERROR, TAG, PCF("Out of Memory"));
1462 return OC_STACK_NO_MEMORY;
1465 if(!protocolRequest->reqMorePacket)
1467 request->requestComplete = 1;
1472 OC_LOG(INFO, TAG, PCF("This is either a repeated or blocked Server Request"));
1475 if(request->requestComplete)
1477 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
1478 result = DetermineResourceHandling (request, &resHandling, &resource);
1479 if (result == OC_STACK_OK)
1481 result = ProcessRequest(resHandling, resource, request);
1486 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
1487 result = OC_STACK_CONTINUE;
1492 bool validatePlatformInfo(OCPlatformInfo info)
1495 if (!info.platformID)
1497 OC_LOG(ERROR, TAG, PCF("No platform ID found."));
1501 if (info.manufacturerName)
1503 size_t lenManufacturerName = strlen(info.manufacturerName);
1505 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1507 OC_LOG(ERROR, TAG, PCF("Manufacturer name fails length requirements."));
1513 OC_LOG(ERROR, TAG, PCF("No manufacturer name present"));
1517 if (info.manufacturerUrl)
1519 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1521 OC_LOG(ERROR, TAG, PCF("Manufacturer url fails length requirements."));
1528 //-----------------------------------------------------------------------------
1530 //-----------------------------------------------------------------------------
1532 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1535 !raInfo->username ||
1536 !raInfo->hostname ||
1537 !raInfo->xmpp_domain)
1540 return OC_STACK_INVALID_PARAM;
1542 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1543 gRASetInfo = (result == OC_STACK_OK)? true : false;
1549 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1553 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1556 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1558 if(stackState == OC_STACK_INITIALIZED)
1560 OC_LOG(INFO, TAG, PCF("Subsequent calls to OCInit() without calling \
1561 OCStop() between them are ignored."));
1568 OC_LOG(ERROR, TAG, PCF("Need to call OCSetRAInfo before calling OCInit"));
1569 return OC_STACK_ERROR;
1573 OCStackResult result = OC_STACK_ERROR;
1574 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1577 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)))
1579 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1580 return OC_STACK_ERROR;
1584 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER)
1586 caglobals.client = true;
1588 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER)
1590 caglobals.server = true;
1593 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1594 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
1596 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
1598 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
1599 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
1601 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
1604 defaultDeviceHandler = NULL;
1605 defaultDeviceHandlerCallbackParameter = NULL;
1608 result = CAResultToOCResult(CAInitialize());
1609 VERIFY_SUCCESS(result, OC_STACK_OK);
1611 result = CAResultToOCResult(OCSelectNetwork());
1612 VERIFY_SUCCESS(result, OC_STACK_OK);
1614 switch (myStackMode)
1617 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1618 result = CAResultToOCResult(CAStartDiscoveryServer());
1619 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1622 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1623 result = CAResultToOCResult(CAStartListeningServer());
1624 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1626 case OC_CLIENT_SERVER:
1627 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1628 result = CAResultToOCResult(CAStartListeningServer());
1629 if(result == OC_STACK_OK)
1631 result = CAResultToOCResult(CAStartDiscoveryServer());
1635 VERIFY_SUCCESS(result, OC_STACK_OK);
1637 #ifdef WITH_PRESENCE
1638 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
1639 #endif // WITH_PRESENCE
1641 //Update Stack state to initialized
1642 stackState = OC_STACK_INITIALIZED;
1644 // Initialize resource
1645 if(myStackMode != OC_CLIENT)
1647 result = initResources();
1650 // Initialize the SRM Policy Engine
1651 if(result == OC_STACK_OK)
1653 result = SRMInitPolicyEngine();
1654 // TODO after BeachHead delivery: consolidate into single SRMInit()
1658 if(result != OC_STACK_OK)
1660 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1661 deleteAllResources();
1663 stackState = OC_STACK_UNINITIALIZED;
1668 OCStackResult OCStop()
1670 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1672 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1674 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1677 else if (stackState != OC_STACK_INITIALIZED)
1679 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1680 return OC_STACK_ERROR;
1683 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1685 #ifdef WITH_PRESENCE
1686 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1687 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1688 presenceResource.presenceTTL = 0;
1689 #endif // WITH_PRESENCE
1691 // Free memory dynamically allocated for resources
1692 deleteAllResources();
1694 DeletePlatformInfo();
1696 // Remove all observers
1697 DeleteObserverList();
1698 // Remove all the client callbacks
1699 DeleteClientCBList();
1701 // De-init the SRM Policy Engine
1702 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
1703 SRMDeInitPolicyEngine();
1706 stackState = OC_STACK_UNINITIALIZED;
1710 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1715 return CA_MSG_CONFIRM;
1720 return CA_MSG_NONCONFIRM;
1724 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1728 query = strchr (inputUri, '?');
1732 if((query - inputUri) > MAX_URI_LENGTH)
1734 return OC_STACK_INVALID_URI;
1737 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1739 return OC_STACK_INVALID_QUERY;
1742 else if(uriLen > MAX_URI_LENGTH)
1744 return OC_STACK_INVALID_URI;
1750 * A request uri consists of the following components in order:
1752 * optional prefix "coap://"
1754 * IPv6 address "[1234::5678]"
1755 * IPv4 address "192.168.1.1"
1756 * optional port ":5683"
1757 * resource uri "/oc/core..."
1759 * for PRESENCE requests, extract resource type.
1761 static OCStackResult ParseRequestUri(const char *fullUri,
1762 OCTransportAdapter adapter,
1763 OCTransportFlags flags,
1764 OCDevAddr **devAddr,
1766 char **resourceType)
1768 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
1770 OCStackResult result = OC_STACK_OK;
1771 OCDevAddr *da = NULL;
1775 // provide defaults for all returned values
1782 *resourceUri = NULL;
1786 *resourceType = NULL;
1789 // delimit url prefix, if any
1790 const char *start = fullUri;
1791 char *slash2 = strstr(start, "//");
1796 char *slash = strchr(start, '/');
1799 return OC_STACK_INVALID_URI;
1802 // processs url prefix, if any
1803 size_t urlLen = slash - start;
1807 if (urlLen && devAddr)
1808 { // construct OCDevAddr
1809 if (start[0] == '[')
1811 char *close = strchr(++start, ']');
1812 if (!close || close > slash)
1814 return OC_STACK_INVALID_URI;
1817 if (close[1] == ':')
1821 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
1822 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
1826 char *dot = strchr(start, '.');
1827 if (dot && dot < slash)
1829 colon = strchr(start, ':');
1830 end = (colon && colon < slash) ? colon : slash;
1831 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
1832 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
1840 if (len >= sizeof(da->addr))
1842 return OC_STACK_INVALID_URI;
1844 // collect port, if any
1845 if (colon && colon < slash)
1847 for (colon++; colon < slash; colon++)
1850 if (c < '0' || c > '9')
1852 return OC_STACK_INVALID_URI;
1854 port = 10 * port + c - '0';
1859 if (len >= sizeof(da->addr))
1861 return OC_STACK_INVALID_URI;
1864 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
1867 return OC_STACK_NO_MEMORY;
1869 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
1871 da->adapter = adapter;
1873 if (!strncmp(fullUri, "coaps:", 6))
1875 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
1880 // process resource uri, if any
1882 { // request uri and query
1883 size_t ulen = strlen(slash); // resource uri length
1884 size_t tlen = 0; // resource type length
1887 static const char strPresence[] = "/oic/ad?rt=";
1888 static const size_t lenPresence = sizeof(strPresence) - 1;
1889 if (!strncmp(slash, strPresence, lenPresence))
1891 type = slash + lenPresence;
1892 tlen = ulen - lenPresence;
1897 *resourceUri = (char *)OICMalloc(ulen + 1);
1900 result = OC_STACK_NO_MEMORY;
1903 strcpy(*resourceUri, slash);
1906 if (type && resourceType)
1908 *resourceType = (char *)OICMalloc(tlen + 1);
1911 result = OC_STACK_NO_MEMORY;
1915 OICStrcpy(*resourceType, (tlen+1), type);
1922 // free all returned values
1929 OICFree(*resourceUri);
1933 OICFree(*resourceType);
1938 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
1939 char *resourceUri, char **requestUri)
1941 char uri[CA_MAX_URI_LENGTH];
1943 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
1945 *requestUri = OICStrdup(uri);
1948 return OC_STACK_NO_MEMORY;
1955 * Discover or Perform requests on a specified resource
1957 OCStackResult OCDoResource(OCDoHandle *handle,
1959 const char *requestUri,
1960 const OCDevAddr *destination,
1962 OCConnectivityType connectivityType,
1963 OCQualityOfService qos,
1964 OCCallbackData *cbData,
1965 OCHeaderOption *options,
1968 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1970 // Validate input parameters
1971 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1972 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1973 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
1975 OCStackResult result = OC_STACK_ERROR;
1976 CAResult_t caResult;
1977 CAToken_t token = NULL;
1978 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
1979 ClientCB *clientCB = NULL;
1980 OCDoHandle resHandle = NULL;
1981 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
1982 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
1984 OCTransportAdapter adapter;
1985 OCTransportFlags flags;
1986 // the request contents are put here
1987 CARequestInfo_t requestInfo = {.method = CA_GET};
1988 // requestUri will be parsed into the following three variables
1989 OCDevAddr *devAddr = NULL;
1990 char *resourceUri = NULL;
1991 char *resourceType = NULL;
1993 // To track if memory is allocated for additional header options
1994 uint8_t hdrOptionMemAlloc = 0;
1996 // This validation is broken, but doesn't cause harm
1997 size_t uriLen = strlen(requestUri );
1998 if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
2004 * Support original behavior with address on resourceUri argument.
2006 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2007 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2009 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2011 if (result != OC_STACK_OK)
2013 OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2020 case OC_REST_OBSERVE:
2021 case OC_REST_OBSERVE_ALL:
2022 case OC_REST_CANCEL_OBSERVE:
2023 requestInfo.method = CA_GET;
2026 requestInfo.method = CA_PUT;
2029 requestInfo.method = CA_POST;
2031 case OC_REST_DELETE:
2032 requestInfo.method = CA_DELETE;
2034 case OC_REST_DISCOVER:
2036 if (destination || devAddr)
2038 requestInfo.isMulticast = false;
2042 tmpDevAddr.adapter = adapter;
2043 tmpDevAddr.flags = flags;
2044 destination = &tmpDevAddr;
2045 requestInfo.isMulticast = true;
2047 // CA_DISCOVER will become GET and isMulticast
2048 requestInfo.method = CA_GET;
2050 #ifdef WITH_PRESENCE
2051 case OC_REST_PRESENCE:
2052 // Replacing method type with GET because "presence"
2053 // is a stack layer only implementation.
2054 requestInfo.method = CA_GET;
2058 result = OC_STACK_INVALID_METHOD;
2062 if (!devAddr && !destination)
2064 OC_LOG_V(DEBUG, TAG, "no devAddr and no destination");
2065 result = OC_STACK_INVALID_PARAM;
2069 /* If not original behavior, use destination argument */
2070 if (destination && !devAddr)
2072 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2075 result = OC_STACK_NO_MEMORY;
2078 *devAddr = *destination;
2081 resHandle = GenerateInvocationHandle();
2084 result = OC_STACK_NO_MEMORY;
2088 caResult = CAGenerateToken(&token, tokenLength);
2089 if (caResult != CA_STATUS_OK)
2091 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2092 result= OC_STACK_ERROR;
2096 // fill in request data
2097 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2098 requestInfo.info.token = token;
2099 requestInfo.info.tokenLength = tokenLength;
2100 requestInfo.info.resourceUri = resourceUri;
2102 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2104 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2105 options, numOptions, OC_OBSERVE_REGISTER);
2106 if (result != OC_STACK_OK)
2110 hdrOptionMemAlloc = 1;
2111 requestInfo.info.numOptions = numOptions + 1;
2115 requestInfo.info.options = (CAHeaderOption_t*)options;
2116 requestInfo.info.numOptions = numOptions;
2119 CopyDevAddrToEndpoint(devAddr, &endpoint);
2124 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2127 OC_LOG(ERROR, TAG, PCF("Failed to create CBOR Payload"));
2133 requestInfo.info.payload = NULL;
2134 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);
2206 if (hdrOptionMemAlloc)
2208 OICFree(requestInfo.info.options);
2213 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2217 * This ftn is implemented one of two ways in the case of observation:
2219 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2220 * Remove the callback associated on client side.
2221 * When the next notification comes in from server,
2222 * reply with RESET message to server.
2223 * Keep in mind that the server will react to RESET only
2224 * if the last notification was sent as CON
2226 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2227 * and it is associated with an observe request
2228 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2229 * Send CON Observe request to server with
2230 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2231 * Remove the callback associated on client side.
2233 OCStackResult ret = OC_STACK_OK;
2234 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2235 CAResult_t caResult;
2236 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2237 CARequestInfo_t requestInfo = {.method = CA_GET};
2241 return OC_STACK_INVALID_PARAM;
2244 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2247 OC_LOG(ERROR, TAG, PCF("Client callback not found. Called OCCancel twice?"));
2251 switch (clientCB->method)
2253 case OC_REST_OBSERVE:
2254 case OC_REST_OBSERVE_ALL:
2255 OC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
2256 clientCB->requestUri);
2257 if (qos != OC_HIGH_QOS)
2259 FindAndDeleteClientCB(clientCB);
2264 OC_LOG(INFO, TAG, PCF("Cancelling observation as CONFIRMABLE"));
2267 requestData.type = qualityOfServiceToMessageType(qos);
2268 requestData.token = clientCB->token;
2269 requestData.tokenLength = clientCB->tokenLength;
2270 if (CreateObserveHeaderOption (&(requestData.options),
2271 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2273 return OC_STACK_ERROR;
2275 requestData.numOptions = numOptions + 1;
2276 requestData.resourceUri = OICStrdup (clientCB->requestUri);
2278 requestInfo.method = CA_GET;
2279 requestInfo.info = requestData;
2281 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2284 caResult = CASendRequest(&endpoint, &requestInfo);
2285 if (caResult != CA_STATUS_OK)
2287 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2288 ret = OC_STACK_ERROR;
2290 ret = CAResultToOCResult (caResult);
2293 #ifdef WITH_PRESENCE
2294 case OC_REST_PRESENCE:
2295 FindAndDeleteClientCB(clientCB);
2300 ret = OC_STACK_INVALID_METHOD;
2305 if (requestData.numOptions > 0)
2307 OICFree(requestData.options);
2309 if (requestData.resourceUri)
2311 OICFree (requestData.resourceUri);
2317 * @brief Register Persistent storage callback.
2318 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2320 * OC_STACK_OK - No errors; Success
2321 * OC_STACK_INVALID_PARAM - Invalid parameter
2323 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2325 OC_LOG(INFO, TAG, PCF("RegisterPersistentStorageHandler !!"));
2326 if(!persistentStorageHandler)
2328 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2329 return OC_STACK_INVALID_PARAM;
2333 if( !persistentStorageHandler->open ||
2334 !persistentStorageHandler->close ||
2335 !persistentStorageHandler->read ||
2336 !persistentStorageHandler->unlink ||
2337 !persistentStorageHandler->write)
2339 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2340 return OC_STACK_INVALID_PARAM;
2343 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2346 #ifdef WITH_PRESENCE
2348 OCStackResult OCProcessPresence()
2350 OCStackResult result = OC_STACK_OK;
2352 // the following line floods the log with messages that are irrelevant
2353 // to most purposes. Uncomment as needed.
2354 //OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
2355 ClientCB* cbNode = NULL;
2356 OCClientResponse clientResponse;
2357 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2359 LL_FOREACH(cbList, cbNode)
2361 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2366 uint32_t now = GetTicks(0);
2367 OC_LOG_V(DEBUG, TAG, "this TTL level %d",
2368 cbNode->presence->TTLlevel);
2369 OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2371 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2376 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2378 OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2379 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2381 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2383 OC_LOG(DEBUG, TAG, PCF("No more timeout ticks"));
2385 clientResponse.sequenceNumber = 0;
2386 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2387 clientResponse.devAddr = *cbNode->devAddr;
2388 FixUpClientResponse(&clientResponse);
2389 clientResponse.payload = NULL;
2391 // Increment the TTLLevel (going to a next state), so we don't keep
2392 // sending presence notification to client.
2393 cbNode->presence->TTLlevel++;
2394 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2395 cbNode->presence->TTLlevel);
2397 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2398 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2400 FindAndDeleteClientCB(cbNode);
2404 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2409 CAResult_t caResult = CA_STATUS_OK;
2410 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2411 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2412 CARequestInfo_t requestInfo = {.method = CA_GET};
2414 OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
2416 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2418 requestData.type = CA_MSG_NONCONFIRM;
2419 requestData.token = cbNode->token;
2420 requestData.tokenLength = cbNode->tokenLength;
2421 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2422 requestInfo.method = CA_GET;
2423 requestInfo.info = requestData;
2425 caResult = CASendRequest(&endpoint, &requestInfo);
2427 if (caResult != CA_STATUS_OK)
2429 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2433 cbNode->presence->TTLlevel++;
2434 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2437 if (result != OC_STACK_OK)
2439 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2444 #endif // WITH_PRESENCE
2446 OCStackResult OCProcess()
2448 #ifdef WITH_PRESENCE
2449 OCProcessPresence();
2451 CAHandleRequestResponse();
2456 #ifdef WITH_PRESENCE
2457 OCStackResult OCStartPresence(const uint32_t ttl)
2459 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2460 OCChangeResourceProperty(
2461 &(((OCResource *)presenceResource.handle)->resourceProperties),
2464 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2466 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2467 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to max value"));
2471 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2472 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to default value"));
2476 presenceResource.presenceTTL = ttl;
2478 OC_LOG_V(DEBUG, TAG, "Presence TTL is %lu seconds", presenceResource.presenceTTL);
2480 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2482 presenceState = OC_PRESENCE_INITIALIZED;
2484 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2486 CAToken_t caToken = NULL;
2487 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2488 if (caResult != CA_STATUS_OK)
2490 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2491 CADestroyToken(caToken);
2492 return OC_STACK_ERROR;
2495 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2496 (OCResource *)presenceResource.handle, OC_LOW_QOS, &devAddr);
2497 CADestroyToken(caToken);
2500 // Each time OCStartPresence is called
2501 // a different random 32-bit integer number is used
2502 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2504 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2505 OC_PRESENCE_TRIGGER_CREATE);
2508 OCStackResult OCStopPresence()
2510 OCStackResult result = OC_STACK_ERROR;
2512 if(presenceResource.handle)
2514 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2516 // make resource inactive
2517 result = OCChangeResourceProperty(
2518 &(((OCResource *) presenceResource.handle)->resourceProperties),
2522 if(result != OC_STACK_OK)
2525 PCF("Changing the presence resource properties to ACTIVE not successful"));
2529 return SendStopNotification();
2533 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
2534 void* callbackParameter)
2536 defaultDeviceHandler = entityHandler;
2537 defaultDeviceHandlerCallbackParameter = callbackParameter;
2542 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
2544 OC_LOG(INFO, TAG, PCF("Entering OCSetPlatformInfo"));
2546 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
2548 if (validatePlatformInfo(platformInfo))
2550 return SavePlatformInfo(platformInfo);
2554 return OC_STACK_INVALID_PARAM;
2559 return OC_STACK_ERROR;
2563 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2565 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2567 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
2569 OC_LOG(ERROR, TAG, PCF("Null or empty device name."));
2570 return OC_STACK_INVALID_PARAM;
2573 return SaveDeviceInfo(deviceInfo);
2576 OCStackResult OCCreateResource(OCResourceHandle *handle,
2577 const char *resourceTypeName,
2578 const char *resourceInterfaceName,
2579 const char *uri, OCEntityHandler entityHandler,
2580 void* callbackParam,
2581 uint8_t resourceProperties)
2584 OCResource *pointer = NULL;
2586 OCStackResult result = OC_STACK_ERROR;
2588 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2590 if(myStackMode == OC_CLIENT)
2592 return OC_STACK_INVALID_PARAM;
2594 // Validate parameters
2595 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2597 OC_LOG(ERROR, TAG, PCF("URI is empty or too long"));
2598 return OC_STACK_INVALID_URI;
2600 // Is it presented during resource discovery?
2601 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
2603 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2604 return OC_STACK_INVALID_PARAM;
2607 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2609 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2612 // Make sure resourceProperties bitmask has allowed properties specified
2613 if (resourceProperties
2614 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
2615 OC_EXPLICIT_DISCOVERABLE))
2617 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2618 return OC_STACK_INVALID_PARAM;
2621 // If the headResource is NULL, then no resources have been created...
2622 pointer = headResource;
2625 // At least one resources is in the resource list, so we need to search for
2626 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2629 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
2631 OC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
2632 return OC_STACK_INVALID_PARAM;
2634 pointer = pointer->next;
2637 // Create the pointer and insert it into the resource list
2638 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
2641 result = OC_STACK_NO_MEMORY;
2644 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2646 insertResource(pointer);
2649 str = OICStrdup(uri);
2652 result = OC_STACK_NO_MEMORY;
2657 // Set properties. Set OC_ACTIVE
2658 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2661 // Add the resourcetype to the resource
2662 result = BindResourceTypeToResource(pointer, resourceTypeName);
2663 if (result != OC_STACK_OK)
2665 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2669 // Add the resourceinterface to the resource
2670 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2671 if (result != OC_STACK_OK)
2673 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2677 // If an entity handler has been passed, attach it to the newly created
2678 // resource. Otherwise, set the default entity handler.
2681 pointer->entityHandler = entityHandler;
2682 pointer->entityHandlerCallbackParam = callbackParam;
2686 pointer->entityHandler = defaultResourceEHandler;
2687 pointer->entityHandlerCallbackParam = NULL;
2691 result = OC_STACK_OK;
2693 #ifdef WITH_PRESENCE
2694 if(presenceResource.handle)
2696 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2697 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
2701 if (result != OC_STACK_OK)
2703 // Deep delete of resource and other dynamic elements that it contains
2704 deleteResource(pointer);
2711 OCStackResult OCBindResource(
2712 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2714 OCResource *resource = NULL;
2717 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2719 // Validate parameters
2720 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2721 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2722 // Container cannot contain itself
2723 if (collectionHandle == resourceHandle)
2725 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2726 return OC_STACK_INVALID_PARAM;
2729 // Use the handle to find the resource in the resource linked list
2730 resource = findResource((OCResource *) collectionHandle);
2733 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2734 return OC_STACK_INVALID_PARAM;
2737 // Look for an open slot to add add the child resource.
2738 // If found, add it and return success
2739 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2741 if (!resource->rsrcResources[i])
2743 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2744 OC_LOG(INFO, TAG, PCF("resource bound"));
2746 #ifdef WITH_PRESENCE
2747 if(presenceResource.handle)
2749 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2750 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2751 OC_PRESENCE_TRIGGER_CHANGE);
2759 // Unable to add resourceHandle, so return error
2760 return OC_STACK_ERROR;
2763 OCStackResult OCUnBindResource(
2764 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2766 OCResource *resource = NULL;
2769 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2771 // Validate parameters
2772 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2773 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2774 // Container cannot contain itself
2775 if (collectionHandle == resourceHandle)
2777 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2778 return OC_STACK_INVALID_PARAM;
2781 // Use the handle to find the resource in the resource linked list
2782 resource = findResource((OCResource *) collectionHandle);
2785 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2786 return OC_STACK_INVALID_PARAM;
2789 // Look for an open slot to add add the child resource.
2790 // If found, add it and return success
2791 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2793 if (resourceHandle == resource->rsrcResources[i])
2795 resource->rsrcResources[i] = (OCResource *) NULL;
2796 OC_LOG(INFO, TAG, PCF("resource unbound"));
2798 // Send notification when resource is unbounded successfully.
2799 #ifdef WITH_PRESENCE
2800 if(presenceResource.handle)
2802 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2803 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2804 OC_PRESENCE_TRIGGER_CHANGE);
2811 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2813 // Unable to add resourceHandle, so return error
2814 return OC_STACK_ERROR;
2817 OCStackResult BindResourceTypeToResource(OCResource* resource,
2818 const char *resourceTypeName)
2820 OCResourceType *pointer = NULL;
2822 OCStackResult result = OC_STACK_ERROR;
2824 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2826 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
2829 result = OC_STACK_NO_MEMORY;
2833 str = OICStrdup(resourceTypeName);
2836 result = OC_STACK_NO_MEMORY;
2839 pointer->resourcetypename = str;
2841 insertResourceType(resource, pointer);
2842 result = OC_STACK_OK;
2845 if (result != OC_STACK_OK)
2854 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2855 const char *resourceInterfaceName)
2857 OCResourceInterface *pointer = NULL;
2859 OCStackResult result = OC_STACK_ERROR;
2861 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2863 OC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
2865 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
2868 result = OC_STACK_NO_MEMORY;
2872 str = OICStrdup(resourceInterfaceName);
2875 result = OC_STACK_NO_MEMORY;
2878 pointer->name = str;
2880 // Bind the resourceinterface to the resource
2881 insertResourceInterface(resource, pointer);
2883 result = OC_STACK_OK;
2886 if (result != OC_STACK_OK)
2895 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2896 const char *resourceTypeName)
2899 OCStackResult result = OC_STACK_ERROR;
2900 OCResource *resource = NULL;
2902 resource = findResource((OCResource *) handle);
2905 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2906 return OC_STACK_ERROR;
2909 result = BindResourceTypeToResource(resource, resourceTypeName);
2911 #ifdef WITH_PRESENCE
2912 if(presenceResource.handle)
2914 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2915 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2922 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2923 const char *resourceInterfaceName)
2926 OCStackResult result = OC_STACK_ERROR;
2927 OCResource *resource = NULL;
2929 resource = findResource((OCResource *) handle);
2932 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2933 return OC_STACK_ERROR;
2936 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2938 #ifdef WITH_PRESENCE
2939 if(presenceResource.handle)
2941 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2942 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2949 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
2951 OCResource *pointer = headResource;
2953 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2957 *numResources = *numResources + 1;
2958 pointer = pointer->next;
2963 OCResourceHandle OCGetResourceHandle(uint8_t index)
2965 OCResource *pointer = headResource;
2967 for( uint8_t i = 0; i < index && pointer; ++i)
2969 pointer = pointer->next;
2971 return (OCResourceHandle) pointer;
2974 OCStackResult OCDeleteResource(OCResourceHandle handle)
2978 OC_LOG(ERROR, TAG, PCF("Invalid handle for deletion"));
2979 return OC_STACK_INVALID_PARAM;
2982 OCResource *resource = findResource((OCResource *) handle);
2983 if (resource == NULL)
2985 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2986 return OC_STACK_NO_RESOURCE;
2989 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
2991 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2992 return OC_STACK_ERROR;
2998 const char *OCGetResourceUri(OCResourceHandle handle)
3000 OCResource *resource = NULL;
3002 resource = findResource((OCResource *) handle);
3005 return resource->uri;
3007 return (const char *) NULL;
3010 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3012 OCResource *resource = NULL;
3014 resource = findResource((OCResource *) handle);
3017 return resource->resourceProperties;
3019 return (OCResourceProperty)-1;
3022 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3023 uint8_t *numResourceTypes)
3025 OCResource *resource = NULL;
3026 OCResourceType *pointer = NULL;
3028 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3029 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3031 *numResourceTypes = 0;
3033 resource = findResource((OCResource *) handle);
3036 pointer = resource->rsrcType;
3039 *numResourceTypes = *numResourceTypes + 1;
3040 pointer = pointer->next;
3046 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3048 OCResourceType *resourceType = NULL;
3050 resourceType = findResourceTypeAtIndex(handle, index);
3053 return resourceType->resourcetypename;
3055 return (const char *) NULL;
3058 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3059 uint8_t *numResourceInterfaces)
3061 OCResourceInterface *pointer = NULL;
3062 OCResource *resource = NULL;
3064 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3065 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3067 *numResourceInterfaces = 0;
3068 resource = findResource((OCResource *) handle);
3071 pointer = resource->rsrcInterface;
3074 *numResourceInterfaces = *numResourceInterfaces + 1;
3075 pointer = pointer->next;
3081 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3083 OCResourceInterface *resourceInterface = NULL;
3085 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3086 if (resourceInterface)
3088 return resourceInterface->name;
3090 return (const char *) NULL;
3093 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3096 OCResource *resource = NULL;
3098 if (index >= MAX_CONTAINED_RESOURCES)
3103 resource = findResource((OCResource *) collectionHandle);
3109 return resource->rsrcResources[index];
3112 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3113 OCEntityHandler entityHandler,
3114 void* callbackParam)
3116 OCResource *resource = NULL;
3118 // Validate parameters
3119 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3121 // Use the handle to find the resource in the resource linked list
3122 resource = findResource((OCResource *)handle);
3125 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3126 return OC_STACK_ERROR;
3130 resource->entityHandler = entityHandler;
3131 resource->entityHandlerCallbackParam = callbackParam;
3133 #ifdef WITH_PRESENCE
3134 if(presenceResource.handle)
3136 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3137 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3144 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3146 OCResource *resource = NULL;
3148 resource = findResource((OCResource *)handle);
3151 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3156 return resource->entityHandler;
3159 void incrementSequenceNumber(OCResource * resPtr)
3161 // Increment the sequence number
3162 resPtr->sequenceNum += 1;
3163 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3165 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3170 #ifdef WITH_PRESENCE
3171 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3172 OCPresenceTrigger trigger)
3174 OCResource *resPtr = NULL;
3175 OCStackResult result = OC_STACK_ERROR;
3176 OCMethod method = OC_REST_PRESENCE;
3177 uint32_t maxAge = 0;
3178 resPtr = findResource((OCResource *) presenceResource.handle);
3181 return OC_STACK_NO_RESOURCE;
3184 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3186 maxAge = presenceResource.presenceTTL;
3188 result = SendAllObserverNotification(method, resPtr, maxAge,
3189 trigger, resourceType, OC_LOW_QOS);
3195 OCStackResult SendStopNotification()
3197 OCResource *resPtr = NULL;
3198 OCStackResult result = OC_STACK_ERROR;
3199 OCMethod method = OC_REST_PRESENCE;
3200 resPtr = findResource((OCResource *) presenceResource.handle);
3203 return OC_STACK_NO_RESOURCE;
3206 // maxAge is 0. ResourceType is NULL.
3207 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3213 #endif // WITH_PRESENCE
3214 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3216 OCResource *resPtr = NULL;
3217 OCStackResult result = OC_STACK_ERROR;
3218 OCMethod method = OC_REST_NOMETHOD;
3219 uint32_t maxAge = 0;
3221 OC_LOG(INFO, TAG, PCF("Notifying all observers"));
3222 #ifdef WITH_PRESENCE
3223 if(handle == presenceResource.handle)
3227 #endif // WITH_PRESENCE
3228 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3230 // Verify that the resource exists
3231 resPtr = findResource ((OCResource *) handle);
3234 return OC_STACK_NO_RESOURCE;
3238 //only increment in the case of regular observing (not presence)
3239 incrementSequenceNumber(resPtr);
3240 method = OC_REST_OBSERVE;
3241 maxAge = MAX_OBSERVE_AGE;
3242 #ifdef WITH_PRESENCE
3243 result = SendAllObserverNotification (method, resPtr, maxAge,
3244 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3246 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3253 OCNotifyListOfObservers (OCResourceHandle handle,
3254 OCObservationId *obsIdList,
3255 uint8_t numberOfIds,
3256 const OCRepPayload *payload,
3257 OCQualityOfService qos)
3259 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3261 OCResource *resPtr = NULL;
3262 //TODO: we should allow the server to define this
3263 uint32_t maxAge = MAX_OBSERVE_AGE;
3265 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3266 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3267 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3269 resPtr = findResource ((OCResource *) handle);
3270 if (NULL == resPtr || myStackMode == OC_CLIENT)
3272 return OC_STACK_NO_RESOURCE;
3276 incrementSequenceNumber(resPtr);
3278 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3279 payload, maxAge, qos));
3282 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3284 OCStackResult result = OC_STACK_ERROR;
3285 OCServerRequest *serverRequest = NULL;
3287 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3289 // Validate input parameters
3290 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3291 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3294 // Get pointer to request info
3295 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3298 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3299 result = serverRequest->ehResponseHandler(ehResponse);
3305 //-----------------------------------------------------------------------------
3306 // Private internal function definitions
3307 //-----------------------------------------------------------------------------
3308 static OCDoHandle GenerateInvocationHandle()
3310 OCDoHandle handle = NULL;
3311 // Generate token here, it will be deleted when the transaction is deleted
3312 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3315 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3321 #ifdef WITH_PRESENCE
3322 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3323 OCResourceProperty resourceProperties, uint8_t enable)
3327 return OC_STACK_INVALID_PARAM;
3329 if (resourceProperties
3330 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3332 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3333 return OC_STACK_INVALID_PARAM;
3337 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3341 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3347 OCStackResult initResources()
3349 OCStackResult result = OC_STACK_OK;
3351 headResource = NULL;
3352 tailResource = NULL;
3353 // Init Virtual Resources
3354 #ifdef WITH_PRESENCE
3355 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3357 result = OCCreateResource(&presenceResource.handle,
3358 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3360 OC_RSRVD_PRESENCE_URI,
3364 //make resource inactive
3365 result = OCChangeResourceProperty(
3366 &(((OCResource *) presenceResource.handle)->resourceProperties),
3370 if (result == OC_STACK_OK)
3372 result = SRMInitSecureResources();
3378 void insertResource(OCResource *resource)
3382 headResource = resource;
3383 tailResource = resource;
3387 tailResource->next = resource;
3388 tailResource = resource;
3390 resource->next = NULL;
3393 OCResource *findResource(OCResource *resource)
3395 OCResource *pointer = headResource;
3399 if (pointer == resource)
3403 pointer = pointer->next;
3408 void deleteAllResources()
3410 OCResource *pointer = headResource;
3411 OCResource *temp = NULL;
3415 temp = pointer->next;
3416 #ifdef WITH_PRESENCE
3417 if(pointer != (OCResource *) presenceResource.handle)
3419 #endif // WITH_PRESENCE
3420 deleteResource(pointer);
3421 #ifdef WITH_PRESENCE
3423 #endif // WITH_PRESENCE
3427 SRMDeInitSecureResources();
3429 #ifdef WITH_PRESENCE
3430 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3431 // presence notification attributed to their deletion to be processed.
3432 deleteResource((OCResource *) presenceResource.handle);
3433 #endif // WITH_PRESENCE
3436 OCStackResult deleteResource(OCResource *resource)
3438 OCResource *prev = NULL;
3439 OCResource *temp = NULL;
3442 OC_LOG_V(DEBUG,TAG,"resource is NULL");
3443 return OC_STACK_INVALID_PARAM;
3446 OC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
3448 temp = headResource;
3451 if (temp == resource)
3453 // Invalidate all Resource Properties.
3454 resource->resourceProperties = (OCResourceProperty) 0;
3455 #ifdef WITH_PRESENCE
3456 if(resource != (OCResource *) presenceResource.handle)
3458 #endif // WITH_PRESENCE
3459 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3460 #ifdef WITH_PRESENCE
3463 if(presenceResource.handle)
3465 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3466 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
3469 // Only resource in list.
3470 if (temp == headResource && temp == tailResource)
3472 headResource = NULL;
3473 tailResource = NULL;
3476 else if (temp == headResource)
3478 headResource = temp->next;
3481 else if (temp == tailResource)
3483 tailResource = prev;
3484 tailResource->next = NULL;
3488 prev->next = temp->next;
3491 deleteResourceElements(temp);
3502 return OC_STACK_ERROR;
3505 void deleteResourceElements(OCResource *resource)
3512 OICFree(resource->uri);
3513 deleteResourceType(resource->rsrcType);
3514 deleteResourceInterface(resource->rsrcInterface);
3517 void deleteResourceType(OCResourceType *resourceType)
3519 OCResourceType *pointer = resourceType;
3520 OCResourceType *next = NULL;
3524 next = pointer->next;
3525 OICFree(pointer->resourcetypename);
3531 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3533 OCResourceInterface *pointer = resourceInterface;
3534 OCResourceInterface *next = NULL;
3538 next = pointer->next;
3539 OICFree(pointer->name);
3545 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3547 OCResourceType *pointer = NULL;
3548 OCResourceType *previous = NULL;
3549 if (!resource || !resourceType)
3553 // resource type list is empty.
3554 else if (!resource->rsrcType)
3556 resource->rsrcType = resourceType;
3560 pointer = resource->rsrcType;
3564 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
3566 OC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
3567 OICFree(resourceType->resourcetypename);
3568 OICFree(resourceType);
3572 pointer = pointer->next;
3574 previous->next = resourceType;
3576 resourceType->next = NULL;
3578 OC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
3581 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3583 OCResource *resource = NULL;
3584 OCResourceType *pointer = NULL;
3586 // Find the specified resource
3587 resource = findResource((OCResource *) handle);
3593 // Make sure a resource has a resourcetype
3594 if (!resource->rsrcType)
3599 // Iterate through the list
3600 pointer = resource->rsrcType;
3601 for(uint8_t i = 0; i< index && pointer; ++i)
3603 pointer = pointer->next;
3608 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3610 if(resourceTypeList && resourceTypeName)
3612 OCResourceType * rtPointer = resourceTypeList;
3613 while(resourceTypeName && rtPointer)
3615 if(rtPointer->resourcetypename &&
3616 strcmp(resourceTypeName, (const char *)
3617 (rtPointer->resourcetypename)) == 0)
3621 rtPointer = rtPointer->next;
3629 * Insert a new interface into interface linked list only if not already present.
3630 * If alredy present, 2nd arg is free'd.
3631 * Default interface will always be first if present.
3633 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
3635 OCResourceInterface *pointer = NULL;
3636 OCResourceInterface *previous = NULL;
3638 newInterface->next = NULL;
3640 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
3642 if (!*firstInterface)
3644 *firstInterface = newInterface;
3646 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3648 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3650 OICFree(newInterface->name);
3651 OICFree(newInterface);
3656 newInterface->next = *firstInterface;
3657 *firstInterface = newInterface;
3662 pointer = *firstInterface;
3665 if (strcmp(newInterface->name, pointer->name) == 0)
3667 OICFree(newInterface->name);
3668 OICFree(newInterface);
3672 pointer = pointer->next;
3674 previous->next = newInterface;
3678 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3681 OCResource *resource = NULL;
3682 OCResourceInterface *pointer = NULL;
3684 // Find the specified resource
3685 resource = findResource((OCResource *) handle);
3691 // Make sure a resource has a resourceinterface
3692 if (!resource->rsrcInterface)
3697 // Iterate through the list
3698 pointer = resource->rsrcInterface;
3700 for (uint8_t i = 0; i < index && pointer; ++i)
3702 pointer = pointer->next;
3708 * This function splits the uri using the '?' delimiter.
3709 * "uriWithoutQuery" is the block of characters between the beginning
3710 * till the delimiter or '\0' which ever comes first.
3711 * "query" is whatever is to the right of the delimiter if present.
3712 * No delimiter sets the query to NULL.
3713 * If either are present, they will be malloc'ed into the params 2, 3.
3714 * The first param, *uri is left untouched.
3716 * NOTE: This function does not account for whitespace at the end of the uri NOR
3717 * malformed uri's with '??'. Whitespace at the end will be assumed to be
3718 * part of the query.
3720 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
3724 return OC_STACK_INVALID_URI;
3726 if(!query || !uriWithoutQuery)
3728 return OC_STACK_INVALID_PARAM;
3732 *uriWithoutQuery = NULL;
3734 size_t uriWithoutQueryLen = 0;
3735 size_t queryLen = 0;
3736 size_t uriLen = strlen(uri);
3738 char *pointerToDelimiter = strstr(uri, "?");
3740 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
3741 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
3743 if (uriWithoutQueryLen)
3745 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
3746 if (!*uriWithoutQuery)
3750 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
3754 *query = (char *) OICCalloc(queryLen + 1, 1);
3757 OICFree(*uriWithoutQuery);
3758 *uriWithoutQuery = NULL;
3761 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
3767 return OC_STACK_NO_MEMORY;
3770 const uint8_t* OCGetServerInstanceID(void)
3772 static bool generated = false;
3773 static ServerID sid;
3779 if (OCGenerateUuid(sid) != RAND_UUID_OK)
3781 OC_LOG(FATAL, TAG, PCF("Generate UUID for Server Instance failed!"));
3788 const char* OCGetServerInstanceIDString(void)
3790 static bool generated = false;
3791 static char sidStr[UUID_STRING_SIZE];
3798 const uint8_t* sid = OCGetServerInstanceID();
3800 if(OCConvertUuidToString(sid, sidStr) != RAND_UUID_OK)
3802 OC_LOG(FATAL, TAG, PCF("Generate UUID String for Server Instance failed!"));
3810 CAResult_t OCSelectNetwork()
3812 CAResult_t retResult = CA_STATUS_FAILED;
3813 CAResult_t caResult = CA_STATUS_OK;
3815 CATransportAdapter_t connTypes[] = {
3817 CA_ADAPTER_RFCOMM_BTEDR,
3818 CA_ADAPTER_GATT_BTLE
3821 ,CA_ADAPTER_REMOTE_ACCESS
3824 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
3826 for(int i = 0; i<numConnTypes; i++)
3828 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
3829 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
3831 caResult = CASelectNetwork(connTypes[i]);
3832 if(caResult == CA_STATUS_OK)
3834 retResult = CA_STATUS_OK;
3839 if(retResult != CA_STATUS_OK)
3841 return caResult; // Returns error of appropriate transport that failed fatally.
3847 OCStackResult CAResultToOCResult(CAResult_t caResult)
3853 case CA_STATUS_INVALID_PARAM:
3854 return OC_STACK_INVALID_PARAM;
3855 case CA_ADAPTER_NOT_ENABLED:
3856 return OC_STACK_ADAPTER_NOT_ENABLED;
3857 case CA_SERVER_STARTED_ALREADY:
3859 case CA_SERVER_NOT_STARTED:
3860 return OC_STACK_ERROR;
3861 case CA_DESTINATION_NOT_REACHABLE:
3862 return OC_STACK_COMM_ERROR;
3863 case CA_SOCKET_OPERATION_FAILED:
3864 return OC_STACK_COMM_ERROR;
3865 case CA_SEND_FAILED:
3866 return OC_STACK_COMM_ERROR;
3867 case CA_RECEIVE_FAILED:
3868 return OC_STACK_COMM_ERROR;
3869 case CA_MEMORY_ALLOC_FAILED:
3870 return OC_STACK_NO_MEMORY;
3871 case CA_REQUEST_TIMEOUT:
3872 return OC_STACK_TIMEOUT;
3873 case CA_DESTINATION_DISCONNECTED:
3874 return OC_STACK_COMM_ERROR;
3875 case CA_STATUS_FAILED:
3876 return OC_STACK_ERROR;
3877 case CA_NOT_SUPPORTED:
3878 return OC_STACK_NOTIMPL;
3880 return OC_STACK_ERROR;