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;
404 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
406 VERIFY_NON_NULL_NR(in, FATAL);
407 VERIFY_NON_NULL_NR(out, FATAL);
409 out->adapter = (CATransportAdapter_t)in->adapter;
410 out->flags = OCToCATransportFlags(in->flags);
411 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
412 out->port = in->port;
415 static OCStackResult OCCreateEndpoint(OCDevAddr *devAddr, CAEndpoint_t **endpoint)
417 VERIFY_NON_NULL(devAddr, FATAL, OC_STACK_INVALID_PARAM);
418 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
420 CAEndpoint_t *ep = (CAEndpoint_t *)OICMalloc(sizeof (CAEndpoint_t));
423 return OC_STACK_NO_MEMORY;
426 ep->adapter = (CATransportAdapter_t)devAddr->adapter;
429 ep->adapter = CA_ADAPTER_IP;
431 ep->flags = OCToCATransportFlags(devAddr->flags);
432 OICStrcpy(ep->addr, sizeof(ep->addr), devAddr->addr);
433 ep->port = devAddr->port;
440 static void OCDestroyEndpoint(CAEndpoint_t *endpoint)
445 void FixUpClientResponse(OCClientResponse *cr)
447 VERIFY_NON_NULL_NR(cr, FATAL);
449 cr->addr = &cr->devAddr;
450 cr->connType = (OCConnectivityType)
451 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
454 //-----------------------------------------------------------------------------
455 // Internal API function
456 //-----------------------------------------------------------------------------
458 // This internal function is called to update the stack with the status of
459 // observers and communication failures
460 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
462 OCStackResult result = OC_STACK_ERROR;
463 ResourceObserver * observer = NULL;
464 OCEntityHandlerRequest ehRequest = {};
468 case OC_OBSERVER_NOT_INTERESTED:
469 OC_LOG(DEBUG, TAG, PCF("observer not interested in our notifications"));
470 observer = GetObserverUsingToken (token, tokenLength);
473 result = FormOCEntityHandlerRequest(&ehRequest,
474 (OCRequestHandle)NULL,
477 (OCResourceHandle)NULL,
478 NULL, NULL, 0, 0, NULL,
479 OC_OBSERVE_DEREGISTER,
480 observer->observeId);
481 if(result != OC_STACK_OK)
485 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
486 observer->resource->entityHandlerCallbackParam);
489 result = DeleteObserverUsingToken (token, tokenLength);
490 if(result == OC_STACK_OK)
492 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
496 result = OC_STACK_OK;
497 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
501 case OC_OBSERVER_STILL_INTERESTED:
502 OC_LOG(DEBUG, TAG, PCF("observer still interested, reset the failedCount"));
503 observer = GetObserverUsingToken (token, tokenLength);
506 observer->forceHighQos = 0;
507 observer->failedCommCount = 0;
508 result = OC_STACK_OK;
512 result = OC_STACK_OBSERVER_NOT_FOUND;
516 case OC_OBSERVER_FAILED_COMM:
517 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
518 observer = GetObserverUsingToken (token, tokenLength);
521 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
523 result = FormOCEntityHandlerRequest(&ehRequest,
524 (OCRequestHandle)NULL,
527 (OCResourceHandle)NULL,
528 NULL, NULL, 0, 0, NULL,
529 OC_OBSERVE_DEREGISTER,
530 observer->observeId);
531 if(result != OC_STACK_OK)
533 return OC_STACK_ERROR;
535 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
536 observer->resource->entityHandlerCallbackParam);
538 result = DeleteObserverUsingToken (token, tokenLength);
539 if(result == OC_STACK_OK)
541 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
545 result = OC_STACK_OK;
546 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
551 observer->failedCommCount++;
552 result = OC_STACK_CONTINUE;
554 observer->forceHighQos = 1;
555 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
559 OC_LOG(ERROR, TAG, PCF("Unknown status"));
560 result = OC_STACK_ERROR;
565 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
567 OCStackResult ret = OC_STACK_ERROR;
575 ret = OC_STACK_RESOURCE_CREATED;
578 ret = OC_STACK_RESOURCE_DELETED;
581 ret = OC_STACK_INVALID_QUERY;
583 case CA_UNAUTHORIZED_REQ:
584 ret = OC_STACK_UNAUTHORIZED_REQ;
587 ret = OC_STACK_INVALID_OPTION;
590 ret = OC_STACK_NO_RESOURCE;
592 case CA_RETRANSMIT_TIMEOUT:
593 ret = OC_STACK_COMM_ERROR;
601 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode)
603 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
610 case OC_STACK_RESOURCE_CREATED:
613 case OC_STACK_RESOURCE_DELETED:
616 case OC_STACK_INVALID_QUERY:
619 case OC_STACK_INVALID_OPTION:
622 case OC_STACK_NO_RESOURCE:
625 case OC_STACK_COMM_ERROR:
626 ret = CA_RETRANSMIT_TIMEOUT;
628 case OC_STACK_UNAUTHORIZED_REQ:
629 ret = CA_UNAUTHORIZED_REQ;
637 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
639 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
641 // supply default behavior.
642 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
644 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
646 if ((caFlags & OC_MASK_SCOPE) == 0)
648 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
653 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
655 return (OCTransportFlags)caFlags;
658 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
660 uint32_t lowerBound = 0;
661 uint32_t higherBound = 0;
663 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
665 return OC_STACK_INVALID_PARAM;
668 OC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
670 cbNode->presence->TTL = maxAgeSeconds;
672 for(int index = 0; index < PresenceTimeOutSize; index++)
674 // Guard against overflow
675 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
678 lowerBound = GetTicks((PresenceTimeOut[index] *
679 cbNode->presence->TTL *
680 MILLISECONDS_PER_SECOND)/100);
684 lowerBound = GetTicks(UINT32_MAX);
687 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
690 higherBound = GetTicks((PresenceTimeOut[index + 1] *
691 cbNode->presence->TTL *
692 MILLISECONDS_PER_SECOND)/100);
696 higherBound = GetTicks(UINT32_MAX);
699 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
701 OC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
702 OC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
703 OC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
706 cbNode->presence->TTLlevel = 0;
708 OC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
712 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
714 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
716 return OC_RSRVD_TRIGGER_CREATE;
718 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
720 return OC_RSRVD_TRIGGER_CHANGE;
724 return OC_RSRVD_TRIGGER_DELETE;
728 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
732 return OC_PRESENCE_TRIGGER_CREATE;
734 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
736 return OC_PRESENCE_TRIGGER_CREATE;
738 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
740 return OC_PRESENCE_TRIGGER_CHANGE;
744 return OC_PRESENCE_TRIGGER_DELETE;
749 * The cononical presence allows constructed URIs to be string compared.
751 * requestUri must be a char array of size CA_MAX_URI_LENGTH
753 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
756 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
757 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
758 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
760 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
762 if (ep->adapter == CA_ADAPTER_IP)
764 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
766 if ('\0' == ep->addr[0]) // multicast
768 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
772 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
773 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
778 if ('\0' == ep->addr[0]) // multicast
780 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
781 ep->port = OC_MULTICAST_PORT;
783 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
784 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
788 // might work for other adapters (untested, but better than nothing)
789 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
790 OC_RSRVD_PRESENCE_URI);
794 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
795 const CAResponseInfo_t *responseInfo)
797 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
798 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
800 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
801 ClientCB * cbNode = NULL;
802 char *resourceTypeName = NULL;
803 OCClientResponse response = {};
804 OCStackResult result = OC_STACK_ERROR;
807 char presenceUri[CA_MAX_URI_LENGTH];
809 int presenceSubscribe = 0;
810 int multicastPresenceSubscribe = 0;
812 if (responseInfo->result != CA_SUCCESS)
814 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
815 return OC_STACK_ERROR;
818 // check for unicast presence
819 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
820 if (uriLen < 0 || uriLen >= sizeof (presenceUri))
822 return OC_STACK_INVALID_URI;
825 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
828 presenceSubscribe = 1;
832 // check for multiicast presence
833 CAEndpoint_t ep = { endpoint->adapter, endpoint->flags };
834 OICStrcpy(ep.addr, sizeof(ep.addr), OC_MULTICAST_IP);
835 ep.port = OC_MULTICAST_PORT;
837 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
839 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
842 multicastPresenceSubscribe = 1;
846 if (!presenceSubscribe && !multicastPresenceSubscribe)
848 OC_LOG(ERROR, TAG, PCF("Received a presence notification, but no callback, ignoring"));
852 response.payload = NULL;
853 response.result = OC_STACK_OK;
855 CopyEndpointToDevAddr(endpoint, &response.devAddr);
856 FixUpClientResponse(&response);
858 if (responseInfo->info.payload)
860 result = OCParsePayload(&response.payload, responseInfo->info.payload,
861 responseInfo->info.payloadSize);
863 if(result != OC_STACK_OK)
865 OC_LOG(ERROR, TAG, PCF("Presence parse failed"));
868 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
870 OC_LOG(ERROR, TAG, PCF("Presence payload was wrong type"));
871 result = OC_STACK_ERROR;
874 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
875 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
876 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
879 if (presenceSubscribe)
881 if(cbNode->sequenceNumber == response.sequenceNumber)
883 OC_LOG(INFO, TAG, PCF("No presence change"));
889 OC_LOG(INFO, TAG, PCF("Stopping presence"));
890 response.result = OC_STACK_PRESENCE_STOPPED;
893 OICFree(cbNode->presence->timeOut);
894 OICFree(cbNode->presence);
895 cbNode->presence = NULL;
900 if(!cbNode->presence)
902 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
904 if(!(cbNode->presence))
906 OC_LOG(ERROR, TAG, PCF("Could not allocate memory for cbNode->presence"));
907 result = OC_STACK_NO_MEMORY;
911 VERIFY_NON_NULL_V(cbNode->presence);
912 cbNode->presence->timeOut = NULL;
913 cbNode->presence->timeOut = (uint32_t *)
914 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
915 if(!(cbNode->presence->timeOut)){
917 PCF("Could not allocate memory for cbNode->presence->timeOut"));
918 OICFree(cbNode->presence);
919 result = OC_STACK_NO_MEMORY;
924 ResetPresenceTTL(cbNode, maxAge);
926 cbNode->sequenceNumber = response.sequenceNumber;
928 // Ensure that a filter is actually applied.
929 if( resourceTypeName && cbNode->filterResourceType)
931 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
940 // This is the multicast case
941 OCMulticastNode* mcNode = NULL;
942 mcNode = GetMCPresenceNode(presenceUri);
946 if(mcNode->nonce == response.sequenceNumber)
948 OC_LOG(INFO, TAG, PCF("No presence change (Multicast)"));
951 mcNode->nonce = response.sequenceNumber;
955 OC_LOG(INFO, TAG, PCF("Stopping presence"));
956 response.result = OC_STACK_PRESENCE_STOPPED;
961 char* uri = OICStrdup(presenceUri);
965 PCF("No Memory for URI to store in the presence node"));
966 result = OC_STACK_NO_MEMORY;
970 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
971 if(result == OC_STACK_NO_MEMORY)
974 PCF("No Memory for Multicast Presence Node"));
978 // presence node now owns uri
981 // Ensure that a filter is actually applied.
982 if(resourceTypeName && cbNode->filterResourceType)
984 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
991 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
993 if (cbResult == OC_STACK_DELETE_TRANSACTION)
995 FindAndDeleteClientCB(cbNode);
999 OCPayloadDestroy(response.payload);
1003 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1005 VERIFY_NON_NULL_NR(endPoint, FATAL);
1006 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1008 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
1010 if(responseInfo->info.resourceUri &&
1011 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1013 HandlePresenceResponse(endPoint, responseInfo);
1017 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1018 responseInfo->info.tokenLength, NULL, NULL);
1020 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1021 responseInfo->info.tokenLength);
1025 OC_LOG(INFO, TAG, PCF("There is a cbNode associated with the response token"));
1026 if(responseInfo->result == CA_EMPTY)
1028 OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
1029 // We do not have a case for the client to receive a RESET
1030 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1032 //This is the case of receiving an ACK on a request to a slow resource!
1033 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
1034 //TODO: should we inform the client
1035 // app that at least the request was received at the server?
1038 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1040 OC_LOG(INFO, TAG, PCF("Receiving A Timeout for this token"));
1041 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1043 OCClientResponse response = {};
1044 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1045 FixUpClientResponse(&response);
1046 response.resourceUri = responseInfo->info.resourceUri;
1048 response.result = CAToOCStackResult(responseInfo->result);
1049 cbNode->callBack(cbNode->context,
1050 cbNode->handle, &response);
1051 FindAndDeleteClientCB(cbNode);
1055 OC_LOG(INFO, TAG, PCF("This is a regular response, A client call back is found"));
1056 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1058 OCClientResponse response = {};
1059 response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1060 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1061 FixUpClientResponse(&response);
1062 response.resourceUri = responseInfo->info.resourceUri;
1064 response.result = CAToOCStackResult(responseInfo->result);
1065 if(responseInfo->info.payload &&
1066 responseInfo->info.payloadSize &&
1067 OC_STACK_OK != OCParsePayload(&response.payload, responseInfo->info.payload,
1068 responseInfo->info.payloadSize))
1070 OC_LOG(ERROR, TAG, PCF("Error converting payload"));
1071 OCPayloadDestroy(response.payload);
1075 response.numRcvdVendorSpecificHeaderOptions = 0;
1076 if(responseInfo->info.numOptions > 0)
1079 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1080 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1082 memcpy (&(response.sequenceNumber),
1083 &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
1084 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1089 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1092 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1094 OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
1095 OCPayloadDestroy(response.payload);
1099 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1101 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1102 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1106 if (cbNode->method == OC_REST_OBSERVE &&
1107 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1108 response.sequenceNumber <= cbNode->sequenceNumber)
1110 OC_LOG_V(INFO, TAG, PCF("Received stale notification. Number :%d"),
1111 response.sequenceNumber);
1115 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1118 cbNode->sequenceNumber = response.sequenceNumber;
1120 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1122 FindAndDeleteClientCB(cbNode);
1126 // To keep discovery callbacks active.
1127 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1128 MILLISECONDS_PER_SECOND);
1132 //Need to send ACK when the response is CON
1133 if(responseInfo->info.type == CA_MSG_CONFIRM)
1135 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1136 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0);
1139 OCPayloadDestroy(response.payload);
1146 OC_LOG(INFO, TAG, PCF("There is an observer associated with the response token"));
1147 if(responseInfo->result == CA_EMPTY)
1149 OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
1150 if(responseInfo->info.type == CA_MSG_RESET)
1152 OC_LOG(INFO, TAG, PCF("This is a RESET"));
1153 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1154 OC_OBSERVER_NOT_INTERESTED);
1156 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1158 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
1159 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1160 OC_OBSERVER_STILL_INTERESTED);
1163 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1165 OC_LOG(INFO, TAG, PCF("Receiving Time Out for an observer"));
1166 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1167 OC_OBSERVER_FAILED_COMM);
1172 if(!cbNode && !observer)
1174 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER)
1176 OC_LOG(INFO, TAG, PCF("This is a client, but no cbNode was found for token"));
1177 if(responseInfo->result == CA_EMPTY)
1179 OC_LOG(INFO, TAG, PCF("Receiving CA_EMPTY in the ocstack"));
1183 OC_LOG(INFO, TAG, PCF("Received a message without callbacks. Sending RESET"));
1184 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1185 CA_MSG_RESET, 0, NULL, NULL, 0);
1189 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
1191 OC_LOG(INFO, TAG, PCF("This is a server, but no observer was found for token"));
1192 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1194 OC_LOG_V(INFO, TAG, PCF("Received ACK at server for messageId : %d"),
1195 responseInfo->info.messageId);
1197 if (responseInfo->info.type == CA_MSG_RESET)
1199 OC_LOG_V(INFO, TAG, PCF("Received RESET at server for messageId : %d"),
1200 responseInfo->info.messageId);
1207 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
1211 * This function handles error response from CA
1212 * code shall be added to handle the errors
1214 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1216 OC_LOG(INFO, TAG, PCF("Enter HandleCAErrorResponse"));
1218 if(NULL == endPoint)
1220 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1224 if(NULL == errrorInfo)
1226 OC_LOG(ERROR, TAG, PCF("errrorInfo is NULL"));
1229 OC_LOG(INFO, TAG, PCF("Exit HandleCAErrorResponse"));
1233 * This function sends out Direct Stack Responses. These are responses that are not coming
1234 * from the application entity handler. These responses have no payload and are usually ACKs,
1235 * RESETs or some error conditions that were caught by the stack.
1237 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1238 const CAResponseResult_t responseResult, const CAMessageType_t type,
1239 const uint8_t numOptions, const CAHeaderOption_t *options,
1240 CAToken_t token, uint8_t tokenLength)
1242 CAResponseInfo_t respInfo = {};
1243 respInfo.result = responseResult;
1244 respInfo.info.messageId = coapID;
1245 respInfo.info.numOptions = numOptions;
1246 respInfo.info.options = (CAHeaderOption_t*)options;
1247 respInfo.info.payload = NULL;
1248 respInfo.info.token = token;
1249 respInfo.info.tokenLength = tokenLength;
1250 respInfo.info.type = type;
1252 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1253 if(caResult != CA_STATUS_OK)
1255 OC_LOG(ERROR, TAG, PCF("CASendResponse error"));
1256 return OC_STACK_ERROR;
1261 //This function will be called back by CA layer when a request is received
1262 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1264 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
1267 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1273 OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
1277 OCStackResult requestResult = OC_STACK_ERROR;
1279 if(myStackMode == OC_CLIENT)
1281 //TODO: should the client be responding to requests?
1285 OCServerProtocolRequest serverRequest = {};
1287 OC_LOG_V(INFO, TAG, PCF("Endpoint URI : %s"), requestInfo->info.resourceUri);
1289 char * uriWithoutQuery = NULL;
1290 char * query = NULL;
1292 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1294 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1296 OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1299 OC_LOG_V(INFO, TAG, PCF("URI without query: %s"), uriWithoutQuery);
1300 OC_LOG_V(INFO, TAG, PCF("Query : %s"), query);
1302 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1304 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1305 OICFree(uriWithoutQuery);
1309 OC_LOG(ERROR, TAG, PCF("URI length exceeds MAX_URI_LENGTH."));
1310 OICFree(uriWithoutQuery);
1317 if(strlen(query) < MAX_QUERY_LENGTH)
1319 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1324 OC_LOG(ERROR, TAG, PCF("Query length exceeds MAX_QUERY_LENGTH."));
1330 if (requestInfo->info.payload)
1332 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1333 memcpy (&(serverRequest.payload), requestInfo->info.payload,
1334 requestInfo->info.payloadSize);
1338 serverRequest.reqTotalSize = 0;
1341 switch (requestInfo->method)
1344 serverRequest.method = OC_REST_GET;
1347 serverRequest.method = OC_REST_PUT;
1350 serverRequest.method = OC_REST_POST;
1353 serverRequest.method = OC_REST_DELETE;
1356 OC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1357 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1358 requestInfo->info.type, requestInfo->info.numOptions,
1359 requestInfo->info.options, requestInfo->info.token,
1360 requestInfo->info.tokenLength);
1364 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1365 requestInfo->info.tokenLength);
1366 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1367 serverRequest.tokenLength = requestInfo->info.tokenLength;
1369 if (!serverRequest.requestToken)
1371 OC_LOG(FATAL, TAG, "Allocation for token failed.");
1372 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1373 requestInfo->info.type, requestInfo->info.numOptions,
1374 requestInfo->info.options, requestInfo->info.token,
1375 requestInfo->info.tokenLength);
1378 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1380 if (requestInfo->info.type == CA_MSG_CONFIRM)
1382 serverRequest.qos = OC_HIGH_QOS;
1386 serverRequest.qos = OC_LOW_QOS;
1388 // CA does not need the following field
1389 // Are we sure CA does not need them? how is it responding to multicast
1390 serverRequest.delayedResNeeded = 0;
1392 serverRequest.coapID = requestInfo->info.messageId;
1394 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1396 // copy vendor specific header options
1397 uint8_t tempNum = (requestInfo->info.numOptions);
1398 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1399 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1402 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
1403 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1404 requestInfo->info.type, requestInfo->info.numOptions,
1405 requestInfo->info.options, requestInfo->info.token,
1406 requestInfo->info.tokenLength);
1407 OICFree(serverRequest.requestToken);
1410 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1411 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1413 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1414 sizeof(CAHeaderOption_t)*tempNum);
1417 requestResult = HandleStackRequests (&serverRequest);
1419 // Send ACK to client as precursor to slow response
1420 if(requestResult == OC_STACK_SLOW_RESOURCE)
1422 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1423 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0);
1425 else if(requestResult != OC_STACK_OK)
1427 OC_LOG_V(ERROR, TAG, PCF("HandleStackRequests failed. error: %d"), requestResult);
1429 CAResponseResult_t stackResponse = OCToCAStackResult(requestResult);
1431 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1432 requestInfo->info.type, requestInfo->info.numOptions,
1433 requestInfo->info.options, requestInfo->info.token,
1434 requestInfo->info.tokenLength);
1436 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1437 // The token is copied in there, and is thus still owned by this function.
1438 OICFree(serverRequest.requestToken);
1439 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
1442 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1444 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
1445 OCStackResult result = OC_STACK_ERROR;
1446 ResourceHandling resHandling;
1447 OCResource *resource;
1448 if(!protocolRequest)
1450 OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
1451 return OC_STACK_INVALID_PARAM;
1454 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1455 protocolRequest->tokenLength);
1458 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
1459 result = AddServerRequest(&request, protocolRequest->coapID,
1460 protocolRequest->delayedResNeeded, 0,
1461 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
1462 protocolRequest->observationOption, protocolRequest->qos,
1463 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1464 protocolRequest->payload, protocolRequest->requestToken,
1465 protocolRequest->tokenLength,
1466 protocolRequest->resourceUrl, protocolRequest->reqTotalSize,
1467 &protocolRequest->devAddr);
1468 if (OC_STACK_OK != result)
1470 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
1476 OC_LOG(ERROR, TAG, PCF("Out of Memory"));
1477 return OC_STACK_NO_MEMORY;
1480 if(!protocolRequest->reqMorePacket)
1482 request->requestComplete = 1;
1487 OC_LOG(INFO, TAG, PCF("This is either a repeated or blocked Server Request"));
1490 if(request->requestComplete)
1492 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
1493 result = DetermineResourceHandling (request, &resHandling, &resource);
1494 if (result == OC_STACK_OK)
1496 result = ProcessRequest(resHandling, resource, request);
1501 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
1502 result = OC_STACK_CONTINUE;
1507 bool validatePlatformInfo(OCPlatformInfo info)
1510 if (!info.platformID)
1512 OC_LOG(ERROR, TAG, PCF("No platform ID found."));
1516 if (info.manufacturerName)
1518 size_t lenManufacturerName = strlen(info.manufacturerName);
1520 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1522 OC_LOG(ERROR, TAG, PCF("Manufacturer name fails length requirements."));
1528 OC_LOG(ERROR, TAG, PCF("No manufacturer name present"));
1532 if (info.manufacturerUrl)
1534 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1536 OC_LOG(ERROR, TAG, PCF("Manufacturer url fails length requirements."));
1543 //-----------------------------------------------------------------------------
1545 //-----------------------------------------------------------------------------
1547 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1550 !raInfo->username ||
1551 !raInfo->hostname ||
1552 !raInfo->xmpp_domain)
1555 return OC_STACK_INVALID_PARAM;
1557 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1558 gRASetInfo = (result == OC_STACK_OK)? true : false;
1564 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1571 OC_LOG(ERROR, TAG, PCF("Need to call OCSetRAInfo before calling OCInit"));
1572 return OC_STACK_ERROR;
1575 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1578 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1580 if(stackState == OC_STACK_INITIALIZED)
1582 OC_LOG(INFO, TAG, PCF("Subsequent calls to OCInit() without calling \
1583 OCStop() between them are ignored."));
1587 OCStackResult result = OC_STACK_ERROR;
1588 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1591 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)))
1593 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1594 return OC_STACK_ERROR;
1598 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER)
1600 caglobals.client = true;
1602 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER)
1604 caglobals.server = true;
1607 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1608 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
1610 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4);
1612 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
1613 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
1615 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4);
1618 defaultDeviceHandler = NULL;
1619 defaultDeviceHandlerCallbackParameter = NULL;
1622 result = CAResultToOCResult(CAInitialize());
1623 VERIFY_SUCCESS(result, OC_STACK_OK);
1625 result = CAResultToOCResult(OCSelectNetwork());
1626 VERIFY_SUCCESS(result, OC_STACK_OK);
1628 switch (myStackMode)
1631 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1632 result = CAResultToOCResult(CAStartDiscoveryServer());
1633 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1636 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1637 result = CAResultToOCResult(CAStartListeningServer());
1638 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1640 case OC_CLIENT_SERVER:
1641 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1642 result = CAResultToOCResult(CAStartListeningServer());
1643 if(result == OC_STACK_OK)
1645 result = CAResultToOCResult(CAStartDiscoveryServer());
1649 VERIFY_SUCCESS(result, OC_STACK_OK);
1651 #ifdef WITH_PRESENCE
1652 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1653 #endif // WITH_PRESENCE
1655 //Update Stack state to initialized
1656 stackState = OC_STACK_INITIALIZED;
1658 // Initialize resource
1659 if(myStackMode != OC_CLIENT)
1661 result = initResources();
1664 // Initialize the SRM Policy Engine
1665 if(result == OC_STACK_OK)
1667 result = SRMInitPolicyEngine();
1668 // TODO after BeachHead delivery: consolidate into single SRMInit()
1672 if(result != OC_STACK_OK)
1674 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1675 deleteAllResources();
1677 stackState = OC_STACK_UNINITIALIZED;
1682 OCStackResult OCStop()
1684 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1686 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1688 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1691 else if (stackState != OC_STACK_INITIALIZED)
1693 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1694 return OC_STACK_ERROR;
1697 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1699 #ifdef WITH_PRESENCE
1700 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1701 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1702 presenceResource.presenceTTL = 0;
1703 #endif // WITH_PRESENCE
1705 // Free memory dynamically allocated for resources
1706 deleteAllResources();
1708 DeletePlatformInfo();
1710 // Remove all observers
1711 DeleteObserverList();
1712 // Remove all the client callbacks
1713 DeleteClientCBList();
1715 // De-init the SRM Policy Engine
1716 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
1717 SRMDeInitPolicyEngine();
1720 stackState = OC_STACK_UNINITIALIZED;
1724 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1729 return CA_MSG_CONFIRM;
1734 return CA_MSG_NONCONFIRM;
1738 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1742 query = strchr (inputUri, '?');
1746 if((query - inputUri) > MAX_URI_LENGTH)
1748 return OC_STACK_INVALID_URI;
1751 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1753 return OC_STACK_INVALID_QUERY;
1756 else if(uriLen > MAX_URI_LENGTH)
1758 return OC_STACK_INVALID_URI;
1764 * A request uri consists of the following components in order:
1766 * optional prefix "coap://"
1768 * IPv6 address "[1234::5678]"
1769 * IPv4 address "192.168.1.1"
1770 * optional port ":5683"
1771 * resource uri "/oc/core..."
1773 * for PRESENCE requests, extract resource type.
1775 static OCStackResult ParseRequestUri(const char *fullUri,
1776 OCTransportAdapter adapter,
1777 OCTransportFlags flags,
1778 OCDevAddr **devAddr,
1780 char **resourceType)
1782 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
1784 OCStackResult result = OC_STACK_OK;
1785 OCDevAddr *da = NULL;
1789 // provide defaults for all returned values
1796 *resourceUri = NULL;
1800 *resourceType = NULL;
1803 // delimit url prefix, if any
1804 const char *start = fullUri;
1805 char *slash2 = strstr(start, "//");
1810 char *slash = strchr(start, '/');
1813 return OC_STACK_INVALID_URI;
1816 // processs url prefix, if any
1817 size_t urlLen = slash - start;
1821 if (urlLen && devAddr)
1822 { // construct OCDevAddr
1823 if (OC_ADAPTER_IP == adapter)
1825 if (start[0] == '[')
1827 char *close = strchr(++start, ']');
1828 if (!close || close > slash)
1830 return OC_STACK_INVALID_URI;
1833 if (close[1] == ':')
1841 colon = strchr(start, ':');
1842 end = (colon && colon < slash) ? colon : slash;
1845 if (len >= sizeof(da->addr))
1847 return OC_STACK_INVALID_URI;
1849 // collect port, if any
1850 if (colon && colon < slash)
1852 for (colon++; colon < slash; colon++)
1855 if (c < '0' || c > '9')
1857 return OC_STACK_INVALID_URI;
1859 port = 10 * port + c - '0';
1866 * This is for Non-IP adapters(EDR and BLE).
1867 * The address will be between "//" and "/" in the request URI.
1868 * [Ex. coap://AB:BC:CD:DE:EF:FG/resource_uri]
1874 if (len >= sizeof(da->addr))
1876 return OC_STACK_INVALID_URI;
1879 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
1882 return OC_STACK_NO_MEMORY;
1884 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
1886 da->adapter = adapter;
1888 if (!strncmp(fullUri, "coaps:", 6))
1890 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
1895 // process resource uri, if any
1897 { // request uri and query
1898 size_t ulen = strlen(slash); // resource uri length
1899 size_t tlen = 0; // resource type length
1902 static const char strPresence[] = "/oic/ad?rt=";
1903 static const size_t lenPresence = sizeof(strPresence) - 1;
1904 if (!strncmp(slash, strPresence, lenPresence))
1906 type = slash + lenPresence;
1907 tlen = ulen - lenPresence;
1912 *resourceUri = (char *)OICMalloc(ulen + 1);
1915 result = OC_STACK_NO_MEMORY;
1918 strcpy(*resourceUri, slash);
1921 if (type && resourceType)
1923 *resourceType = (char *)OICMalloc(tlen + 1);
1926 result = OC_STACK_NO_MEMORY;
1930 OICStrcpy(*resourceType, (tlen+1), type);
1937 // free all returned values
1944 OICFree(*resourceUri);
1948 OICFree(*resourceType);
1953 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
1954 char *resourceUri, char **requestUri)
1956 char uri[CA_MAX_URI_LENGTH];
1958 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
1960 *requestUri = OICStrdup(uri);
1963 return OC_STACK_NO_MEMORY;
1970 * Discover or Perform requests on a specified resource
1972 OCStackResult OCDoResource(OCDoHandle *handle,
1974 const char *requestUri,
1975 const OCDevAddr *destination,
1977 OCConnectivityType connectivityType,
1978 OCQualityOfService qos,
1979 OCCallbackData *cbData,
1980 OCHeaderOption *options,
1983 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1985 // Validate input parameters
1986 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1987 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1988 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
1990 OCStackResult result = OC_STACK_ERROR;
1991 CAResult_t caResult;
1992 CAToken_t token = NULL;
1993 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
1994 ClientCB *clientCB = NULL;
1995 OCDoHandle resHandle = NULL;
1996 CAEndpoint_t *endpoint = NULL;
1997 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
1999 OCTransportAdapter adapter;
2000 OCTransportFlags flags;
2001 // the request contents are put here
2002 CARequestInfo_t requestInfo = { CA_GET };
2003 // requestUri will be parsed into the following three variables
2004 OCDevAddr *devAddr = NULL;
2005 char *resourceUri = NULL;
2006 char *resourceType = NULL;
2008 // To track if memory is allocated for additional header options
2009 uint8_t hdrOptionMemAlloc = 0;
2011 // This validation is broken, but doesn't cause harm
2012 size_t uriLen = strlen(requestUri );
2013 if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
2019 * Support original behavior with address on resourceUri argument.
2021 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2022 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2024 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2026 if (result != OC_STACK_OK)
2028 OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2035 case OC_REST_OBSERVE:
2036 case OC_REST_OBSERVE_ALL:
2037 case OC_REST_CANCEL_OBSERVE:
2038 requestInfo.method = CA_GET;
2041 requestInfo.method = CA_PUT;
2044 requestInfo.method = CA_POST;
2046 case OC_REST_DELETE:
2047 requestInfo.method = CA_DELETE;
2049 case OC_REST_DISCOVER:
2051 if (destination || devAddr)
2053 requestInfo.isMulticast = false;
2057 destination = &tmpDevAddr;
2058 requestInfo.isMulticast = true;
2060 // CA_DISCOVER will become GET and isMulticast
2061 requestInfo.method = CA_GET;
2063 #ifdef WITH_PRESENCE
2064 case OC_REST_PRESENCE:
2065 // Replacing method type with GET because "presence"
2066 // is a stack layer only implementation.
2067 requestInfo.method = CA_GET;
2071 result = OC_STACK_INVALID_METHOD;
2075 if (!devAddr && !destination)
2077 OC_LOG_V(DEBUG, TAG, "no devAddr and no destination");
2078 result = OC_STACK_INVALID_PARAM;
2082 /* If not original behavior, use destination argument */
2083 if (destination && !devAddr)
2085 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2088 result = OC_STACK_NO_MEMORY;
2091 *devAddr = *destination;
2094 resHandle = GenerateInvocationHandle();
2097 result = OC_STACK_NO_MEMORY;
2101 caResult = CAGenerateToken(&token, tokenLength);
2102 if (caResult != CA_STATUS_OK)
2104 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2105 result= OC_STACK_ERROR;
2109 // fill in request data
2110 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2111 requestInfo.info.token = token;
2112 requestInfo.info.tokenLength = tokenLength;
2113 requestInfo.info.resourceUri = resourceUri;
2115 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2117 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2118 options, numOptions, OC_OBSERVE_REGISTER);
2119 if (result != OC_STACK_OK)
2123 hdrOptionMemAlloc = 1;
2124 requestInfo.info.numOptions = numOptions + 1;
2128 requestInfo.info.options = (CAHeaderOption_t*)options;
2129 requestInfo.info.numOptions = numOptions;
2132 // create remote endpoint
2133 result = OCCreateEndpoint(devAddr, &endpoint);
2137 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2140 OC_LOG(ERROR, TAG, PCF("Failed to create CBOR Payload"));
2146 requestInfo.info.payload = NULL;
2147 requestInfo.info.payloadSize = 0;
2152 if (result != OC_STACK_OK)
2154 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2158 // prepare for response
2159 #ifdef WITH_PRESENCE
2160 if (method == OC_REST_PRESENCE)
2162 char *presenceUri = NULL;
2163 result = OCPreparePresence(endpoint, resourceUri, &presenceUri);
2164 if (OC_STACK_OK != result)
2169 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2170 // Presence notification will form a canonical uri to
2171 // look for callbacks into the application.
2172 resourceUri = presenceUri;
2176 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2177 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2178 method, devAddr, resourceUri, resourceType, ttl);
2179 if (OC_STACK_OK != result)
2184 devAddr = NULL; // Client CB list entry now owns it
2185 resourceUri = NULL; // Client CB list entry now owns it
2186 resourceType = NULL; // Client CB list entry now owns it
2189 caResult = CASendRequest(endpoint, &requestInfo);
2190 if (caResult != CA_STATUS_OK)
2192 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
2193 result = OC_STACK_COMM_ERROR;
2199 *handle = resHandle;
2203 if (result != OC_STACK_OK)
2205 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
2206 FindAndDeleteClientCB(clientCB);
2207 CADestroyToken(token);
2215 // This is the owner of the payload object, so we free it
2216 OCPayloadDestroy(payload);
2217 OICFree(requestInfo.info.payload);
2219 OICFree(resourceUri);
2220 OICFree(resourceType);
2222 if (hdrOptionMemAlloc)
2224 OICFree(requestInfo.info.options);
2229 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2233 * This ftn is implemented one of two ways in the case of observation:
2235 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2236 * Remove the callback associated on client side.
2237 * When the next notification comes in from server,
2238 * reply with RESET message to server.
2239 * Keep in mind that the server will react to RESET only
2240 * if the last notification was sent as CON
2242 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2243 * and it is associated with an observe request
2244 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2245 * Send CON Observe request to server with
2246 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2247 * Remove the callback associated on client side.
2249 OCStackResult ret = OC_STACK_OK;
2250 CAEndpoint_t* endpoint = NULL;
2251 CAResult_t caResult;
2252 CAInfo_t requestData = {};
2253 CARequestInfo_t requestInfo = {};
2257 return OC_STACK_INVALID_PARAM;
2260 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2263 OC_LOG(ERROR, TAG, PCF("Client callback not found. Called OCCancel twice?"));
2267 switch (clientCB->method)
2269 case OC_REST_OBSERVE:
2270 case OC_REST_OBSERVE_ALL:
2271 OC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
2272 clientCB->requestUri);
2273 if (qos != OC_HIGH_QOS)
2275 FindAndDeleteClientCB(clientCB);
2280 OC_LOG(INFO, TAG, PCF("Cancelling observation as CONFIRMABLE"));
2283 requestData.type = qualityOfServiceToMessageType(qos);
2284 requestData.token = clientCB->token;
2285 requestData.tokenLength = clientCB->tokenLength;
2286 if (CreateObserveHeaderOption (&(requestData.options),
2287 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2289 return OC_STACK_ERROR;
2291 requestData.numOptions = numOptions + 1;
2292 requestData.resourceUri = OICStrdup (clientCB->requestUri);
2294 requestInfo.method = CA_GET;
2295 requestInfo.info = requestData;
2297 ret = OCCreateEndpoint(clientCB->devAddr, &endpoint);
2298 if (ret != OC_STACK_OK)
2300 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2305 caResult = CASendRequest(endpoint, &requestInfo);
2306 if (caResult != CA_STATUS_OK)
2308 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2309 ret = OC_STACK_ERROR;
2311 ret = CAResultToOCResult (caResult);
2314 #ifdef WITH_PRESENCE
2315 case OC_REST_PRESENCE:
2316 FindAndDeleteClientCB(clientCB);
2321 ret = OC_STACK_INVALID_METHOD;
2326 OCDestroyEndpoint(endpoint);
2327 if (requestData.numOptions > 0)
2329 OICFree(requestData.options);
2331 if (requestData.resourceUri)
2333 OICFree (requestData.resourceUri);
2340 * @brief Register Persistent storage callback.
2341 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2343 * OC_STACK_OK - No errors; Success
2344 * OC_STACK_INVALID_PARAM - Invalid parameter
2346 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2348 OC_LOG(INFO, TAG, PCF("RegisterPersistentStorageHandler !!"));
2349 if(!persistentStorageHandler)
2351 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2352 return OC_STACK_INVALID_PARAM;
2356 if( !persistentStorageHandler->open ||
2357 !persistentStorageHandler->close ||
2358 !persistentStorageHandler->read ||
2359 !persistentStorageHandler->unlink ||
2360 !persistentStorageHandler->write)
2362 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2363 return OC_STACK_INVALID_PARAM;
2366 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2369 #ifdef WITH_PRESENCE
2371 OCStackResult OCProcessPresence()
2373 OCStackResult result = OC_STACK_OK;
2375 // the following line floods the log with messages that are irrelevant
2376 // to most purposes. Uncomment as needed.
2377 //OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
2378 ClientCB* cbNode = NULL;
2379 OCClientResponse clientResponse;
2380 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2382 LL_FOREACH(cbList, cbNode)
2384 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2389 uint32_t now = GetTicks(0);
2390 OC_LOG_V(DEBUG, TAG, "this TTL level %d",
2391 cbNode->presence->TTLlevel);
2392 OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2394 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
2399 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2401 OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2402 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2405 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2407 OC_LOG(DEBUG, TAG, PCF("No more timeout ticks"));
2409 clientResponse.sequenceNumber = 0;
2410 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2411 clientResponse.devAddr = *cbNode->devAddr;
2412 FixUpClientResponse(&clientResponse);
2413 clientResponse.payload = NULL;
2415 // Increment the TTLLevel (going to a next state), so we don't keep
2416 // sending presence notification to client.
2417 cbNode->presence->TTLlevel++;
2418 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2419 cbNode->presence->TTLlevel);
2421 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2422 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2424 FindAndDeleteClientCB(cbNode);
2428 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2433 CAResult_t caResult = CA_STATUS_OK;
2434 CAEndpoint_t* endpoint = NULL;
2435 CAInfo_t requestData ={};
2436 CARequestInfo_t requestInfo = {};
2438 OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
2440 result = OCCreateEndpoint(cbNode->devAddr, &endpoint);
2441 if (result != OC_STACK_OK)
2443 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2447 requestData.type = CA_MSG_NONCONFIRM;
2448 requestData.token = cbNode->token;
2449 requestData.tokenLength = cbNode->tokenLength;
2450 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2451 requestInfo.method = CA_GET;
2452 requestInfo.info = requestData;
2454 caResult = CASendRequest(endpoint, &requestInfo);
2455 OCDestroyEndpoint(endpoint);
2457 if (caResult != CA_STATUS_OK)
2459 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2463 cbNode->presence->TTLlevel++;
2464 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2467 if (result != OC_STACK_OK)
2469 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2473 #endif // WITH_PRESENCE
2475 OCStackResult OCProcess()
2477 #ifdef WITH_PRESENCE
2478 OCProcessPresence();
2480 CAHandleRequestResponse();
2485 #ifdef WITH_PRESENCE
2486 OCStackResult OCStartPresence(const uint32_t ttl)
2488 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2489 OCChangeResourceProperty(
2490 &(((OCResource *)presenceResource.handle)->resourceProperties),
2493 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2495 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2496 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to max value"));
2500 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2501 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to default value"));
2505 presenceResource.presenceTTL = ttl;
2507 OC_LOG_V(DEBUG, TAG, "Presence TTL is %lu seconds", presenceResource.presenceTTL);
2509 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2511 presenceState = OC_PRESENCE_INITIALIZED;
2513 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2514 OICStrcpy(devAddr.addr, sizeof(devAddr.addr), OC_MULTICAST_IP);
2515 devAddr.port = OC_MULTICAST_PORT;
2517 CAToken_t caToken = NULL;
2518 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2519 if (caResult != CA_STATUS_OK)
2521 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2522 CADestroyToken(caToken);
2523 return OC_STACK_ERROR;
2526 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2527 (OCResource *)presenceResource.handle, OC_LOW_QOS, &devAddr);
2528 CADestroyToken(caToken);
2531 // Each time OCStartPresence is called
2532 // a different random 32-bit integer number is used
2533 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2535 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2536 OC_PRESENCE_TRIGGER_CREATE);
2539 OCStackResult OCStopPresence()
2541 OCStackResult result = OC_STACK_ERROR;
2543 if(presenceResource.handle)
2545 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2547 // make resource inactive
2548 result = OCChangeResourceProperty(
2549 &(((OCResource *) presenceResource.handle)->resourceProperties),
2553 if(result != OC_STACK_OK)
2556 PCF("Changing the presence resource properties to ACTIVE not successful"));
2560 return SendStopNotification();
2564 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
2565 void* callbackParameter)
2567 defaultDeviceHandler = entityHandler;
2568 defaultDeviceHandlerCallbackParameter = callbackParameter;
2573 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
2575 OC_LOG(INFO, TAG, PCF("Entering OCSetPlatformInfo"));
2577 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
2579 if (validatePlatformInfo(platformInfo))
2581 return SavePlatformInfo(platformInfo);
2585 return OC_STACK_INVALID_PARAM;
2590 return OC_STACK_ERROR;
2594 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2596 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2598 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
2600 OC_LOG(ERROR, TAG, PCF("Null or empty device name."));
2601 return OC_STACK_INVALID_PARAM;
2604 return SaveDeviceInfo(deviceInfo);
2607 OCStackResult OCCreateResource(OCResourceHandle *handle,
2608 const char *resourceTypeName,
2609 const char *resourceInterfaceName,
2610 const char *uri, OCEntityHandler entityHandler,
2611 void* callbackParam,
2612 uint8_t resourceProperties)
2615 OCResource *pointer = NULL;
2617 OCStackResult result = OC_STACK_ERROR;
2619 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2621 if(myStackMode == OC_CLIENT)
2623 return OC_STACK_INVALID_PARAM;
2625 // Validate parameters
2626 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2628 OC_LOG(ERROR, TAG, PCF("URI is empty or too long"));
2629 return OC_STACK_INVALID_URI;
2631 // Is it presented during resource discovery?
2632 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
2634 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2635 return OC_STACK_INVALID_PARAM;
2638 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2640 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2643 // Make sure resourceProperties bitmask has allowed properties specified
2644 if (resourceProperties
2645 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
2646 OC_EXPLICIT_DISCOVERABLE))
2648 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2649 return OC_STACK_INVALID_PARAM;
2652 // If the headResource is NULL, then no resources have been created...
2653 pointer = headResource;
2656 // At least one resources is in the resource list, so we need to search for
2657 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2660 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
2662 OC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
2663 return OC_STACK_INVALID_PARAM;
2665 pointer = pointer->next;
2668 // Create the pointer and insert it into the resource list
2669 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
2672 result = OC_STACK_NO_MEMORY;
2675 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2677 insertResource(pointer);
2680 str = OICStrdup(uri);
2683 result = OC_STACK_NO_MEMORY;
2688 // Set properties. Set OC_ACTIVE
2689 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2692 // Add the resourcetype to the resource
2693 result = BindResourceTypeToResource(pointer, resourceTypeName);
2694 if (result != OC_STACK_OK)
2696 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2700 // Add the resourceinterface to the resource
2701 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2702 if (result != OC_STACK_OK)
2704 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2708 // If an entity handler has been passed, attach it to the newly created
2709 // resource. Otherwise, set the default entity handler.
2712 pointer->entityHandler = entityHandler;
2713 pointer->entityHandlerCallbackParam = callbackParam;
2717 pointer->entityHandler = defaultResourceEHandler;
2718 pointer->entityHandlerCallbackParam = NULL;
2722 result = OC_STACK_OK;
2724 #ifdef WITH_PRESENCE
2725 if(presenceResource.handle)
2727 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2728 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
2732 if (result != OC_STACK_OK)
2734 // Deep delete of resource and other dynamic elements that it contains
2735 deleteResource(pointer);
2742 OCStackResult OCBindResource(
2743 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2745 OCResource *resource = NULL;
2748 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2750 // Validate parameters
2751 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2752 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2753 // Container cannot contain itself
2754 if (collectionHandle == resourceHandle)
2756 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2757 return OC_STACK_INVALID_PARAM;
2760 // Use the handle to find the resource in the resource linked list
2761 resource = findResource((OCResource *) collectionHandle);
2764 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2765 return OC_STACK_INVALID_PARAM;
2768 // Look for an open slot to add add the child resource.
2769 // If found, add it and return success
2770 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2772 if (!resource->rsrcResources[i])
2774 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2775 OC_LOG(INFO, TAG, PCF("resource bound"));
2777 #ifdef WITH_PRESENCE
2778 if(presenceResource.handle)
2780 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2781 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2782 OC_PRESENCE_TRIGGER_CHANGE);
2790 // Unable to add resourceHandle, so return error
2791 return OC_STACK_ERROR;
2794 OCStackResult OCUnBindResource(
2795 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2797 OCResource *resource = NULL;
2800 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2802 // Validate parameters
2803 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2804 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2805 // Container cannot contain itself
2806 if (collectionHandle == resourceHandle)
2808 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2809 return OC_STACK_INVALID_PARAM;
2812 // Use the handle to find the resource in the resource linked list
2813 resource = findResource((OCResource *) collectionHandle);
2816 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2817 return OC_STACK_INVALID_PARAM;
2820 // Look for an open slot to add add the child resource.
2821 // If found, add it and return success
2822 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2824 if (resourceHandle == resource->rsrcResources[i])
2826 resource->rsrcResources[i] = (OCResource *) NULL;
2827 OC_LOG(INFO, TAG, PCF("resource unbound"));
2829 // Send notification when resource is unbounded successfully.
2830 #ifdef WITH_PRESENCE
2831 if(presenceResource.handle)
2833 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2834 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2835 OC_PRESENCE_TRIGGER_CHANGE);
2842 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2844 // Unable to add resourceHandle, so return error
2845 return OC_STACK_ERROR;
2848 OCStackResult BindResourceTypeToResource(OCResource* resource,
2849 const char *resourceTypeName)
2851 OCResourceType *pointer = NULL;
2853 OCStackResult result = OC_STACK_ERROR;
2855 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2857 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
2860 result = OC_STACK_NO_MEMORY;
2864 str = OICStrdup(resourceTypeName);
2867 result = OC_STACK_NO_MEMORY;
2870 pointer->resourcetypename = str;
2872 insertResourceType(resource, pointer);
2873 result = OC_STACK_OK;
2876 if (result != OC_STACK_OK)
2885 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2886 const char *resourceInterfaceName)
2888 OCResourceInterface *pointer = NULL;
2890 OCStackResult result = OC_STACK_ERROR;
2892 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2894 OC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
2896 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
2899 result = OC_STACK_NO_MEMORY;
2903 str = OICStrdup(resourceInterfaceName);
2906 result = OC_STACK_NO_MEMORY;
2909 pointer->name = str;
2911 // Bind the resourceinterface to the resource
2912 insertResourceInterface(resource, pointer);
2914 result = OC_STACK_OK;
2917 if (result != OC_STACK_OK)
2926 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2927 const char *resourceTypeName)
2930 OCStackResult result = OC_STACK_ERROR;
2931 OCResource *resource = NULL;
2933 resource = findResource((OCResource *) handle);
2936 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2937 return OC_STACK_ERROR;
2940 result = BindResourceTypeToResource(resource, resourceTypeName);
2942 #ifdef WITH_PRESENCE
2943 if(presenceResource.handle)
2945 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2946 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2953 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2954 const char *resourceInterfaceName)
2957 OCStackResult result = OC_STACK_ERROR;
2958 OCResource *resource = NULL;
2960 resource = findResource((OCResource *) handle);
2963 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2964 return OC_STACK_ERROR;
2967 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2969 #ifdef WITH_PRESENCE
2970 if(presenceResource.handle)
2972 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2973 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2980 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
2982 OCResource *pointer = headResource;
2984 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2988 *numResources = *numResources + 1;
2989 pointer = pointer->next;
2994 OCResourceHandle OCGetResourceHandle(uint8_t index)
2996 OCResource *pointer = headResource;
2998 for( uint8_t i = 0; i < index && pointer; ++i)
3000 pointer = pointer->next;
3002 return (OCResourceHandle) pointer;
3005 OCStackResult OCDeleteResource(OCResourceHandle handle)
3009 OC_LOG(ERROR, TAG, PCF("Invalid handle for deletion"));
3010 return OC_STACK_INVALID_PARAM;
3013 OCResource *resource = findResource((OCResource *) handle);
3014 if (resource == NULL)
3016 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3017 return OC_STACK_NO_RESOURCE;
3020 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3022 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
3023 return OC_STACK_ERROR;
3029 const char *OCGetResourceUri(OCResourceHandle handle)
3031 OCResource *resource = NULL;
3033 resource = findResource((OCResource *) handle);
3036 return resource->uri;
3038 return (const char *) NULL;
3041 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3043 OCResource *resource = NULL;
3045 resource = findResource((OCResource *) handle);
3048 return resource->resourceProperties;
3050 return (OCResourceProperty)-1;
3053 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3054 uint8_t *numResourceTypes)
3056 OCResource *resource = NULL;
3057 OCResourceType *pointer = NULL;
3059 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3060 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3062 *numResourceTypes = 0;
3064 resource = findResource((OCResource *) handle);
3067 pointer = resource->rsrcType;
3070 *numResourceTypes = *numResourceTypes + 1;
3071 pointer = pointer->next;
3077 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3079 OCResourceType *resourceType = NULL;
3081 resourceType = findResourceTypeAtIndex(handle, index);
3084 return resourceType->resourcetypename;
3086 return (const char *) NULL;
3089 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3090 uint8_t *numResourceInterfaces)
3092 OCResourceInterface *pointer = NULL;
3093 OCResource *resource = NULL;
3095 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3096 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3098 *numResourceInterfaces = 0;
3099 resource = findResource((OCResource *) handle);
3102 pointer = resource->rsrcInterface;
3105 *numResourceInterfaces = *numResourceInterfaces + 1;
3106 pointer = pointer->next;
3112 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3114 OCResourceInterface *resourceInterface = NULL;
3116 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3117 if (resourceInterface)
3119 return resourceInterface->name;
3121 return (const char *) NULL;
3124 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3127 OCResource *resource = NULL;
3129 if (index >= MAX_CONTAINED_RESOURCES)
3134 resource = findResource((OCResource *) collectionHandle);
3140 return resource->rsrcResources[index];
3143 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3144 OCEntityHandler entityHandler,
3145 void* callbackParam)
3147 OCResource *resource = NULL;
3149 // Validate parameters
3150 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3152 // Use the handle to find the resource in the resource linked list
3153 resource = findResource((OCResource *)handle);
3156 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3157 return OC_STACK_ERROR;
3161 resource->entityHandler = entityHandler;
3162 resource->entityHandlerCallbackParam = callbackParam;
3164 #ifdef WITH_PRESENCE
3165 if(presenceResource.handle)
3167 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3168 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3175 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3177 OCResource *resource = NULL;
3179 resource = findResource((OCResource *)handle);
3182 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3187 return resource->entityHandler;
3190 void incrementSequenceNumber(OCResource * resPtr)
3192 // Increment the sequence number
3193 resPtr->sequenceNum += 1;
3194 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3196 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3201 #ifdef WITH_PRESENCE
3202 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3203 OCPresenceTrigger trigger)
3205 OCResource *resPtr = NULL;
3206 OCStackResult result = OC_STACK_ERROR;
3207 OCMethod method = OC_REST_PRESENCE;
3208 uint32_t maxAge = 0;
3209 resPtr = findResource((OCResource *) presenceResource.handle);
3212 return OC_STACK_NO_RESOURCE;
3215 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3217 maxAge = presenceResource.presenceTTL;
3219 result = SendAllObserverNotification(method, resPtr, maxAge,
3220 trigger, resourceType, OC_LOW_QOS);
3226 OCStackResult SendStopNotification()
3228 OCResource *resPtr = NULL;
3229 OCStackResult result = OC_STACK_ERROR;
3230 OCMethod method = OC_REST_PRESENCE;
3231 resPtr = findResource((OCResource *) presenceResource.handle);
3234 return OC_STACK_NO_RESOURCE;
3237 // maxAge is 0. ResourceType is NULL.
3238 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3244 #endif // WITH_PRESENCE
3245 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3247 OCResource *resPtr = NULL;
3248 OCStackResult result = OC_STACK_ERROR;
3249 OCMethod method = OC_REST_NOMETHOD;
3250 uint32_t maxAge = 0;
3252 OC_LOG(INFO, TAG, PCF("Notifying all observers"));
3253 #ifdef WITH_PRESENCE
3254 if(handle == presenceResource.handle)
3258 #endif // WITH_PRESENCE
3259 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3261 // Verify that the resource exists
3262 resPtr = findResource ((OCResource *) handle);
3265 return OC_STACK_NO_RESOURCE;
3269 //only increment in the case of regular observing (not presence)
3270 incrementSequenceNumber(resPtr);
3271 method = OC_REST_OBSERVE;
3272 maxAge = MAX_OBSERVE_AGE;
3273 #ifdef WITH_PRESENCE
3274 result = SendAllObserverNotification (method, resPtr, maxAge,
3275 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3277 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3284 OCNotifyListOfObservers (OCResourceHandle handle,
3285 OCObservationId *obsIdList,
3286 uint8_t numberOfIds,
3287 const OCRepPayload *payload,
3288 OCQualityOfService qos)
3290 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3292 OCResource *resPtr = NULL;
3293 //TODO: we should allow the server to define this
3294 uint32_t maxAge = MAX_OBSERVE_AGE;
3296 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3297 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3298 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3300 resPtr = findResource ((OCResource *) handle);
3301 if (NULL == resPtr || myStackMode == OC_CLIENT)
3303 return OC_STACK_NO_RESOURCE;
3307 incrementSequenceNumber(resPtr);
3309 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3310 payload, maxAge, qos));
3313 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3315 OCStackResult result = OC_STACK_ERROR;
3316 OCServerRequest *serverRequest = NULL;
3318 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3320 // Validate input parameters
3321 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3322 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3325 // Get pointer to request info
3326 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3329 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3330 result = serverRequest->ehResponseHandler(ehResponse);
3336 //-----------------------------------------------------------------------------
3337 // Private internal function definitions
3338 //-----------------------------------------------------------------------------
3339 static OCDoHandle GenerateInvocationHandle()
3341 OCDoHandle handle = NULL;
3342 // Generate token here, it will be deleted when the transaction is deleted
3343 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3346 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3352 #ifdef WITH_PRESENCE
3353 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3354 OCResourceProperty resourceProperties, uint8_t enable)
3358 return OC_STACK_INVALID_PARAM;
3360 if (resourceProperties
3361 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3363 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3364 return OC_STACK_INVALID_PARAM;
3368 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3372 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3378 OCStackResult initResources()
3380 OCStackResult result = OC_STACK_OK;
3382 headResource = NULL;
3383 tailResource = NULL;
3384 // Init Virtual Resources
3385 #ifdef WITH_PRESENCE
3386 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3388 result = OCCreateResource(&presenceResource.handle,
3389 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3391 OC_RSRVD_PRESENCE_URI,
3395 //make resource inactive
3396 result = OCChangeResourceProperty(
3397 &(((OCResource *) presenceResource.handle)->resourceProperties),
3401 if (result == OC_STACK_OK)
3403 result = SRMInitSecureResources();
3409 void insertResource(OCResource *resource)
3413 headResource = resource;
3414 tailResource = resource;
3418 tailResource->next = resource;
3419 tailResource = resource;
3421 resource->next = NULL;
3424 OCResource *findResource(OCResource *resource)
3426 OCResource *pointer = headResource;
3430 if (pointer == resource)
3434 pointer = pointer->next;
3439 void deleteAllResources()
3441 OCResource *pointer = headResource;
3442 OCResource *temp = NULL;
3446 temp = pointer->next;
3447 #ifdef WITH_PRESENCE
3448 if(pointer != (OCResource *) presenceResource.handle)
3450 #endif // WITH_PRESENCE
3451 deleteResource(pointer);
3452 #ifdef WITH_PRESENCE
3454 #endif // WITH_PRESENCE
3458 SRMDeInitSecureResources();
3460 #ifdef WITH_PRESENCE
3461 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3462 // presence notification attributed to their deletion to be processed.
3463 deleteResource((OCResource *) presenceResource.handle);
3464 #endif // WITH_PRESENCE
3467 OCStackResult deleteResource(OCResource *resource)
3469 OCResource *prev = NULL;
3470 OCResource *temp = NULL;
3473 OC_LOG_V(DEBUG,TAG,"resource is NULL");
3474 return OC_STACK_INVALID_PARAM;
3477 OC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
3479 temp = headResource;
3482 if (temp == resource)
3484 // Invalidate all Resource Properties.
3485 resource->resourceProperties = (OCResourceProperty) 0;
3486 #ifdef WITH_PRESENCE
3487 if(resource != (OCResource *) presenceResource.handle)
3489 #endif // WITH_PRESENCE
3490 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3491 #ifdef WITH_PRESENCE
3494 if(presenceResource.handle)
3496 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3497 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
3500 // Only resource in list.
3501 if (temp == headResource && temp == tailResource)
3503 headResource = NULL;
3504 tailResource = NULL;
3507 else if (temp == headResource)
3509 headResource = temp->next;
3512 else if (temp == tailResource)
3514 tailResource = prev;
3515 tailResource->next = NULL;
3519 prev->next = temp->next;
3522 deleteResourceElements(temp);
3533 return OC_STACK_ERROR;
3536 void deleteResourceElements(OCResource *resource)
3543 OICFree(resource->uri);
3544 deleteResourceType(resource->rsrcType);
3545 deleteResourceInterface(resource->rsrcInterface);
3548 void deleteResourceType(OCResourceType *resourceType)
3550 OCResourceType *pointer = resourceType;
3551 OCResourceType *next = NULL;
3555 next = pointer->next;
3556 OICFree(pointer->resourcetypename);
3562 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3564 OCResourceInterface *pointer = resourceInterface;
3565 OCResourceInterface *next = NULL;
3569 next = pointer->next;
3570 OICFree(pointer->name);
3576 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3578 OCResourceType *pointer = NULL;
3579 OCResourceType *previous = NULL;
3580 if (!resource || !resourceType)
3584 // resource type list is empty.
3585 else if (!resource->rsrcType)
3587 resource->rsrcType = resourceType;
3591 pointer = resource->rsrcType;
3595 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
3597 OC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
3598 OICFree(resourceType->resourcetypename);
3599 OICFree(resourceType);
3603 pointer = pointer->next;
3605 previous->next = resourceType;
3607 resourceType->next = NULL;
3609 OC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
3612 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3614 OCResource *resource = NULL;
3615 OCResourceType *pointer = NULL;
3617 // Find the specified resource
3618 resource = findResource((OCResource *) handle);
3624 // Make sure a resource has a resourcetype
3625 if (!resource->rsrcType)
3630 // Iterate through the list
3631 pointer = resource->rsrcType;
3632 for(uint8_t i = 0; i< index && pointer; ++i)
3634 pointer = pointer->next;
3639 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3641 if(resourceTypeList && resourceTypeName)
3643 OCResourceType * rtPointer = resourceTypeList;
3644 while(resourceTypeName && rtPointer)
3646 if(rtPointer->resourcetypename &&
3647 strcmp(resourceTypeName, (const char *)
3648 (rtPointer->resourcetypename)) == 0)
3652 rtPointer = rtPointer->next;
3660 * Insert a new interface into interface linked list only if not already present.
3661 * If alredy present, 2nd arg is free'd.
3662 * Default interface will always be first if present.
3664 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
3666 OCResourceInterface *pointer = NULL;
3667 OCResourceInterface *previous = NULL;
3669 newInterface->next = NULL;
3671 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
3673 if (!*firstInterface)
3675 *firstInterface = newInterface;
3677 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3679 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3681 OICFree(newInterface->name);
3682 OICFree(newInterface);
3687 newInterface->next = *firstInterface;
3688 *firstInterface = newInterface;
3693 pointer = *firstInterface;
3696 if (strcmp(newInterface->name, pointer->name) == 0)
3698 OICFree(newInterface->name);
3699 OICFree(newInterface);
3703 pointer = pointer->next;
3705 previous->next = newInterface;
3709 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3712 OCResource *resource = NULL;
3713 OCResourceInterface *pointer = NULL;
3715 // Find the specified resource
3716 resource = findResource((OCResource *) handle);
3722 // Make sure a resource has a resourceinterface
3723 if (!resource->rsrcInterface)
3728 // Iterate through the list
3729 pointer = resource->rsrcInterface;
3731 for (uint8_t i = 0; i < index && pointer; ++i)
3733 pointer = pointer->next;
3739 * This function splits the uri using the '?' delimiter.
3740 * "uriWithoutQuery" is the block of characters between the beginning
3741 * till the delimiter or '\0' which ever comes first.
3742 * "query" is whatever is to the right of the delimiter if present.
3743 * No delimiter sets the query to NULL.
3744 * If either are present, they will be malloc'ed into the params 2, 3.
3745 * The first param, *uri is left untouched.
3747 * NOTE: This function does not account for whitespace at the end of the uri NOR
3748 * malformed uri's with '??'. Whitespace at the end will be assumed to be
3749 * part of the query.
3751 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
3755 return OC_STACK_INVALID_URI;
3757 if(!query || !uriWithoutQuery)
3759 return OC_STACK_INVALID_PARAM;
3763 *uriWithoutQuery = NULL;
3765 size_t uriWithoutQueryLen = 0;
3766 size_t queryLen = 0;
3767 size_t uriLen = strlen(uri);
3769 char *pointerToDelimiter = strstr(uri, "?");
3771 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : pointerToDelimiter - uri;
3772 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
3774 if (uriWithoutQueryLen)
3776 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
3777 if (!*uriWithoutQuery)
3781 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
3785 *query = (char *) OICCalloc(queryLen + 1, 1);
3788 OICFree(*uriWithoutQuery);
3789 *uriWithoutQuery = NULL;
3792 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
3798 return OC_STACK_NO_MEMORY;
3801 const uint8_t* OCGetServerInstanceID(void)
3803 static bool generated = false;
3804 static ServerID sid;
3810 if (OCGenerateUuid(sid) != RAND_UUID_OK)
3812 OC_LOG(FATAL, TAG, PCF("Generate UUID for Server Instance failed!"));
3819 const char* OCGetServerInstanceIDString(void)
3821 static bool generated = false;
3822 static char sidStr[UUID_STRING_SIZE];
3829 const uint8_t* sid = OCGetServerInstanceID();
3831 if(OCConvertUuidToString(sid, sidStr) != RAND_UUID_OK)
3833 OC_LOG(FATAL, TAG, PCF("Generate UUID String for Server Instance failed!"));
3841 CAResult_t OCSelectNetwork()
3843 CAResult_t retResult = CA_STATUS_FAILED;
3844 CAResult_t caResult = CA_STATUS_OK;
3846 CATransportAdapter_t connTypes[] = {
3848 CA_ADAPTER_RFCOMM_BTEDR,
3849 CA_ADAPTER_GATT_BTLE
3852 ,CA_ADAPTER_REMOTE_ACCESS
3855 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
3857 for(int i = 0; i<numConnTypes; i++)
3859 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
3860 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
3862 caResult = CASelectNetwork(connTypes[i]);
3863 if(caResult == CA_STATUS_OK)
3865 retResult = CA_STATUS_OK;
3870 if(retResult != CA_STATUS_OK)
3872 return caResult; // Returns error of appropriate transport that failed fatally.
3878 OCStackResult CAResultToOCResult(CAResult_t caResult)
3884 case CA_STATUS_INVALID_PARAM:
3885 return OC_STACK_INVALID_PARAM;
3886 case CA_ADAPTER_NOT_ENABLED:
3887 return OC_STACK_ADAPTER_NOT_ENABLED;
3888 case CA_SERVER_STARTED_ALREADY:
3890 case CA_SERVER_NOT_STARTED:
3891 return OC_STACK_ERROR;
3892 case CA_DESTINATION_NOT_REACHABLE:
3893 return OC_STACK_COMM_ERROR;
3894 case CA_SOCKET_OPERATION_FAILED:
3895 return OC_STACK_COMM_ERROR;
3896 case CA_SEND_FAILED:
3897 return OC_STACK_COMM_ERROR;
3898 case CA_RECEIVE_FAILED:
3899 return OC_STACK_COMM_ERROR;
3900 case CA_MEMORY_ALLOC_FAILED:
3901 return OC_STACK_NO_MEMORY;
3902 case CA_REQUEST_TIMEOUT:
3903 return OC_STACK_TIMEOUT;
3904 case CA_DESTINATION_DISCONNECTED:
3905 return OC_STACK_COMM_ERROR;
3906 case CA_STATUS_FAILED:
3907 return OC_STACK_ERROR;
3908 case CA_NOT_SUPPORTED:
3909 return OC_STACK_NOTIMPL;
3911 return OC_STACK_ERROR;