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 OICFree(resourceTypeName);
1000 OCPayloadDestroy(response.payload);
1004 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1006 VERIFY_NON_NULL_NR(endPoint, FATAL);
1007 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1009 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
1011 if(responseInfo->info.resourceUri &&
1012 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1014 HandlePresenceResponse(endPoint, responseInfo);
1018 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1019 responseInfo->info.tokenLength, NULL, NULL);
1021 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1022 responseInfo->info.tokenLength);
1026 OC_LOG(INFO, TAG, PCF("There is a cbNode associated with the response token"));
1027 if(responseInfo->result == CA_EMPTY)
1029 OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
1030 // We do not have a case for the client to receive a RESET
1031 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1033 //This is the case of receiving an ACK on a request to a slow resource!
1034 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
1035 //TODO: should we inform the client
1036 // app that at least the request was received at the server?
1039 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1041 OC_LOG(INFO, TAG, PCF("Receiving A Timeout for this token"));
1042 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1044 OCClientResponse response = {};
1045 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1046 FixUpClientResponse(&response);
1047 response.resourceUri = responseInfo->info.resourceUri;
1049 response.result = CAToOCStackResult(responseInfo->result);
1050 cbNode->callBack(cbNode->context,
1051 cbNode->handle, &response);
1052 FindAndDeleteClientCB(cbNode);
1056 OC_LOG(INFO, TAG, PCF("This is a regular response, A client call back is found"));
1057 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1059 OCClientResponse response = {};
1060 response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1061 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1062 FixUpClientResponse(&response);
1063 response.resourceUri = responseInfo->info.resourceUri;
1065 response.result = CAToOCStackResult(responseInfo->result);
1066 if(responseInfo->info.payload &&
1067 responseInfo->info.payloadSize &&
1068 OC_STACK_OK != OCParsePayload(&response.payload, responseInfo->info.payload,
1069 responseInfo->info.payloadSize))
1071 OC_LOG(ERROR, TAG, PCF("Error converting payload"));
1072 OCPayloadDestroy(response.payload);
1076 response.numRcvdVendorSpecificHeaderOptions = 0;
1077 if(responseInfo->info.numOptions > 0)
1080 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1081 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1083 memcpy (&(response.sequenceNumber),
1084 &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
1085 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1090 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1093 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1095 OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
1096 OCPayloadDestroy(response.payload);
1100 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1102 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1103 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1107 if (cbNode->method == OC_REST_OBSERVE &&
1108 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1109 response.sequenceNumber <= cbNode->sequenceNumber)
1111 OC_LOG_V(INFO, TAG, PCF("Received stale notification. Number :%d"),
1112 response.sequenceNumber);
1116 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1119 cbNode->sequenceNumber = response.sequenceNumber;
1121 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1123 FindAndDeleteClientCB(cbNode);
1127 // To keep discovery callbacks active.
1128 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1129 MILLISECONDS_PER_SECOND);
1133 //Need to send ACK when the response is CON
1134 if(responseInfo->info.type == CA_MSG_CONFIRM)
1136 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1137 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0);
1140 OCPayloadDestroy(response.payload);
1147 OC_LOG(INFO, TAG, PCF("There is an observer associated with the response token"));
1148 if(responseInfo->result == CA_EMPTY)
1150 OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
1151 if(responseInfo->info.type == CA_MSG_RESET)
1153 OC_LOG(INFO, TAG, PCF("This is a RESET"));
1154 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1155 OC_OBSERVER_NOT_INTERESTED);
1157 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1159 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
1160 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1161 OC_OBSERVER_STILL_INTERESTED);
1164 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1166 OC_LOG(INFO, TAG, PCF("Receiving Time Out for an observer"));
1167 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1168 OC_OBSERVER_FAILED_COMM);
1173 if(!cbNode && !observer)
1175 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER)
1177 OC_LOG(INFO, TAG, PCF("This is a client, but no cbNode was found for token"));
1178 if(responseInfo->result == CA_EMPTY)
1180 OC_LOG(INFO, TAG, PCF("Receiving CA_EMPTY in the ocstack"));
1184 OC_LOG(INFO, TAG, PCF("Received a message without callbacks. Sending RESET"));
1185 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1186 CA_MSG_RESET, 0, NULL, NULL, 0);
1190 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
1192 OC_LOG(INFO, TAG, PCF("This is a server, but no observer was found for token"));
1193 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1195 OC_LOG_V(INFO, TAG, PCF("Received ACK at server for messageId : %d"),
1196 responseInfo->info.messageId);
1198 if (responseInfo->info.type == CA_MSG_RESET)
1200 OC_LOG_V(INFO, TAG, PCF("Received RESET at server for messageId : %d"),
1201 responseInfo->info.messageId);
1208 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
1212 * This function handles error response from CA
1213 * code shall be added to handle the errors
1215 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1217 OC_LOG(INFO, TAG, PCF("Enter HandleCAErrorResponse"));
1219 if(NULL == endPoint)
1221 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1225 if(NULL == errrorInfo)
1227 OC_LOG(ERROR, TAG, PCF("errrorInfo is NULL"));
1230 OC_LOG(INFO, TAG, PCF("Exit HandleCAErrorResponse"));
1234 * This function sends out Direct Stack Responses. These are responses that are not coming
1235 * from the application entity handler. These responses have no payload and are usually ACKs,
1236 * RESETs or some error conditions that were caught by the stack.
1238 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1239 const CAResponseResult_t responseResult, const CAMessageType_t type,
1240 const uint8_t numOptions, const CAHeaderOption_t *options,
1241 CAToken_t token, uint8_t tokenLength)
1243 CAResponseInfo_t respInfo = {};
1244 respInfo.result = responseResult;
1245 respInfo.info.messageId = coapID;
1246 respInfo.info.numOptions = numOptions;
1247 respInfo.info.options = (CAHeaderOption_t*)options;
1248 respInfo.info.payload = NULL;
1249 respInfo.info.token = token;
1250 respInfo.info.tokenLength = tokenLength;
1251 respInfo.info.type = type;
1253 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1254 if(caResult != CA_STATUS_OK)
1256 OC_LOG(ERROR, TAG, PCF("CASendResponse error"));
1257 return OC_STACK_ERROR;
1262 //This function will be called back by CA layer when a request is received
1263 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1265 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
1268 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1274 OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
1278 OCStackResult requestResult = OC_STACK_ERROR;
1280 if(myStackMode == OC_CLIENT)
1282 //TODO: should the client be responding to requests?
1286 OCServerProtocolRequest serverRequest = {};
1288 OC_LOG_V(INFO, TAG, PCF("Endpoint URI : %s"), requestInfo->info.resourceUri);
1290 char * uriWithoutQuery = NULL;
1291 char * query = NULL;
1293 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1295 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1297 OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1300 OC_LOG_V(INFO, TAG, PCF("URI without query: %s"), uriWithoutQuery);
1301 OC_LOG_V(INFO, TAG, PCF("Query : %s"), query);
1303 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1305 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1306 OICFree(uriWithoutQuery);
1310 OC_LOG(ERROR, TAG, PCF("URI length exceeds MAX_URI_LENGTH."));
1311 OICFree(uriWithoutQuery);
1318 if(strlen(query) < MAX_QUERY_LENGTH)
1320 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1325 OC_LOG(ERROR, TAG, PCF("Query length exceeds MAX_QUERY_LENGTH."));
1331 if (requestInfo->info.payload)
1333 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1334 memcpy (&(serverRequest.payload), requestInfo->info.payload,
1335 requestInfo->info.payloadSize);
1339 serverRequest.reqTotalSize = 0;
1342 switch (requestInfo->method)
1345 serverRequest.method = OC_REST_GET;
1348 serverRequest.method = OC_REST_PUT;
1351 serverRequest.method = OC_REST_POST;
1354 serverRequest.method = OC_REST_DELETE;
1357 OC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1358 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1359 requestInfo->info.type, requestInfo->info.numOptions,
1360 requestInfo->info.options, requestInfo->info.token,
1361 requestInfo->info.tokenLength);
1365 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1366 requestInfo->info.tokenLength);
1367 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1368 serverRequest.tokenLength = requestInfo->info.tokenLength;
1370 if (!serverRequest.requestToken)
1372 OC_LOG(FATAL, TAG, "Allocation for token failed.");
1373 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1374 requestInfo->info.type, requestInfo->info.numOptions,
1375 requestInfo->info.options, requestInfo->info.token,
1376 requestInfo->info.tokenLength);
1379 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1381 if (requestInfo->info.type == CA_MSG_CONFIRM)
1383 serverRequest.qos = OC_HIGH_QOS;
1387 serverRequest.qos = OC_LOW_QOS;
1389 // CA does not need the following field
1390 // Are we sure CA does not need them? how is it responding to multicast
1391 serverRequest.delayedResNeeded = 0;
1393 serverRequest.coapID = requestInfo->info.messageId;
1395 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1397 // copy vendor specific header options
1398 uint8_t tempNum = (requestInfo->info.numOptions);
1399 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1400 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1403 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
1404 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1405 requestInfo->info.type, requestInfo->info.numOptions,
1406 requestInfo->info.options, requestInfo->info.token,
1407 requestInfo->info.tokenLength);
1408 OICFree(serverRequest.requestToken);
1411 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1412 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1414 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1415 sizeof(CAHeaderOption_t)*tempNum);
1418 requestResult = HandleStackRequests (&serverRequest);
1420 // Send ACK to client as precursor to slow response
1421 if(requestResult == OC_STACK_SLOW_RESOURCE)
1423 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1424 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0);
1426 else if(requestResult != OC_STACK_OK)
1428 OC_LOG_V(ERROR, TAG, PCF("HandleStackRequests failed. error: %d"), requestResult);
1430 CAResponseResult_t stackResponse = OCToCAStackResult(requestResult);
1432 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1433 requestInfo->info.type, requestInfo->info.numOptions,
1434 requestInfo->info.options, requestInfo->info.token,
1435 requestInfo->info.tokenLength);
1437 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1438 // The token is copied in there, and is thus still owned by this function.
1439 OICFree(serverRequest.requestToken);
1440 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
1443 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1445 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
1446 OCStackResult result = OC_STACK_ERROR;
1447 ResourceHandling resHandling;
1448 OCResource *resource;
1449 if(!protocolRequest)
1451 OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
1452 return OC_STACK_INVALID_PARAM;
1455 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1456 protocolRequest->tokenLength);
1459 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
1460 result = AddServerRequest(&request, protocolRequest->coapID,
1461 protocolRequest->delayedResNeeded, 0,
1462 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
1463 protocolRequest->observationOption, protocolRequest->qos,
1464 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1465 protocolRequest->payload, protocolRequest->requestToken,
1466 protocolRequest->tokenLength,
1467 protocolRequest->resourceUrl, protocolRequest->reqTotalSize,
1468 &protocolRequest->devAddr);
1469 if (OC_STACK_OK != result)
1471 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
1477 OC_LOG(ERROR, TAG, PCF("Out of Memory"));
1478 return OC_STACK_NO_MEMORY;
1481 if(!protocolRequest->reqMorePacket)
1483 request->requestComplete = 1;
1488 OC_LOG(INFO, TAG, PCF("This is either a repeated or blocked Server Request"));
1491 if(request->requestComplete)
1493 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
1494 result = DetermineResourceHandling (request, &resHandling, &resource);
1495 if (result == OC_STACK_OK)
1497 result = ProcessRequest(resHandling, resource, request);
1502 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
1503 result = OC_STACK_CONTINUE;
1508 bool validatePlatformInfo(OCPlatformInfo info)
1511 if (!info.platformID)
1513 OC_LOG(ERROR, TAG, PCF("No platform ID found."));
1517 if (info.manufacturerName)
1519 size_t lenManufacturerName = strlen(info.manufacturerName);
1521 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1523 OC_LOG(ERROR, TAG, PCF("Manufacturer name fails length requirements."));
1529 OC_LOG(ERROR, TAG, PCF("No manufacturer name present"));
1533 if (info.manufacturerUrl)
1535 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1537 OC_LOG(ERROR, TAG, PCF("Manufacturer url fails length requirements."));
1544 //-----------------------------------------------------------------------------
1546 //-----------------------------------------------------------------------------
1548 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1551 !raInfo->username ||
1552 !raInfo->hostname ||
1553 !raInfo->xmpp_domain)
1556 return OC_STACK_INVALID_PARAM;
1558 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1559 gRASetInfo = (result == OC_STACK_OK)? true : false;
1565 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1572 OC_LOG(ERROR, TAG, PCF("Need to call OCSetRAInfo before calling OCInit"));
1573 return OC_STACK_ERROR;
1576 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1579 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1581 if(stackState == OC_STACK_INITIALIZED)
1583 OC_LOG(INFO, TAG, PCF("Subsequent calls to OCInit() without calling \
1584 OCStop() between them are ignored."));
1588 OCStackResult result = OC_STACK_ERROR;
1589 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1592 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)))
1594 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1595 return OC_STACK_ERROR;
1599 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER)
1601 caglobals.client = true;
1603 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER)
1605 caglobals.server = true;
1608 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1609 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
1611 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4);
1613 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
1614 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
1616 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4);
1619 defaultDeviceHandler = NULL;
1620 defaultDeviceHandlerCallbackParameter = NULL;
1623 result = CAResultToOCResult(CAInitialize());
1624 VERIFY_SUCCESS(result, OC_STACK_OK);
1626 result = CAResultToOCResult(OCSelectNetwork());
1627 VERIFY_SUCCESS(result, OC_STACK_OK);
1629 switch (myStackMode)
1632 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1633 result = CAResultToOCResult(CAStartDiscoveryServer());
1634 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1637 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1638 result = CAResultToOCResult(CAStartListeningServer());
1639 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1641 case OC_CLIENT_SERVER:
1642 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1643 result = CAResultToOCResult(CAStartListeningServer());
1644 if(result == OC_STACK_OK)
1646 result = CAResultToOCResult(CAStartDiscoveryServer());
1650 VERIFY_SUCCESS(result, OC_STACK_OK);
1652 #ifdef WITH_PRESENCE
1653 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1654 #endif // WITH_PRESENCE
1656 //Update Stack state to initialized
1657 stackState = OC_STACK_INITIALIZED;
1659 // Initialize resource
1660 if(myStackMode != OC_CLIENT)
1662 result = initResources();
1665 // Initialize the SRM Policy Engine
1666 if(result == OC_STACK_OK)
1668 result = SRMInitPolicyEngine();
1669 // TODO after BeachHead delivery: consolidate into single SRMInit()
1673 if(result != OC_STACK_OK)
1675 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1676 deleteAllResources();
1678 stackState = OC_STACK_UNINITIALIZED;
1683 OCStackResult OCStop()
1685 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1687 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1689 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1692 else if (stackState != OC_STACK_INITIALIZED)
1694 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1695 return OC_STACK_ERROR;
1698 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1700 #ifdef WITH_PRESENCE
1701 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1702 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1703 presenceResource.presenceTTL = 0;
1704 #endif // WITH_PRESENCE
1706 // Free memory dynamically allocated for resources
1707 deleteAllResources();
1709 DeletePlatformInfo();
1711 // Remove all observers
1712 DeleteObserverList();
1713 // Remove all the client callbacks
1714 DeleteClientCBList();
1716 // De-init the SRM Policy Engine
1717 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
1718 SRMDeInitPolicyEngine();
1721 stackState = OC_STACK_UNINITIALIZED;
1725 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1730 return CA_MSG_CONFIRM;
1735 return CA_MSG_NONCONFIRM;
1739 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1743 query = strchr (inputUri, '?');
1747 if((query - inputUri) > MAX_URI_LENGTH)
1749 return OC_STACK_INVALID_URI;
1752 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1754 return OC_STACK_INVALID_QUERY;
1757 else if(uriLen > MAX_URI_LENGTH)
1759 return OC_STACK_INVALID_URI;
1765 * A request uri consists of the following components in order:
1767 * optional prefix "coap://"
1769 * IPv6 address "[1234::5678]"
1770 * IPv4 address "192.168.1.1"
1771 * optional port ":5683"
1772 * resource uri "/oc/core..."
1774 * for PRESENCE requests, extract resource type.
1776 static OCStackResult ParseRequestUri(const char *fullUri,
1777 OCTransportAdapter adapter,
1778 OCTransportFlags flags,
1779 OCDevAddr **devAddr,
1781 char **resourceType)
1783 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
1785 OCStackResult result = OC_STACK_OK;
1786 OCDevAddr *da = NULL;
1790 // provide defaults for all returned values
1797 *resourceUri = NULL;
1801 *resourceType = NULL;
1804 // delimit url prefix, if any
1805 const char *start = fullUri;
1806 char *slash2 = strstr(start, "//");
1811 char *slash = strchr(start, '/');
1814 return OC_STACK_INVALID_URI;
1817 // processs url prefix, if any
1818 size_t urlLen = slash - start;
1822 if (urlLen && devAddr)
1823 { // construct OCDevAddr
1824 if (OC_ADAPTER_IP == adapter)
1826 if (start[0] == '[')
1828 char *close = strchr(++start, ']');
1829 if (!close || close > slash)
1831 return OC_STACK_INVALID_URI;
1834 if (close[1] == ':')
1842 colon = strchr(start, ':');
1843 end = (colon && colon < slash) ? colon : slash;
1846 if (len >= sizeof(da->addr))
1848 return OC_STACK_INVALID_URI;
1850 // use standard multicast port
1851 if (colon && colon < slash)
1853 for (colon++; colon < slash; colon++)
1856 if (c < '0' || c > '9')
1858 return OC_STACK_INVALID_URI;
1860 port = 10 * port + c - '0';
1867 * This is for Non-IP adapters(EDR and BLE).
1868 * The address will be between "//" and "/" in the request URI.
1869 * [Ex. coap://AB:BC:CD:DE:EF:FG/resource_uri]
1875 if (len >= sizeof(da->addr))
1877 return OC_STACK_INVALID_URI;
1880 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
1883 return OC_STACK_NO_MEMORY;
1885 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
1887 da->adapter = adapter;
1889 if (!strncmp(fullUri, "coaps:", 6))
1891 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
1896 // process resource uri, if any
1898 { // request uri and query
1899 size_t ulen = strlen(slash); // resource uri length
1900 size_t tlen = 0; // resource type length
1903 static const char strPresence[] = "/oic/ad?rt=";
1904 static const size_t lenPresence = sizeof(strPresence) - 1;
1905 if (!strncmp(slash, strPresence, lenPresence))
1907 type = slash + lenPresence;
1908 tlen = ulen - lenPresence;
1913 *resourceUri = (char *)OICMalloc(ulen + 1);
1916 result = OC_STACK_NO_MEMORY;
1919 strcpy(*resourceUri, slash);
1922 if (type && resourceType)
1924 *resourceType = (char *)OICMalloc(tlen + 1);
1927 result = OC_STACK_NO_MEMORY;
1931 OICStrcpy(*resourceType, (tlen+1), type);
1938 // free all returned values
1945 OICFree(*resourceUri);
1949 OICFree(*resourceType);
1954 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
1955 char *resourceUri, char **requestUri)
1957 char uri[CA_MAX_URI_LENGTH];
1959 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
1961 *requestUri = OICStrdup(uri);
1964 return OC_STACK_NO_MEMORY;
1971 * Discover or Perform requests on a specified resource
1973 OCStackResult OCDoResource(OCDoHandle *handle,
1975 const char *requestUri,
1976 const OCDevAddr *destination,
1978 OCConnectivityType connectivityType,
1979 OCQualityOfService qos,
1980 OCCallbackData *cbData,
1981 OCHeaderOption *options,
1984 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1986 // Validate input parameters
1987 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1988 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1989 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
1991 OCStackResult result = OC_STACK_ERROR;
1992 CAResult_t caResult;
1993 CAToken_t token = NULL;
1994 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
1995 ClientCB *clientCB = NULL;
1996 OCDoHandle resHandle = NULL;
1997 CAEndpoint_t *endpoint = NULL;
1998 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2000 OCTransportAdapter adapter;
2001 OCTransportFlags flags;
2002 // the request contents are put here
2003 CARequestInfo_t requestInfo = { CA_GET };
2004 // requestUri will be parsed into the following three variables
2005 OCDevAddr *devAddr = NULL;
2006 char *resourceUri = NULL;
2007 char *resourceType = NULL;
2009 // To track if memory is allocated for additional header options
2010 uint8_t hdrOptionMemAlloc = 0;
2012 // This validation is broken, but doesn't cause harm
2013 size_t uriLen = strlen(requestUri );
2014 if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
2020 * Support original behavior with address on resourceUri argument.
2022 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2023 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2025 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2027 if (result != OC_STACK_OK)
2029 OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2036 case OC_REST_OBSERVE:
2037 case OC_REST_OBSERVE_ALL:
2038 case OC_REST_CANCEL_OBSERVE:
2039 requestInfo.method = CA_GET;
2042 requestInfo.method = CA_PUT;
2045 requestInfo.method = CA_POST;
2047 case OC_REST_DELETE:
2048 requestInfo.method = CA_DELETE;
2050 case OC_REST_DISCOVER:
2052 if (!destination && !devAddr)
2054 destination = &tmpDevAddr;
2056 // CA_DISCOVER will become GET and isMulticast
2057 requestInfo.method = CA_GET;
2058 requestInfo.isMulticast = true;
2060 #ifdef WITH_PRESENCE
2061 case OC_REST_PRESENCE:
2062 // Replacing method type with GET because "presence"
2063 // is a stack layer only implementation.
2064 requestInfo.method = CA_GET;
2068 result = OC_STACK_INVALID_METHOD;
2072 if (!devAddr && !destination)
2074 OC_LOG_V(DEBUG, TAG, "no devAddr and no destination");
2075 result = OC_STACK_INVALID_PARAM;
2079 /* If not original behavior, use destination argument */
2080 if (destination && !devAddr)
2082 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2085 result = OC_STACK_NO_MEMORY;
2088 *devAddr = *destination;
2091 resHandle = GenerateInvocationHandle();
2094 result = OC_STACK_NO_MEMORY;
2098 caResult = CAGenerateToken(&token, tokenLength);
2099 if (caResult != CA_STATUS_OK)
2101 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2102 result= OC_STACK_ERROR;
2106 // fill in request data
2107 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2108 requestInfo.info.token = token;
2109 requestInfo.info.tokenLength = tokenLength;
2110 requestInfo.info.resourceUri = resourceUri;
2112 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2114 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2115 options, numOptions, OC_OBSERVE_REGISTER);
2116 if (result != OC_STACK_OK)
2120 hdrOptionMemAlloc = 1;
2121 requestInfo.info.numOptions = numOptions + 1;
2125 requestInfo.info.options = (CAHeaderOption_t*)options;
2126 requestInfo.info.numOptions = numOptions;
2129 // create remote endpoint
2130 result = OCCreateEndpoint(devAddr, &endpoint);
2134 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2137 OC_LOG(ERROR, TAG, PCF("Failed to create CBOR Payload"));
2143 requestInfo.info.payload = NULL;
2144 requestInfo.info.payloadSize = 0;
2149 if (result != OC_STACK_OK)
2151 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2155 // prepare for response
2156 #ifdef WITH_PRESENCE
2157 if (method == OC_REST_PRESENCE)
2159 char *presenceUri = NULL;
2160 result = OCPreparePresence(endpoint, resourceUri, &presenceUri);
2161 if (OC_STACK_OK != result)
2166 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2167 // Presence notification will form a canonical uri to
2168 // look for callbacks into the application.
2169 resourceUri = presenceUri;
2173 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2174 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2175 method, devAddr, resourceUri, resourceType, ttl);
2176 if (OC_STACK_OK != result)
2181 devAddr = NULL; // Client CB list entry now owns it
2182 resourceUri = NULL; // Client CB list entry now owns it
2183 resourceType = NULL; // Client CB list entry now owns it
2186 caResult = CASendRequest(endpoint, &requestInfo);
2187 if (caResult != CA_STATUS_OK)
2189 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
2190 result = OC_STACK_COMM_ERROR;
2196 *handle = resHandle;
2200 if (result != OC_STACK_OK)
2202 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
2203 FindAndDeleteClientCB(clientCB);
2204 CADestroyToken(token);
2212 // This is the owner of the payload object, so we free it
2213 OCPayloadDestroy(payload);
2214 OICFree(requestInfo.info.payload);
2216 OICFree(resourceUri);
2217 OICFree(resourceType);
2219 if (hdrOptionMemAlloc)
2221 OICFree(requestInfo.info.options);
2226 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2230 * This ftn is implemented one of two ways in the case of observation:
2232 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2233 * Remove the callback associated on client side.
2234 * When the next notification comes in from server,
2235 * reply with RESET message to server.
2236 * Keep in mind that the server will react to RESET only
2237 * if the last notification was sent as CON
2239 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2240 * and it is associated with an observe request
2241 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2242 * Send CON Observe request to server with
2243 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2244 * Remove the callback associated on client side.
2246 OCStackResult ret = OC_STACK_OK;
2247 CAEndpoint_t* endpoint = NULL;
2248 CAResult_t caResult;
2249 CAInfo_t requestData = {};
2250 CARequestInfo_t requestInfo = {};
2254 return OC_STACK_INVALID_PARAM;
2257 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2260 OC_LOG(ERROR, TAG, PCF("Client callback not found. Called OCCancel twice?"));
2264 switch (clientCB->method)
2266 case OC_REST_OBSERVE:
2267 case OC_REST_OBSERVE_ALL:
2268 OC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
2269 clientCB->requestUri);
2270 if (qos != OC_HIGH_QOS)
2272 FindAndDeleteClientCB(clientCB);
2277 OC_LOG(INFO, TAG, PCF("Cancelling observation as CONFIRMABLE"));
2280 requestData.type = qualityOfServiceToMessageType(qos);
2281 requestData.token = clientCB->token;
2282 requestData.tokenLength = clientCB->tokenLength;
2283 if (CreateObserveHeaderOption (&(requestData.options),
2284 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2286 return OC_STACK_ERROR;
2288 requestData.numOptions = numOptions + 1;
2289 requestData.resourceUri = OICStrdup (clientCB->requestUri);
2291 requestInfo.method = CA_GET;
2292 requestInfo.info = requestData;
2294 ret = OCCreateEndpoint(clientCB->devAddr, &endpoint);
2295 if (ret != OC_STACK_OK)
2297 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2302 caResult = CASendRequest(endpoint, &requestInfo);
2303 if (caResult != CA_STATUS_OK)
2305 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2306 ret = OC_STACK_ERROR;
2308 ret = CAResultToOCResult (caResult);
2311 #ifdef WITH_PRESENCE
2312 case OC_REST_PRESENCE:
2313 FindAndDeleteClientCB(clientCB);
2318 ret = OC_STACK_INVALID_METHOD;
2323 OCDestroyEndpoint(endpoint);
2324 if (requestData.numOptions > 0)
2326 OICFree(requestData.options);
2328 if (requestData.resourceUri)
2330 OICFree (requestData.resourceUri);
2337 * @brief Register Persistent storage callback.
2338 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2340 * OC_STACK_OK - No errors; Success
2341 * OC_STACK_INVALID_PARAM - Invalid parameter
2343 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2345 OC_LOG(INFO, TAG, PCF("RegisterPersistentStorageHandler !!"));
2346 if(!persistentStorageHandler)
2348 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2349 return OC_STACK_INVALID_PARAM;
2353 if( !persistentStorageHandler->open ||
2354 !persistentStorageHandler->close ||
2355 !persistentStorageHandler->read ||
2356 !persistentStorageHandler->unlink ||
2357 !persistentStorageHandler->write)
2359 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2360 return OC_STACK_INVALID_PARAM;
2363 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2366 #ifdef WITH_PRESENCE
2368 OCStackResult OCProcessPresence()
2370 OCStackResult result = OC_STACK_OK;
2372 // the following line floods the log with messages that are irrelevant
2373 // to most purposes. Uncomment as needed.
2374 //OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
2375 ClientCB* cbNode = NULL;
2376 OCClientResponse clientResponse;
2377 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2379 LL_FOREACH(cbList, cbNode)
2381 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2386 uint32_t now = GetTicks(0);
2387 OC_LOG_V(DEBUG, TAG, "this TTL level %d",
2388 cbNode->presence->TTLlevel);
2389 OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2391 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
2396 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2398 OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2399 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2402 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2404 OC_LOG(DEBUG, TAG, PCF("No more timeout ticks"));
2406 clientResponse.sequenceNumber = 0;
2407 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2408 clientResponse.devAddr = *cbNode->devAddr;
2409 FixUpClientResponse(&clientResponse);
2410 clientResponse.payload = NULL;
2412 // Increment the TTLLevel (going to a next state), so we don't keep
2413 // sending presence notification to client.
2414 cbNode->presence->TTLlevel++;
2415 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2416 cbNode->presence->TTLlevel);
2418 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2419 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2421 FindAndDeleteClientCB(cbNode);
2425 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2430 CAResult_t caResult = CA_STATUS_OK;
2431 CAEndpoint_t* endpoint = NULL;
2432 CAInfo_t requestData ={};
2433 CARequestInfo_t requestInfo = {};
2435 OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
2437 result = OCCreateEndpoint(cbNode->devAddr, &endpoint);
2438 if (result != OC_STACK_OK)
2440 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2444 requestData.type = CA_MSG_NONCONFIRM;
2445 requestData.token = cbNode->token;
2446 requestData.tokenLength = cbNode->tokenLength;
2447 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2448 requestInfo.method = CA_GET;
2449 requestInfo.info = requestData;
2451 caResult = CASendRequest(endpoint, &requestInfo);
2452 OCDestroyEndpoint(endpoint);
2454 if (caResult != CA_STATUS_OK)
2456 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2460 cbNode->presence->TTLlevel++;
2461 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2464 if (result != OC_STACK_OK)
2466 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2470 #endif // WITH_PRESENCE
2472 OCStackResult OCProcess()
2474 #ifdef WITH_PRESENCE
2475 OCProcessPresence();
2477 CAHandleRequestResponse();
2482 #ifdef WITH_PRESENCE
2483 OCStackResult OCStartPresence(const uint32_t ttl)
2485 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2486 OCChangeResourceProperty(
2487 &(((OCResource *)presenceResource.handle)->resourceProperties),
2490 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2492 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2493 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to max value"));
2497 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2498 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to default value"));
2502 presenceResource.presenceTTL = ttl;
2504 OC_LOG_V(DEBUG, TAG, "Presence TTL is %lu seconds", presenceResource.presenceTTL);
2506 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2508 presenceState = OC_PRESENCE_INITIALIZED;
2510 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2511 OICStrcpy(devAddr.addr, sizeof(devAddr.addr), OC_MULTICAST_IP);
2512 devAddr.port = OC_MULTICAST_PORT;
2514 CAToken_t caToken = NULL;
2515 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2516 if (caResult != CA_STATUS_OK)
2518 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2519 CADestroyToken(caToken);
2520 return OC_STACK_ERROR;
2523 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2524 (OCResource *)presenceResource.handle, OC_LOW_QOS, &devAddr);
2525 CADestroyToken(caToken);
2528 // Each time OCStartPresence is called
2529 // a different random 32-bit integer number is used
2530 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2532 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2533 OC_PRESENCE_TRIGGER_CREATE);
2536 OCStackResult OCStopPresence()
2538 OCStackResult result = OC_STACK_ERROR;
2540 if(presenceResource.handle)
2542 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2544 // make resource inactive
2545 result = OCChangeResourceProperty(
2546 &(((OCResource *) presenceResource.handle)->resourceProperties),
2550 if(result != OC_STACK_OK)
2553 PCF("Changing the presence resource properties to ACTIVE not successful"));
2557 return SendStopNotification();
2561 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
2562 void* callbackParameter)
2564 defaultDeviceHandler = entityHandler;
2565 defaultDeviceHandlerCallbackParameter = callbackParameter;
2570 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
2572 OC_LOG(INFO, TAG, PCF("Entering OCSetPlatformInfo"));
2574 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
2576 if (validatePlatformInfo(platformInfo))
2578 return SavePlatformInfo(platformInfo);
2582 return OC_STACK_INVALID_PARAM;
2587 return OC_STACK_ERROR;
2591 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2593 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2595 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
2597 OC_LOG(ERROR, TAG, PCF("Null or empty device name."));
2598 return OC_STACK_INVALID_PARAM;
2601 return SaveDeviceInfo(deviceInfo);
2604 OCStackResult OCCreateResource(OCResourceHandle *handle,
2605 const char *resourceTypeName,
2606 const char *resourceInterfaceName,
2607 const char *uri, OCEntityHandler entityHandler,
2608 void* callbackParam,
2609 uint8_t resourceProperties)
2612 OCResource *pointer = NULL;
2614 OCStackResult result = OC_STACK_ERROR;
2616 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2618 if(myStackMode == OC_CLIENT)
2620 return OC_STACK_INVALID_PARAM;
2622 // Validate parameters
2623 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2625 OC_LOG(ERROR, TAG, PCF("URI is empty or too long"));
2626 return OC_STACK_INVALID_URI;
2628 // Is it presented during resource discovery?
2629 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
2631 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2632 return OC_STACK_INVALID_PARAM;
2635 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2637 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2640 // Make sure resourceProperties bitmask has allowed properties specified
2641 if (resourceProperties
2642 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
2643 OC_EXPLICIT_DISCOVERABLE))
2645 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2646 return OC_STACK_INVALID_PARAM;
2649 // If the headResource is NULL, then no resources have been created...
2650 pointer = headResource;
2653 // At least one resources is in the resource list, so we need to search for
2654 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2657 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
2659 OC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
2660 return OC_STACK_INVALID_PARAM;
2662 pointer = pointer->next;
2665 // Create the pointer and insert it into the resource list
2666 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
2669 result = OC_STACK_NO_MEMORY;
2672 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2674 insertResource(pointer);
2677 str = OICStrdup(uri);
2680 result = OC_STACK_NO_MEMORY;
2685 // Set properties. Set OC_ACTIVE
2686 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2689 // Add the resourcetype to the resource
2690 result = BindResourceTypeToResource(pointer, resourceTypeName);
2691 if (result != OC_STACK_OK)
2693 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2697 // Add the resourceinterface to the resource
2698 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2699 if (result != OC_STACK_OK)
2701 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2705 // If an entity handler has been passed, attach it to the newly created
2706 // resource. Otherwise, set the default entity handler.
2709 pointer->entityHandler = entityHandler;
2710 pointer->entityHandlerCallbackParam = callbackParam;
2714 pointer->entityHandler = defaultResourceEHandler;
2715 pointer->entityHandlerCallbackParam = NULL;
2719 result = OC_STACK_OK;
2721 #ifdef WITH_PRESENCE
2722 if(presenceResource.handle)
2724 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2725 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
2729 if (result != OC_STACK_OK)
2731 // Deep delete of resource and other dynamic elements that it contains
2732 deleteResource(pointer);
2739 OCStackResult OCBindResource(
2740 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2742 OCResource *resource = NULL;
2745 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2747 // Validate parameters
2748 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2749 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2750 // Container cannot contain itself
2751 if (collectionHandle == resourceHandle)
2753 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2754 return OC_STACK_INVALID_PARAM;
2757 // Use the handle to find the resource in the resource linked list
2758 resource = findResource((OCResource *) collectionHandle);
2761 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2762 return OC_STACK_INVALID_PARAM;
2765 // Look for an open slot to add add the child resource.
2766 // If found, add it and return success
2767 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2769 if (!resource->rsrcResources[i])
2771 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2772 OC_LOG(INFO, TAG, PCF("resource bound"));
2774 #ifdef WITH_PRESENCE
2775 if(presenceResource.handle)
2777 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2778 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2779 OC_PRESENCE_TRIGGER_CHANGE);
2787 // Unable to add resourceHandle, so return error
2788 return OC_STACK_ERROR;
2791 OCStackResult OCUnBindResource(
2792 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2794 OCResource *resource = NULL;
2797 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2799 // Validate parameters
2800 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2801 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2802 // Container cannot contain itself
2803 if (collectionHandle == resourceHandle)
2805 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2806 return OC_STACK_INVALID_PARAM;
2809 // Use the handle to find the resource in the resource linked list
2810 resource = findResource((OCResource *) collectionHandle);
2813 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2814 return OC_STACK_INVALID_PARAM;
2817 // Look for an open slot to add add the child resource.
2818 // If found, add it and return success
2819 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2821 if (resourceHandle == resource->rsrcResources[i])
2823 resource->rsrcResources[i] = (OCResource *) NULL;
2824 OC_LOG(INFO, TAG, PCF("resource unbound"));
2826 // Send notification when resource is unbounded successfully.
2827 #ifdef WITH_PRESENCE
2828 if(presenceResource.handle)
2830 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2831 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2832 OC_PRESENCE_TRIGGER_CHANGE);
2839 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2841 // Unable to add resourceHandle, so return error
2842 return OC_STACK_ERROR;
2845 OCStackResult BindResourceTypeToResource(OCResource* resource,
2846 const char *resourceTypeName)
2848 OCResourceType *pointer = NULL;
2850 OCStackResult result = OC_STACK_ERROR;
2852 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2854 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
2857 result = OC_STACK_NO_MEMORY;
2861 str = OICStrdup(resourceTypeName);
2864 result = OC_STACK_NO_MEMORY;
2867 pointer->resourcetypename = str;
2869 insertResourceType(resource, pointer);
2870 result = OC_STACK_OK;
2873 if (result != OC_STACK_OK)
2882 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2883 const char *resourceInterfaceName)
2885 OCResourceInterface *pointer = NULL;
2887 OCStackResult result = OC_STACK_ERROR;
2889 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2891 OC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
2893 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
2896 result = OC_STACK_NO_MEMORY;
2900 str = OICStrdup(resourceInterfaceName);
2903 result = OC_STACK_NO_MEMORY;
2906 pointer->name = str;
2908 // Bind the resourceinterface to the resource
2909 insertResourceInterface(resource, pointer);
2911 result = OC_STACK_OK;
2914 if (result != OC_STACK_OK)
2923 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2924 const char *resourceTypeName)
2927 OCStackResult result = OC_STACK_ERROR;
2928 OCResource *resource = NULL;
2930 resource = findResource((OCResource *) handle);
2933 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2934 return OC_STACK_ERROR;
2937 result = BindResourceTypeToResource(resource, resourceTypeName);
2939 #ifdef WITH_PRESENCE
2940 if(presenceResource.handle)
2942 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2943 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2950 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2951 const char *resourceInterfaceName)
2954 OCStackResult result = OC_STACK_ERROR;
2955 OCResource *resource = NULL;
2957 resource = findResource((OCResource *) handle);
2960 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2961 return OC_STACK_ERROR;
2964 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2966 #ifdef WITH_PRESENCE
2967 if(presenceResource.handle)
2969 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2970 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2977 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
2979 OCResource *pointer = headResource;
2981 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2985 *numResources = *numResources + 1;
2986 pointer = pointer->next;
2991 OCResourceHandle OCGetResourceHandle(uint8_t index)
2993 OCResource *pointer = headResource;
2995 for( uint8_t i = 0; i < index && pointer; ++i)
2997 pointer = pointer->next;
2999 return (OCResourceHandle) pointer;
3002 OCStackResult OCDeleteResource(OCResourceHandle handle)
3006 OC_LOG(ERROR, TAG, PCF("Invalid handle for deletion"));
3007 return OC_STACK_INVALID_PARAM;
3010 OCResource *resource = findResource((OCResource *) handle);
3011 if (resource == NULL)
3013 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3014 return OC_STACK_NO_RESOURCE;
3017 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3019 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
3020 return OC_STACK_ERROR;
3026 const char *OCGetResourceUri(OCResourceHandle handle)
3028 OCResource *resource = NULL;
3030 resource = findResource((OCResource *) handle);
3033 return resource->uri;
3035 return (const char *) NULL;
3038 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3040 OCResource *resource = NULL;
3042 resource = findResource((OCResource *) handle);
3045 return resource->resourceProperties;
3047 return (OCResourceProperty)-1;
3050 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3051 uint8_t *numResourceTypes)
3053 OCResource *resource = NULL;
3054 OCResourceType *pointer = NULL;
3056 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3057 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3059 *numResourceTypes = 0;
3061 resource = findResource((OCResource *) handle);
3064 pointer = resource->rsrcType;
3067 *numResourceTypes = *numResourceTypes + 1;
3068 pointer = pointer->next;
3074 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3076 OCResourceType *resourceType = NULL;
3078 resourceType = findResourceTypeAtIndex(handle, index);
3081 return resourceType->resourcetypename;
3083 return (const char *) NULL;
3086 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3087 uint8_t *numResourceInterfaces)
3089 OCResourceInterface *pointer = NULL;
3090 OCResource *resource = NULL;
3092 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3093 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3095 *numResourceInterfaces = 0;
3096 resource = findResource((OCResource *) handle);
3099 pointer = resource->rsrcInterface;
3102 *numResourceInterfaces = *numResourceInterfaces + 1;
3103 pointer = pointer->next;
3109 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3111 OCResourceInterface *resourceInterface = NULL;
3113 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3114 if (resourceInterface)
3116 return resourceInterface->name;
3118 return (const char *) NULL;
3121 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3124 OCResource *resource = NULL;
3126 if (index >= MAX_CONTAINED_RESOURCES)
3131 resource = findResource((OCResource *) collectionHandle);
3137 return resource->rsrcResources[index];
3140 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3141 OCEntityHandler entityHandler,
3142 void* callbackParam)
3144 OCResource *resource = NULL;
3146 // Validate parameters
3147 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3149 // Use the handle to find the resource in the resource linked list
3150 resource = findResource((OCResource *)handle);
3153 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3154 return OC_STACK_ERROR;
3158 resource->entityHandler = entityHandler;
3159 resource->entityHandlerCallbackParam = callbackParam;
3161 #ifdef WITH_PRESENCE
3162 if(presenceResource.handle)
3164 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3165 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3172 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3174 OCResource *resource = NULL;
3176 resource = findResource((OCResource *)handle);
3179 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3184 return resource->entityHandler;
3187 void incrementSequenceNumber(OCResource * resPtr)
3189 // Increment the sequence number
3190 resPtr->sequenceNum += 1;
3191 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3193 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3198 #ifdef WITH_PRESENCE
3199 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3200 OCPresenceTrigger trigger)
3202 OCResource *resPtr = NULL;
3203 OCStackResult result = OC_STACK_ERROR;
3204 OCMethod method = OC_REST_PRESENCE;
3205 uint32_t maxAge = 0;
3206 resPtr = findResource((OCResource *) presenceResource.handle);
3209 return OC_STACK_NO_RESOURCE;
3212 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3214 maxAge = presenceResource.presenceTTL;
3216 result = SendAllObserverNotification(method, resPtr, maxAge,
3217 trigger, resourceType, OC_LOW_QOS);
3223 OCStackResult SendStopNotification()
3225 OCResource *resPtr = NULL;
3226 OCStackResult result = OC_STACK_ERROR;
3227 OCMethod method = OC_REST_PRESENCE;
3228 resPtr = findResource((OCResource *) presenceResource.handle);
3231 return OC_STACK_NO_RESOURCE;
3234 // maxAge is 0. ResourceType is NULL.
3235 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3241 #endif // WITH_PRESENCE
3242 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3244 OCResource *resPtr = NULL;
3245 OCStackResult result = OC_STACK_ERROR;
3246 OCMethod method = OC_REST_NOMETHOD;
3247 uint32_t maxAge = 0;
3249 OC_LOG(INFO, TAG, PCF("Notifying all observers"));
3250 #ifdef WITH_PRESENCE
3251 if(handle == presenceResource.handle)
3255 #endif // WITH_PRESENCE
3256 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3258 // Verify that the resource exists
3259 resPtr = findResource ((OCResource *) handle);
3262 return OC_STACK_NO_RESOURCE;
3266 //only increment in the case of regular observing (not presence)
3267 incrementSequenceNumber(resPtr);
3268 method = OC_REST_OBSERVE;
3269 maxAge = MAX_OBSERVE_AGE;
3270 #ifdef WITH_PRESENCE
3271 result = SendAllObserverNotification (method, resPtr, maxAge,
3272 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3274 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3281 OCNotifyListOfObservers (OCResourceHandle handle,
3282 OCObservationId *obsIdList,
3283 uint8_t numberOfIds,
3284 const OCRepPayload *payload,
3285 OCQualityOfService qos)
3287 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3289 OCResource *resPtr = NULL;
3290 //TODO: we should allow the server to define this
3291 uint32_t maxAge = MAX_OBSERVE_AGE;
3293 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3294 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3295 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3297 resPtr = findResource ((OCResource *) handle);
3298 if (NULL == resPtr || myStackMode == OC_CLIENT)
3300 return OC_STACK_NO_RESOURCE;
3304 incrementSequenceNumber(resPtr);
3306 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3307 payload, maxAge, qos));
3310 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3312 OCStackResult result = OC_STACK_ERROR;
3313 OCServerRequest *serverRequest = NULL;
3315 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3317 // Validate input parameters
3318 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3319 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3322 // Get pointer to request info
3323 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3326 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3327 result = serverRequest->ehResponseHandler(ehResponse);
3333 //-----------------------------------------------------------------------------
3334 // Private internal function definitions
3335 //-----------------------------------------------------------------------------
3336 static OCDoHandle GenerateInvocationHandle()
3338 OCDoHandle handle = NULL;
3339 // Generate token here, it will be deleted when the transaction is deleted
3340 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3343 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3349 #ifdef WITH_PRESENCE
3350 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3351 OCResourceProperty resourceProperties, uint8_t enable)
3355 return OC_STACK_INVALID_PARAM;
3357 if (resourceProperties
3358 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3360 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3361 return OC_STACK_INVALID_PARAM;
3365 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3369 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3375 OCStackResult initResources()
3377 OCStackResult result = OC_STACK_OK;
3379 headResource = NULL;
3380 tailResource = NULL;
3381 // Init Virtual Resources
3382 #ifdef WITH_PRESENCE
3383 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3385 result = OCCreateResource(&presenceResource.handle,
3386 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3388 OC_RSRVD_PRESENCE_URI,
3392 //make resource inactive
3393 result = OCChangeResourceProperty(
3394 &(((OCResource *) presenceResource.handle)->resourceProperties),
3398 if (result == OC_STACK_OK)
3400 result = SRMInitSecureResources();
3406 void insertResource(OCResource *resource)
3410 headResource = resource;
3411 tailResource = resource;
3415 tailResource->next = resource;
3416 tailResource = resource;
3418 resource->next = NULL;
3421 OCResource *findResource(OCResource *resource)
3423 OCResource *pointer = headResource;
3427 if (pointer == resource)
3431 pointer = pointer->next;
3436 void deleteAllResources()
3438 OCResource *pointer = headResource;
3439 OCResource *temp = NULL;
3443 temp = pointer->next;
3444 #ifdef WITH_PRESENCE
3445 if(pointer != (OCResource *) presenceResource.handle)
3447 #endif // WITH_PRESENCE
3448 deleteResource(pointer);
3449 #ifdef WITH_PRESENCE
3451 #endif // WITH_PRESENCE
3455 SRMDeInitSecureResources();
3457 #ifdef WITH_PRESENCE
3458 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3459 // presence notification attributed to their deletion to be processed.
3460 deleteResource((OCResource *) presenceResource.handle);
3461 #endif // WITH_PRESENCE
3464 OCStackResult deleteResource(OCResource *resource)
3466 OCResource *prev = NULL;
3467 OCResource *temp = NULL;
3470 OC_LOG_V(DEBUG,TAG,"resource is NULL");
3471 return OC_STACK_INVALID_PARAM;
3474 OC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
3476 temp = headResource;
3479 if (temp == resource)
3481 // Invalidate all Resource Properties.
3482 resource->resourceProperties = (OCResourceProperty) 0;
3483 #ifdef WITH_PRESENCE
3484 if(resource != (OCResource *) presenceResource.handle)
3486 #endif // WITH_PRESENCE
3487 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3488 #ifdef WITH_PRESENCE
3491 if(presenceResource.handle)
3493 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3494 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
3497 // Only resource in list.
3498 if (temp == headResource && temp == tailResource)
3500 headResource = NULL;
3501 tailResource = NULL;
3504 else if (temp == headResource)
3506 headResource = temp->next;
3509 else if (temp == tailResource)
3511 tailResource = prev;
3512 tailResource->next = NULL;
3516 prev->next = temp->next;
3519 deleteResourceElements(temp);
3530 return OC_STACK_ERROR;
3533 void deleteResourceElements(OCResource *resource)
3540 OICFree(resource->uri);
3541 deleteResourceType(resource->rsrcType);
3542 deleteResourceInterface(resource->rsrcInterface);
3545 void deleteResourceType(OCResourceType *resourceType)
3547 OCResourceType *pointer = resourceType;
3548 OCResourceType *next = NULL;
3552 next = pointer->next;
3553 OICFree(pointer->resourcetypename);
3559 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3561 OCResourceInterface *pointer = resourceInterface;
3562 OCResourceInterface *next = NULL;
3566 next = pointer->next;
3567 OICFree(pointer->name);
3573 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3575 OCResourceType *pointer = NULL;
3576 OCResourceType *previous = NULL;
3577 if (!resource || !resourceType)
3581 // resource type list is empty.
3582 else if (!resource->rsrcType)
3584 resource->rsrcType = resourceType;
3588 pointer = resource->rsrcType;
3592 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
3594 OC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
3595 OICFree(resourceType->resourcetypename);
3596 OICFree(resourceType);
3600 pointer = pointer->next;
3602 previous->next = resourceType;
3604 resourceType->next = NULL;
3606 OC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
3609 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3611 OCResource *resource = NULL;
3612 OCResourceType *pointer = NULL;
3614 // Find the specified resource
3615 resource = findResource((OCResource *) handle);
3621 // Make sure a resource has a resourcetype
3622 if (!resource->rsrcType)
3627 // Iterate through the list
3628 pointer = resource->rsrcType;
3629 for(uint8_t i = 0; i< index && pointer; ++i)
3631 pointer = pointer->next;
3636 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3638 if(resourceTypeList && resourceTypeName)
3640 OCResourceType * rtPointer = resourceTypeList;
3641 while(resourceTypeName && rtPointer)
3643 if(rtPointer->resourcetypename &&
3644 strcmp(resourceTypeName, (const char *)
3645 (rtPointer->resourcetypename)) == 0)
3649 rtPointer = rtPointer->next;
3657 * Insert a new interface into interface linked list only if not already present.
3658 * If alredy present, 2nd arg is free'd.
3659 * Default interface will always be first if present.
3661 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
3663 OCResourceInterface *pointer = NULL;
3664 OCResourceInterface *previous = NULL;
3666 newInterface->next = NULL;
3668 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
3670 if (!*firstInterface)
3672 *firstInterface = newInterface;
3674 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3676 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3678 OICFree(newInterface->name);
3679 OICFree(newInterface);
3684 newInterface->next = *firstInterface;
3685 *firstInterface = newInterface;
3690 pointer = *firstInterface;
3693 if (strcmp(newInterface->name, pointer->name) == 0)
3695 OICFree(newInterface->name);
3696 OICFree(newInterface);
3700 pointer = pointer->next;
3702 previous->next = newInterface;
3706 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3709 OCResource *resource = NULL;
3710 OCResourceInterface *pointer = NULL;
3712 // Find the specified resource
3713 resource = findResource((OCResource *) handle);
3719 // Make sure a resource has a resourceinterface
3720 if (!resource->rsrcInterface)
3725 // Iterate through the list
3726 pointer = resource->rsrcInterface;
3728 for (uint8_t i = 0; i < index && pointer; ++i)
3730 pointer = pointer->next;
3736 * This function splits the uri using the '?' delimiter.
3737 * "uriWithoutQuery" is the block of characters between the beginning
3738 * till the delimiter or '\0' which ever comes first.
3739 * "query" is whatever is to the right of the delimiter if present.
3740 * No delimiter sets the query to NULL.
3741 * If either are present, they will be malloc'ed into the params 2, 3.
3742 * The first param, *uri is left untouched.
3744 * NOTE: This function does not account for whitespace at the end of the uri NOR
3745 * malformed uri's with '??'. Whitespace at the end will be assumed to be
3746 * part of the query.
3748 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
3752 return OC_STACK_INVALID_URI;
3754 if(!query || !uriWithoutQuery)
3756 return OC_STACK_INVALID_PARAM;
3760 *uriWithoutQuery = NULL;
3762 size_t uriWithoutQueryLen = 0;
3763 size_t queryLen = 0;
3764 size_t uriLen = strlen(uri);
3766 char *pointerToDelimiter = strstr(uri, "?");
3768 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : pointerToDelimiter - uri;
3769 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
3771 if (uriWithoutQueryLen)
3773 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
3774 if (!*uriWithoutQuery)
3778 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
3782 *query = (char *) OICCalloc(queryLen + 1, 1);
3785 OICFree(*uriWithoutQuery);
3786 *uriWithoutQuery = NULL;
3789 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
3795 return OC_STACK_NO_MEMORY;
3798 const uint8_t* OCGetServerInstanceID(void)
3800 static bool generated = false;
3801 static ServerID sid;
3807 if (OCGenerateUuid(sid) != RAND_UUID_OK)
3809 OC_LOG(FATAL, TAG, PCF("Generate UUID for Server Instance failed!"));
3816 const char* OCGetServerInstanceIDString(void)
3818 static bool generated = false;
3819 static char sidStr[UUID_STRING_SIZE];
3826 const uint8_t* sid = OCGetServerInstanceID();
3828 if(OCConvertUuidToString(sid, sidStr) != RAND_UUID_OK)
3830 OC_LOG(FATAL, TAG, PCF("Generate UUID String for Server Instance failed!"));
3838 CAResult_t OCSelectNetwork()
3840 CAResult_t retResult = CA_STATUS_FAILED;
3841 CAResult_t caResult = CA_STATUS_OK;
3843 CATransportAdapter_t connTypes[] = {
3845 CA_ADAPTER_RFCOMM_BTEDR,
3846 CA_ADAPTER_GATT_BTLE
3849 ,CA_ADAPTER_REMOTE_ACCESS
3852 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
3854 for(int i = 0; i<numConnTypes; i++)
3856 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
3857 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
3859 caResult = CASelectNetwork(connTypes[i]);
3860 if(caResult == CA_STATUS_OK)
3862 retResult = CA_STATUS_OK;
3867 if(retResult != CA_STATUS_OK)
3869 return caResult; // Returns error of appropriate transport that failed fatally.
3875 OCStackResult CAResultToOCResult(CAResult_t caResult)
3881 case CA_STATUS_INVALID_PARAM:
3882 return OC_STACK_INVALID_PARAM;
3883 case CA_ADAPTER_NOT_ENABLED:
3884 return OC_STACK_ADAPTER_NOT_ENABLED;
3885 case CA_SERVER_STARTED_ALREADY:
3887 case CA_SERVER_NOT_STARTED:
3888 return OC_STACK_ERROR;
3889 case CA_DESTINATION_NOT_REACHABLE:
3890 return OC_STACK_COMM_ERROR;
3891 case CA_SOCKET_OPERATION_FAILED:
3892 return OC_STACK_COMM_ERROR;
3893 case CA_SEND_FAILED:
3894 return OC_STACK_COMM_ERROR;
3895 case CA_RECEIVE_FAILED:
3896 return OC_STACK_COMM_ERROR;
3897 case CA_MEMORY_ALLOC_FAILED:
3898 return OC_STACK_NO_MEMORY;
3899 case CA_REQUEST_TIMEOUT:
3900 return OC_STACK_TIMEOUT;
3901 case CA_DESTINATION_DISCONNECTED:
3902 return OC_STACK_COMM_ERROR;
3903 case CA_STATUS_FAILED:
3904 return OC_STACK_ERROR;
3905 case CA_NOT_SUPPORTED:
3906 return OC_STACK_NOTIMPL;
3908 return OC_STACK_ERROR;