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 = {0};
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 = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
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 = { .adapter = endpoint->adapter,
834 .flags = endpoint->flags };
835 OICStrcpy(ep.addr, sizeof(ep.addr), OC_MULTICAST_IP);
836 ep.port = OC_MULTICAST_PORT;
838 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
840 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
843 multicastPresenceSubscribe = 1;
847 if (!presenceSubscribe && !multicastPresenceSubscribe)
849 OC_LOG(ERROR, TAG, PCF("Received a presence notification, but no callback, ignoring"));
853 response.payload = NULL;
854 response.result = OC_STACK_OK;
856 CopyEndpointToDevAddr(endpoint, &response.devAddr);
857 FixUpClientResponse(&response);
859 if (responseInfo->info.payload)
861 result = OCParsePayload(&response.payload, responseInfo->info.payload,
862 responseInfo->info.payloadSize);
864 if(result != OC_STACK_OK)
866 OC_LOG(ERROR, TAG, PCF("Presence parse failed"));
869 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
871 OC_LOG(ERROR, TAG, PCF("Presence payload was wrong type"));
872 result = OC_STACK_ERROR;
875 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
876 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
877 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
880 if (presenceSubscribe)
882 if(cbNode->sequenceNumber == response.sequenceNumber)
884 OC_LOG(INFO, TAG, PCF("No presence change"));
890 OC_LOG(INFO, TAG, PCF("Stopping presence"));
891 response.result = OC_STACK_PRESENCE_STOPPED;
894 OICFree(cbNode->presence->timeOut);
895 OICFree(cbNode->presence);
896 cbNode->presence = NULL;
901 if(!cbNode->presence)
903 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
905 if(!(cbNode->presence))
907 OC_LOG(ERROR, TAG, PCF("Could not allocate memory for cbNode->presence"));
908 result = OC_STACK_NO_MEMORY;
912 VERIFY_NON_NULL_V(cbNode->presence);
913 cbNode->presence->timeOut = NULL;
914 cbNode->presence->timeOut = (uint32_t *)
915 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
916 if(!(cbNode->presence->timeOut)){
918 PCF("Could not allocate memory for cbNode->presence->timeOut"));
919 OICFree(cbNode->presence);
920 result = OC_STACK_NO_MEMORY;
925 ResetPresenceTTL(cbNode, maxAge);
927 cbNode->sequenceNumber = response.sequenceNumber;
929 // Ensure that a filter is actually applied.
930 if( resourceTypeName && cbNode->filterResourceType)
932 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
941 // This is the multicast case
942 OCMulticastNode* mcNode = NULL;
943 mcNode = GetMCPresenceNode(presenceUri);
947 if(mcNode->nonce == response.sequenceNumber)
949 OC_LOG(INFO, TAG, PCF("No presence change (Multicast)"));
952 mcNode->nonce = response.sequenceNumber;
956 OC_LOG(INFO, TAG, PCF("Stopping presence"));
957 response.result = OC_STACK_PRESENCE_STOPPED;
962 char* uri = OICStrdup(presenceUri);
966 PCF("No Memory for URI to store in the presence node"));
967 result = OC_STACK_NO_MEMORY;
971 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
972 if(result == OC_STACK_NO_MEMORY)
975 PCF("No Memory for Multicast Presence Node"));
979 // presence node now owns uri
982 // Ensure that a filter is actually applied.
983 if(resourceTypeName && cbNode->filterResourceType)
985 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
992 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
994 if (cbResult == OC_STACK_DELETE_TRANSACTION)
996 FindAndDeleteClientCB(cbNode);
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 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1046 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1047 FixUpClientResponse(&response);
1048 response.resourceUri = responseInfo->info.resourceUri;
1050 response.result = CAToOCStackResult(responseInfo->result);
1051 cbNode->callBack(cbNode->context,
1052 cbNode->handle, &response);
1053 FindAndDeleteClientCB(cbNode);
1057 OC_LOG(INFO, TAG, PCF("This is a regular response, A client call back is found"));
1058 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1060 OCClientResponse response =
1061 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1062 response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1063 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1064 FixUpClientResponse(&response);
1065 response.resourceUri = responseInfo->info.resourceUri;
1067 response.result = CAToOCStackResult(responseInfo->result);
1068 if(responseInfo->info.payload &&
1069 responseInfo->info.payloadSize &&
1070 OC_STACK_OK != OCParsePayload(&response.payload, responseInfo->info.payload,
1071 responseInfo->info.payloadSize))
1073 OC_LOG(ERROR, TAG, PCF("Error converting payload"));
1074 OCPayloadDestroy(response.payload);
1078 response.numRcvdVendorSpecificHeaderOptions = 0;
1079 if(responseInfo->info.numOptions > 0)
1082 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1083 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1085 memcpy (&(response.sequenceNumber),
1086 &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
1087 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1092 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1095 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1097 OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
1098 OCPayloadDestroy(response.payload);
1102 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1104 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1105 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1109 if (cbNode->method == OC_REST_OBSERVE &&
1110 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1111 response.sequenceNumber <= cbNode->sequenceNumber)
1113 OC_LOG_V(INFO, TAG, PCF("Received stale notification. Number :%d"),
1114 response.sequenceNumber);
1118 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1121 cbNode->sequenceNumber = response.sequenceNumber;
1123 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1125 FindAndDeleteClientCB(cbNode);
1129 // To keep discovery callbacks active.
1130 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1131 MILLISECONDS_PER_SECOND);
1135 //Need to send ACK when the response is CON
1136 if(responseInfo->info.type == CA_MSG_CONFIRM)
1138 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1139 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0);
1142 OCPayloadDestroy(response.payload);
1149 OC_LOG(INFO, TAG, PCF("There is an observer associated with the response token"));
1150 if(responseInfo->result == CA_EMPTY)
1152 OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
1153 if(responseInfo->info.type == CA_MSG_RESET)
1155 OC_LOG(INFO, TAG, PCF("This is a RESET"));
1156 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1157 OC_OBSERVER_NOT_INTERESTED);
1159 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1161 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
1162 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1163 OC_OBSERVER_STILL_INTERESTED);
1166 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1168 OC_LOG(INFO, TAG, PCF("Receiving Time Out for an observer"));
1169 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1170 OC_OBSERVER_FAILED_COMM);
1175 if(!cbNode && !observer)
1177 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER)
1179 OC_LOG(INFO, TAG, PCF("This is a client, but no cbNode was found for token"));
1180 if(responseInfo->result == CA_EMPTY)
1182 OC_LOG(INFO, TAG, PCF("Receiving CA_EMPTY in the ocstack"));
1186 OC_LOG(INFO, TAG, PCF("Received a message without callbacks. Sending RESET"));
1187 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1188 CA_MSG_RESET, 0, NULL, NULL, 0);
1192 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
1194 OC_LOG(INFO, TAG, PCF("This is a server, but no observer was found for token"));
1195 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1197 OC_LOG_V(INFO, TAG, PCF("Received ACK at server for messageId : %d"),
1198 responseInfo->info.messageId);
1200 if (responseInfo->info.type == CA_MSG_RESET)
1202 OC_LOG_V(INFO, TAG, PCF("Received RESET at server for messageId : %d"),
1203 responseInfo->info.messageId);
1210 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
1214 * This function handles error response from CA
1215 * code shall be added to handle the errors
1217 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1219 OC_LOG(INFO, TAG, PCF("Enter HandleCAErrorResponse"));
1221 if(NULL == endPoint)
1223 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1227 if(NULL == errrorInfo)
1229 OC_LOG(ERROR, TAG, PCF("errrorInfo is NULL"));
1232 OC_LOG(INFO, TAG, PCF("Exit HandleCAErrorResponse"));
1236 * This function sends out Direct Stack Responses. These are responses that are not coming
1237 * from the application entity handler. These responses have no payload and are usually ACKs,
1238 * RESETs or some error conditions that were caught by the stack.
1240 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1241 const CAResponseResult_t responseResult, const CAMessageType_t type,
1242 const uint8_t numOptions, const CAHeaderOption_t *options,
1243 CAToken_t token, uint8_t tokenLength)
1245 CAResponseInfo_t respInfo = {
1246 .result = responseResult
1248 respInfo.info.messageId = coapID;
1249 respInfo.info.numOptions = numOptions;
1250 respInfo.info.options = (CAHeaderOption_t*)options;
1251 respInfo.info.payload = NULL;
1252 respInfo.info.token = token;
1253 respInfo.info.tokenLength = tokenLength;
1254 respInfo.info.type = type;
1256 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1257 if(caResult != CA_STATUS_OK)
1259 OC_LOG(ERROR, TAG, PCF("CASendResponse error"));
1260 return OC_STACK_ERROR;
1265 //This function will be called back by CA layer when a request is received
1266 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1268 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
1271 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1277 OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
1281 OCStackResult requestResult = OC_STACK_ERROR;
1283 if(myStackMode == OC_CLIENT)
1285 //TODO: should the client be responding to requests?
1289 OCServerProtocolRequest serverRequest = {0};
1291 OC_LOG_V(INFO, TAG, PCF("Endpoint URI : %s"), requestInfo->info.resourceUri);
1293 char * uriWithoutQuery = NULL;
1294 char * query = NULL;
1296 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1298 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1300 OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1303 OC_LOG_V(INFO, TAG, PCF("URI without query: %s"), uriWithoutQuery);
1304 OC_LOG_V(INFO, TAG, PCF("Query : %s"), query);
1306 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1308 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1309 OICFree(uriWithoutQuery);
1313 OC_LOG(ERROR, TAG, PCF("URI length exceeds MAX_URI_LENGTH."));
1314 OICFree(uriWithoutQuery);
1321 if(strlen(query) < MAX_QUERY_LENGTH)
1323 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1328 OC_LOG(ERROR, TAG, PCF("Query length exceeds MAX_QUERY_LENGTH."));
1334 if (requestInfo->info.payload)
1336 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1337 memcpy (&(serverRequest.payload), requestInfo->info.payload,
1338 requestInfo->info.payloadSize);
1342 serverRequest.reqTotalSize = 0;
1345 switch (requestInfo->method)
1348 serverRequest.method = OC_REST_GET;
1351 serverRequest.method = OC_REST_PUT;
1354 serverRequest.method = OC_REST_POST;
1357 serverRequest.method = OC_REST_DELETE;
1360 OC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1361 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1362 requestInfo->info.type, requestInfo->info.numOptions,
1363 requestInfo->info.options, requestInfo->info.token,
1364 requestInfo->info.tokenLength);
1368 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1369 requestInfo->info.tokenLength);
1370 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1371 serverRequest.tokenLength = requestInfo->info.tokenLength;
1373 if (!serverRequest.requestToken)
1375 OC_LOG(FATAL, TAG, "Allocation for token failed.");
1376 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1377 requestInfo->info.type, requestInfo->info.numOptions,
1378 requestInfo->info.options, requestInfo->info.token,
1379 requestInfo->info.tokenLength);
1382 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1384 if (requestInfo->info.type == CA_MSG_CONFIRM)
1386 serverRequest.qos = OC_HIGH_QOS;
1390 serverRequest.qos = OC_LOW_QOS;
1392 // CA does not need the following field
1393 // Are we sure CA does not need them? how is it responding to multicast
1394 serverRequest.delayedResNeeded = 0;
1396 serverRequest.coapID = requestInfo->info.messageId;
1398 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1400 // copy vendor specific header options
1401 uint8_t tempNum = (requestInfo->info.numOptions);
1402 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1403 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1406 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
1407 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1408 requestInfo->info.type, requestInfo->info.numOptions,
1409 requestInfo->info.options, requestInfo->info.token,
1410 requestInfo->info.tokenLength);
1411 OICFree(serverRequest.requestToken);
1414 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1415 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1417 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1418 sizeof(CAHeaderOption_t)*tempNum);
1421 requestResult = HandleStackRequests (&serverRequest);
1423 // Send ACK to client as precursor to slow response
1424 if(requestResult == OC_STACK_SLOW_RESOURCE)
1426 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1427 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0);
1429 else if(requestResult != OC_STACK_OK)
1431 OC_LOG_V(ERROR, TAG, PCF("HandleStackRequests failed. error: %d"), requestResult);
1433 CAResponseResult_t stackResponse = OCToCAStackResult(requestResult);
1435 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1436 requestInfo->info.type, requestInfo->info.numOptions,
1437 requestInfo->info.options, requestInfo->info.token,
1438 requestInfo->info.tokenLength);
1440 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1441 // The token is copied in there, and is thus still owned by this function.
1442 OICFree(serverRequest.requestToken);
1443 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
1446 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1448 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
1449 OCStackResult result = OC_STACK_ERROR;
1450 ResourceHandling resHandling;
1451 OCResource *resource;
1452 if(!protocolRequest)
1454 OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
1455 return OC_STACK_INVALID_PARAM;
1458 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1459 protocolRequest->tokenLength);
1462 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
1463 result = AddServerRequest(&request, protocolRequest->coapID,
1464 protocolRequest->delayedResNeeded, 0,
1465 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
1466 protocolRequest->observationOption, protocolRequest->qos,
1467 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1468 protocolRequest->payload, protocolRequest->requestToken,
1469 protocolRequest->tokenLength,
1470 protocolRequest->resourceUrl, protocolRequest->reqTotalSize,
1471 &protocolRequest->devAddr);
1472 if (OC_STACK_OK != result)
1474 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
1480 OC_LOG(ERROR, TAG, PCF("Out of Memory"));
1481 return OC_STACK_NO_MEMORY;
1484 if(!protocolRequest->reqMorePacket)
1486 request->requestComplete = 1;
1491 OC_LOG(INFO, TAG, PCF("This is either a repeated or blocked Server Request"));
1494 if(request->requestComplete)
1496 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
1497 result = DetermineResourceHandling (request, &resHandling, &resource);
1498 if (result == OC_STACK_OK)
1500 result = ProcessRequest(resHandling, resource, request);
1505 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
1506 result = OC_STACK_CONTINUE;
1511 bool validatePlatformInfo(OCPlatformInfo info)
1514 if (!info.platformID)
1516 OC_LOG(ERROR, TAG, PCF("No platform ID found."));
1520 if (info.manufacturerName)
1522 size_t lenManufacturerName = strlen(info.manufacturerName);
1524 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1526 OC_LOG(ERROR, TAG, PCF("Manufacturer name fails length requirements."));
1532 OC_LOG(ERROR, TAG, PCF("No manufacturer name present"));
1536 if (info.manufacturerUrl)
1538 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1540 OC_LOG(ERROR, TAG, PCF("Manufacturer url fails length requirements."));
1547 //-----------------------------------------------------------------------------
1549 //-----------------------------------------------------------------------------
1551 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1554 !raInfo->username ||
1555 !raInfo->hostname ||
1556 !raInfo->xmpp_domain)
1559 return OC_STACK_INVALID_PARAM;
1561 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1562 gRASetInfo = (result == OC_STACK_OK)? true : false;
1568 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1575 OC_LOG(ERROR, TAG, PCF("Need to call OCSetRAInfo before calling OCInit"));
1576 return OC_STACK_ERROR;
1579 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1582 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1584 if(stackState == OC_STACK_INITIALIZED)
1586 OC_LOG(INFO, TAG, PCF("Subsequent calls to OCInit() without calling \
1587 OCStop() between them are ignored."));
1591 OCStackResult result = OC_STACK_ERROR;
1592 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1595 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)))
1597 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1598 return OC_STACK_ERROR;
1602 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER)
1604 caglobals.client = true;
1606 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER)
1608 caglobals.server = true;
1611 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1612 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
1614 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4);
1616 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
1617 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
1619 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4);
1622 defaultDeviceHandler = NULL;
1623 defaultDeviceHandlerCallbackParameter = NULL;
1626 result = CAResultToOCResult(CAInitialize());
1627 VERIFY_SUCCESS(result, OC_STACK_OK);
1629 result = CAResultToOCResult(OCSelectNetwork());
1630 VERIFY_SUCCESS(result, OC_STACK_OK);
1632 switch (myStackMode)
1635 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1636 result = CAResultToOCResult(CAStartDiscoveryServer());
1637 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1640 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1641 result = CAResultToOCResult(CAStartListeningServer());
1642 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1644 case OC_CLIENT_SERVER:
1645 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1646 result = CAResultToOCResult(CAStartListeningServer());
1647 if(result == OC_STACK_OK)
1649 result = CAResultToOCResult(CAStartDiscoveryServer());
1653 VERIFY_SUCCESS(result, OC_STACK_OK);
1655 #ifdef WITH_PRESENCE
1656 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1657 #endif // WITH_PRESENCE
1659 //Update Stack state to initialized
1660 stackState = OC_STACK_INITIALIZED;
1662 // Initialize resource
1663 if(myStackMode != OC_CLIENT)
1665 result = initResources();
1668 // Initialize the SRM Policy Engine
1669 if(result == OC_STACK_OK)
1671 result = SRMInitPolicyEngine();
1672 // TODO after BeachHead delivery: consolidate into single SRMInit()
1676 if(result != OC_STACK_OK)
1678 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1679 deleteAllResources();
1681 stackState = OC_STACK_UNINITIALIZED;
1686 OCStackResult OCStop()
1688 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1690 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1692 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1695 else if (stackState != OC_STACK_INITIALIZED)
1697 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1698 return OC_STACK_ERROR;
1701 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1703 #ifdef WITH_PRESENCE
1704 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1705 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1706 presenceResource.presenceTTL = 0;
1707 #endif // WITH_PRESENCE
1709 // Free memory dynamically allocated for resources
1710 deleteAllResources();
1712 DeletePlatformInfo();
1714 // Remove all observers
1715 DeleteObserverList();
1716 // Remove all the client callbacks
1717 DeleteClientCBList();
1719 // De-init the SRM Policy Engine
1720 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
1721 SRMDeInitPolicyEngine();
1724 stackState = OC_STACK_UNINITIALIZED;
1728 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1733 return CA_MSG_CONFIRM;
1738 return CA_MSG_NONCONFIRM;
1742 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1746 query = strchr (inputUri, '?');
1750 if((query - inputUri) > MAX_URI_LENGTH)
1752 return OC_STACK_INVALID_URI;
1755 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1757 return OC_STACK_INVALID_QUERY;
1760 else if(uriLen > MAX_URI_LENGTH)
1762 return OC_STACK_INVALID_URI;
1768 * A request uri consists of the following components in order:
1770 * optional prefix "coap://"
1772 * IPv6 address "[1234::5678]"
1773 * IPv4 address "192.168.1.1"
1774 * optional port ":5683"
1775 * resource uri "/oc/core..."
1777 * for PRESENCE requests, extract resource type.
1779 static OCStackResult ParseRequestUri(const char *fullUri,
1780 OCTransportAdapter adapter,
1781 OCTransportFlags flags,
1782 OCDevAddr **devAddr,
1784 char **resourceType)
1786 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
1788 OCStackResult result = OC_STACK_OK;
1789 OCDevAddr *da = NULL;
1793 // provide defaults for all returned values
1800 *resourceUri = NULL;
1804 *resourceType = NULL;
1807 // delimit url prefix, if any
1808 const char *start = fullUri;
1809 char *slash2 = strstr(start, "//");
1814 char *slash = strchr(start, '/');
1817 return OC_STACK_INVALID_URI;
1820 // processs url prefix, if any
1821 size_t urlLen = slash - start;
1825 if (urlLen && devAddr)
1826 { // construct OCDevAddr
1827 if (start[0] == '[')
1829 char *close = strchr(++start, ']');
1830 if (!close || close > slash)
1832 return OC_STACK_INVALID_URI;
1835 if (close[1] == ':')
1839 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
1840 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
1844 char *dot = strchr(start, '.');
1845 if (dot && dot < slash)
1847 colon = strchr(start, ':');
1848 end = (colon && colon < slash) ? colon : slash;
1849 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
1850 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
1858 if (len >= sizeof(da->addr))
1860 return OC_STACK_INVALID_URI;
1862 // collect port, if any
1863 if (colon && colon < slash)
1865 for (colon++; colon < slash; colon++)
1868 if (c < '0' || c > '9')
1870 return OC_STACK_INVALID_URI;
1872 port = 10 * port + c - '0';
1877 if (len >= sizeof(da->addr))
1879 return OC_STACK_INVALID_URI;
1882 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
1885 return OC_STACK_NO_MEMORY;
1887 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
1889 da->adapter = adapter;
1891 if (!strncmp(fullUri, "coaps:", 6))
1893 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
1898 // process resource uri, if any
1900 { // request uri and query
1901 size_t ulen = strlen(slash); // resource uri length
1902 size_t tlen = 0; // resource type length
1905 static const char strPresence[] = "/oic/ad?rt=";
1906 static const size_t lenPresence = sizeof(strPresence) - 1;
1907 if (!strncmp(slash, strPresence, lenPresence))
1909 type = slash + lenPresence;
1910 tlen = ulen - lenPresence;
1915 *resourceUri = (char *)OICMalloc(ulen + 1);
1918 result = OC_STACK_NO_MEMORY;
1921 strcpy(*resourceUri, slash);
1924 if (type && resourceType)
1926 *resourceType = (char *)OICMalloc(tlen + 1);
1929 result = OC_STACK_NO_MEMORY;
1933 OICStrcpy(*resourceType, (tlen+1), type);
1940 // free all returned values
1947 OICFree(*resourceUri);
1951 OICFree(*resourceType);
1956 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
1957 char *resourceUri, char **requestUri)
1959 char uri[CA_MAX_URI_LENGTH];
1961 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
1963 *requestUri = OICStrdup(uri);
1966 return OC_STACK_NO_MEMORY;
1973 * Discover or Perform requests on a specified resource
1975 OCStackResult OCDoResource(OCDoHandle *handle,
1977 const char *requestUri,
1978 const OCDevAddr *destination,
1980 OCConnectivityType connectivityType,
1981 OCQualityOfService qos,
1982 OCCallbackData *cbData,
1983 OCHeaderOption *options,
1986 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1988 // Validate input parameters
1989 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1990 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1991 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
1993 OCStackResult result = OC_STACK_ERROR;
1994 CAResult_t caResult;
1995 CAToken_t token = NULL;
1996 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
1997 ClientCB *clientCB = NULL;
1998 OCDoHandle resHandle = NULL;
1999 CAEndpoint_t *endpoint = NULL;
2000 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2002 OCTransportAdapter adapter;
2003 OCTransportFlags flags;
2004 // the request contents are put here
2005 CARequestInfo_t requestInfo = {.method = CA_GET};
2006 // requestUri will be parsed into the following three variables
2007 OCDevAddr *devAddr = NULL;
2008 char *resourceUri = NULL;
2009 char *resourceType = NULL;
2011 // To track if memory is allocated for additional header options
2012 uint8_t hdrOptionMemAlloc = 0;
2014 // This validation is broken, but doesn't cause harm
2015 size_t uriLen = strlen(requestUri );
2016 if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
2022 * Support original behavior with address on resourceUri argument.
2024 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2025 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2027 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2029 if (result != OC_STACK_OK)
2031 OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2038 case OC_REST_OBSERVE:
2039 case OC_REST_OBSERVE_ALL:
2040 case OC_REST_CANCEL_OBSERVE:
2041 requestInfo.method = CA_GET;
2044 requestInfo.method = CA_PUT;
2047 requestInfo.method = CA_POST;
2049 case OC_REST_DELETE:
2050 requestInfo.method = CA_DELETE;
2052 case OC_REST_DISCOVER:
2054 if (destination || devAddr)
2056 requestInfo.isMulticast = false;
2060 destination = &tmpDevAddr;
2061 requestInfo.isMulticast = true;
2063 // CA_DISCOVER will become GET and isMulticast
2064 requestInfo.method = CA_GET;
2066 #ifdef WITH_PRESENCE
2067 case OC_REST_PRESENCE:
2068 // Replacing method type with GET because "presence"
2069 // is a stack layer only implementation.
2070 requestInfo.method = CA_GET;
2074 result = OC_STACK_INVALID_METHOD;
2078 if (!devAddr && !destination)
2080 OC_LOG_V(DEBUG, TAG, "no devAddr and no destination");
2081 result = OC_STACK_INVALID_PARAM;
2085 /* If not original behavior, use destination argument */
2086 if (destination && !devAddr)
2088 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2091 result = OC_STACK_NO_MEMORY;
2094 *devAddr = *destination;
2097 resHandle = GenerateInvocationHandle();
2100 result = OC_STACK_NO_MEMORY;
2104 caResult = CAGenerateToken(&token, tokenLength);
2105 if (caResult != CA_STATUS_OK)
2107 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2108 result= OC_STACK_ERROR;
2112 // fill in request data
2113 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2114 requestInfo.info.token = token;
2115 requestInfo.info.tokenLength = tokenLength;
2116 requestInfo.info.resourceUri = resourceUri;
2118 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2120 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2121 options, numOptions, OC_OBSERVE_REGISTER);
2122 if (result != OC_STACK_OK)
2126 hdrOptionMemAlloc = 1;
2127 requestInfo.info.numOptions = numOptions + 1;
2131 requestInfo.info.options = (CAHeaderOption_t*)options;
2132 requestInfo.info.numOptions = numOptions;
2135 // create remote endpoint
2136 result = OCCreateEndpoint(devAddr, &endpoint);
2140 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2143 OC_LOG(ERROR, TAG, PCF("Failed to create CBOR Payload"));
2149 requestInfo.info.payload = NULL;
2150 requestInfo.info.payloadSize = 0;
2155 if (result != OC_STACK_OK)
2157 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2161 // prepare for response
2162 #ifdef WITH_PRESENCE
2163 if (method == OC_REST_PRESENCE)
2165 char *presenceUri = NULL;
2166 result = OCPreparePresence(endpoint, resourceUri, &presenceUri);
2167 if (OC_STACK_OK != result)
2172 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2173 // Presence notification will form a canonical uri to
2174 // look for callbacks into the application.
2175 resourceUri = presenceUri;
2179 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2180 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2181 method, devAddr, resourceUri, resourceType, ttl);
2182 if (OC_STACK_OK != result)
2187 devAddr = NULL; // Client CB list entry now owns it
2188 resourceUri = NULL; // Client CB list entry now owns it
2189 resourceType = NULL; // Client CB list entry now owns it
2192 caResult = CASendRequest(endpoint, &requestInfo);
2193 if (caResult != CA_STATUS_OK)
2195 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
2196 result = OC_STACK_COMM_ERROR;
2202 *handle = resHandle;
2206 if (result != OC_STACK_OK)
2208 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
2209 FindAndDeleteClientCB(clientCB);
2210 CADestroyToken(token);
2218 // This is the owner of the payload object, so we free it
2219 OCPayloadDestroy(payload);
2220 OICFree(requestInfo.info.payload);
2222 OICFree(resourceUri);
2223 OICFree(resourceType);
2225 if (hdrOptionMemAlloc)
2227 OICFree(requestInfo.info.options);
2232 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2236 * This ftn is implemented one of two ways in the case of observation:
2238 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2239 * Remove the callback associated on client side.
2240 * When the next notification comes in from server,
2241 * reply with RESET message to server.
2242 * Keep in mind that the server will react to RESET only
2243 * if the last notification was sent as CON
2245 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2246 * and it is associated with an observe request
2247 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2248 * Send CON Observe request to server with
2249 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2250 * Remove the callback associated on client side.
2252 OCStackResult ret = OC_STACK_OK;
2253 CAEndpoint_t* endpoint = NULL;
2254 CAResult_t caResult;
2255 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2256 CARequestInfo_t requestInfo = {.method = CA_GET};
2260 return OC_STACK_INVALID_PARAM;
2263 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2266 OC_LOG(ERROR, TAG, PCF("Client callback not found. Called OCCancel twice?"));
2270 switch (clientCB->method)
2272 case OC_REST_OBSERVE:
2273 case OC_REST_OBSERVE_ALL:
2274 OC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
2275 clientCB->requestUri);
2276 if (qos != OC_HIGH_QOS)
2278 FindAndDeleteClientCB(clientCB);
2283 OC_LOG(INFO, TAG, PCF("Cancelling observation as CONFIRMABLE"));
2286 requestData.type = qualityOfServiceToMessageType(qos);
2287 requestData.token = clientCB->token;
2288 requestData.tokenLength = clientCB->tokenLength;
2289 if (CreateObserveHeaderOption (&(requestData.options),
2290 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2292 return OC_STACK_ERROR;
2294 requestData.numOptions = numOptions + 1;
2295 requestData.resourceUri = OICStrdup (clientCB->requestUri);
2297 requestInfo.method = CA_GET;
2298 requestInfo.info = requestData;
2300 ret = OCCreateEndpoint(clientCB->devAddr, &endpoint);
2301 if (ret != OC_STACK_OK)
2303 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2308 caResult = CASendRequest(endpoint, &requestInfo);
2309 if (caResult != CA_STATUS_OK)
2311 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2312 ret = OC_STACK_ERROR;
2314 ret = CAResultToOCResult (caResult);
2317 #ifdef WITH_PRESENCE
2318 case OC_REST_PRESENCE:
2319 FindAndDeleteClientCB(clientCB);
2324 ret = OC_STACK_INVALID_METHOD;
2329 OCDestroyEndpoint(endpoint);
2330 if (requestData.numOptions > 0)
2332 OICFree(requestData.options);
2334 if (requestData.resourceUri)
2336 OICFree (requestData.resourceUri);
2343 * @brief Register Persistent storage callback.
2344 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2346 * OC_STACK_OK - No errors; Success
2347 * OC_STACK_INVALID_PARAM - Invalid parameter
2349 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2351 OC_LOG(INFO, TAG, PCF("RegisterPersistentStorageHandler !!"));
2352 if(!persistentStorageHandler)
2354 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2355 return OC_STACK_INVALID_PARAM;
2359 if( !persistentStorageHandler->open ||
2360 !persistentStorageHandler->close ||
2361 !persistentStorageHandler->read ||
2362 !persistentStorageHandler->unlink ||
2363 !persistentStorageHandler->write)
2365 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2366 return OC_STACK_INVALID_PARAM;
2369 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2372 #ifdef WITH_PRESENCE
2374 OCStackResult OCProcessPresence()
2376 OCStackResult result = OC_STACK_OK;
2378 // the following line floods the log with messages that are irrelevant
2379 // to most purposes. Uncomment as needed.
2380 //OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
2381 ClientCB* cbNode = NULL;
2382 OCClientResponse clientResponse;
2383 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2385 LL_FOREACH(cbList, cbNode)
2387 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2392 uint32_t now = GetTicks(0);
2393 OC_LOG_V(DEBUG, TAG, "this TTL level %d",
2394 cbNode->presence->TTLlevel);
2395 OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2397 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
2402 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2404 OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2405 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2408 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2410 OC_LOG(DEBUG, TAG, PCF("No more timeout ticks"));
2412 clientResponse.sequenceNumber = 0;
2413 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2414 clientResponse.devAddr = *cbNode->devAddr;
2415 FixUpClientResponse(&clientResponse);
2416 clientResponse.payload = NULL;
2418 // Increment the TTLLevel (going to a next state), so we don't keep
2419 // sending presence notification to client.
2420 cbNode->presence->TTLlevel++;
2421 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2422 cbNode->presence->TTLlevel);
2424 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2425 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2427 FindAndDeleteClientCB(cbNode);
2431 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2436 CAResult_t caResult = CA_STATUS_OK;
2437 CAEndpoint_t* endpoint = NULL;
2438 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2439 CARequestInfo_t requestInfo = {.method = CA_GET};
2441 OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
2443 result = OCCreateEndpoint(cbNode->devAddr, &endpoint);
2444 if (result != OC_STACK_OK)
2446 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2450 requestData.type = CA_MSG_NONCONFIRM;
2451 requestData.token = cbNode->token;
2452 requestData.tokenLength = cbNode->tokenLength;
2453 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2454 requestInfo.method = CA_GET;
2455 requestInfo.info = requestData;
2457 caResult = CASendRequest(endpoint, &requestInfo);
2458 OCDestroyEndpoint(endpoint);
2460 if (caResult != CA_STATUS_OK)
2462 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2466 cbNode->presence->TTLlevel++;
2467 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2470 if (result != OC_STACK_OK)
2472 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2476 #endif // WITH_PRESENCE
2478 OCStackResult OCProcess()
2480 #ifdef WITH_PRESENCE
2481 OCProcessPresence();
2483 CAHandleRequestResponse();
2488 #ifdef WITH_PRESENCE
2489 OCStackResult OCStartPresence(const uint32_t ttl)
2491 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2492 OCChangeResourceProperty(
2493 &(((OCResource *)presenceResource.handle)->resourceProperties),
2496 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2498 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2499 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to max value"));
2503 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2504 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to default value"));
2508 presenceResource.presenceTTL = ttl;
2510 OC_LOG_V(DEBUG, TAG, "Presence TTL is %lu seconds", presenceResource.presenceTTL);
2512 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2514 presenceState = OC_PRESENCE_INITIALIZED;
2516 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2517 OICStrcpy(devAddr.addr, sizeof(devAddr.addr), OC_MULTICAST_IP);
2518 devAddr.port = OC_MULTICAST_PORT;
2520 CAToken_t caToken = NULL;
2521 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2522 if (caResult != CA_STATUS_OK)
2524 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2525 CADestroyToken(caToken);
2526 return OC_STACK_ERROR;
2529 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2530 (OCResource *)presenceResource.handle, OC_LOW_QOS, &devAddr);
2531 CADestroyToken(caToken);
2534 // Each time OCStartPresence is called
2535 // a different random 32-bit integer number is used
2536 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2538 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2539 OC_PRESENCE_TRIGGER_CREATE);
2542 OCStackResult OCStopPresence()
2544 OCStackResult result = OC_STACK_ERROR;
2546 if(presenceResource.handle)
2548 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2550 // make resource inactive
2551 result = OCChangeResourceProperty(
2552 &(((OCResource *) presenceResource.handle)->resourceProperties),
2556 if(result != OC_STACK_OK)
2559 PCF("Changing the presence resource properties to ACTIVE not successful"));
2563 return SendStopNotification();
2567 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
2568 void* callbackParameter)
2570 defaultDeviceHandler = entityHandler;
2571 defaultDeviceHandlerCallbackParameter = callbackParameter;
2576 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
2578 OC_LOG(INFO, TAG, PCF("Entering OCSetPlatformInfo"));
2580 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
2582 if (validatePlatformInfo(platformInfo))
2584 return SavePlatformInfo(platformInfo);
2588 return OC_STACK_INVALID_PARAM;
2593 return OC_STACK_ERROR;
2597 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2599 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2601 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
2603 OC_LOG(ERROR, TAG, PCF("Null or empty device name."));
2604 return OC_STACK_INVALID_PARAM;
2607 return SaveDeviceInfo(deviceInfo);
2610 OCStackResult OCCreateResource(OCResourceHandle *handle,
2611 const char *resourceTypeName,
2612 const char *resourceInterfaceName,
2613 const char *uri, OCEntityHandler entityHandler,
2614 void* callbackParam,
2615 uint8_t resourceProperties)
2618 OCResource *pointer = NULL;
2620 OCStackResult result = OC_STACK_ERROR;
2622 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2624 if(myStackMode == OC_CLIENT)
2626 return OC_STACK_INVALID_PARAM;
2628 // Validate parameters
2629 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2631 OC_LOG(ERROR, TAG, PCF("URI is empty or too long"));
2632 return OC_STACK_INVALID_URI;
2634 // Is it presented during resource discovery?
2635 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
2637 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2638 return OC_STACK_INVALID_PARAM;
2641 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2643 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2646 // Make sure resourceProperties bitmask has allowed properties specified
2647 if (resourceProperties
2648 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
2649 OC_EXPLICIT_DISCOVERABLE))
2651 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2652 return OC_STACK_INVALID_PARAM;
2655 // If the headResource is NULL, then no resources have been created...
2656 pointer = headResource;
2659 // At least one resources is in the resource list, so we need to search for
2660 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2663 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
2665 OC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
2666 return OC_STACK_INVALID_PARAM;
2668 pointer = pointer->next;
2671 // Create the pointer and insert it into the resource list
2672 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
2675 result = OC_STACK_NO_MEMORY;
2678 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2680 insertResource(pointer);
2683 str = OICStrdup(uri);
2686 result = OC_STACK_NO_MEMORY;
2691 // Set properties. Set OC_ACTIVE
2692 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2695 // Add the resourcetype to the resource
2696 result = BindResourceTypeToResource(pointer, resourceTypeName);
2697 if (result != OC_STACK_OK)
2699 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2703 // Add the resourceinterface to the resource
2704 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2705 if (result != OC_STACK_OK)
2707 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2711 // If an entity handler has been passed, attach it to the newly created
2712 // resource. Otherwise, set the default entity handler.
2715 pointer->entityHandler = entityHandler;
2716 pointer->entityHandlerCallbackParam = callbackParam;
2720 pointer->entityHandler = defaultResourceEHandler;
2721 pointer->entityHandlerCallbackParam = NULL;
2725 result = OC_STACK_OK;
2727 #ifdef WITH_PRESENCE
2728 if(presenceResource.handle)
2730 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2731 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
2735 if (result != OC_STACK_OK)
2737 // Deep delete of resource and other dynamic elements that it contains
2738 deleteResource(pointer);
2745 OCStackResult OCBindResource(
2746 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2748 OCResource *resource = NULL;
2751 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2753 // Validate parameters
2754 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2755 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2756 // Container cannot contain itself
2757 if (collectionHandle == resourceHandle)
2759 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2760 return OC_STACK_INVALID_PARAM;
2763 // Use the handle to find the resource in the resource linked list
2764 resource = findResource((OCResource *) collectionHandle);
2767 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2768 return OC_STACK_INVALID_PARAM;
2771 // Look for an open slot to add add the child resource.
2772 // If found, add it and return success
2773 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2775 if (!resource->rsrcResources[i])
2777 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2778 OC_LOG(INFO, TAG, PCF("resource bound"));
2780 #ifdef WITH_PRESENCE
2781 if(presenceResource.handle)
2783 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2784 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2785 OC_PRESENCE_TRIGGER_CHANGE);
2793 // Unable to add resourceHandle, so return error
2794 return OC_STACK_ERROR;
2797 OCStackResult OCUnBindResource(
2798 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2800 OCResource *resource = NULL;
2803 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2805 // Validate parameters
2806 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2807 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2808 // Container cannot contain itself
2809 if (collectionHandle == resourceHandle)
2811 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2812 return OC_STACK_INVALID_PARAM;
2815 // Use the handle to find the resource in the resource linked list
2816 resource = findResource((OCResource *) collectionHandle);
2819 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2820 return OC_STACK_INVALID_PARAM;
2823 // Look for an open slot to add add the child resource.
2824 // If found, add it and return success
2825 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2827 if (resourceHandle == resource->rsrcResources[i])
2829 resource->rsrcResources[i] = (OCResource *) NULL;
2830 OC_LOG(INFO, TAG, PCF("resource unbound"));
2832 // Send notification when resource is unbounded successfully.
2833 #ifdef WITH_PRESENCE
2834 if(presenceResource.handle)
2836 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2837 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2838 OC_PRESENCE_TRIGGER_CHANGE);
2845 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2847 // Unable to add resourceHandle, so return error
2848 return OC_STACK_ERROR;
2851 OCStackResult BindResourceTypeToResource(OCResource* resource,
2852 const char *resourceTypeName)
2854 OCResourceType *pointer = NULL;
2856 OCStackResult result = OC_STACK_ERROR;
2858 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2860 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
2863 result = OC_STACK_NO_MEMORY;
2867 str = OICStrdup(resourceTypeName);
2870 result = OC_STACK_NO_MEMORY;
2873 pointer->resourcetypename = str;
2875 insertResourceType(resource, pointer);
2876 result = OC_STACK_OK;
2879 if (result != OC_STACK_OK)
2888 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2889 const char *resourceInterfaceName)
2891 OCResourceInterface *pointer = NULL;
2893 OCStackResult result = OC_STACK_ERROR;
2895 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2897 OC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
2899 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
2902 result = OC_STACK_NO_MEMORY;
2906 str = OICStrdup(resourceInterfaceName);
2909 result = OC_STACK_NO_MEMORY;
2912 pointer->name = str;
2914 // Bind the resourceinterface to the resource
2915 insertResourceInterface(resource, pointer);
2917 result = OC_STACK_OK;
2920 if (result != OC_STACK_OK)
2929 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2930 const char *resourceTypeName)
2933 OCStackResult result = OC_STACK_ERROR;
2934 OCResource *resource = NULL;
2936 resource = findResource((OCResource *) handle);
2939 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2940 return OC_STACK_ERROR;
2943 result = BindResourceTypeToResource(resource, resourceTypeName);
2945 #ifdef WITH_PRESENCE
2946 if(presenceResource.handle)
2948 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2949 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2956 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2957 const char *resourceInterfaceName)
2960 OCStackResult result = OC_STACK_ERROR;
2961 OCResource *resource = NULL;
2963 resource = findResource((OCResource *) handle);
2966 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2967 return OC_STACK_ERROR;
2970 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2972 #ifdef WITH_PRESENCE
2973 if(presenceResource.handle)
2975 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2976 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2983 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
2985 OCResource *pointer = headResource;
2987 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2991 *numResources = *numResources + 1;
2992 pointer = pointer->next;
2997 OCResourceHandle OCGetResourceHandle(uint8_t index)
2999 OCResource *pointer = headResource;
3001 for( uint8_t i = 0; i < index && pointer; ++i)
3003 pointer = pointer->next;
3005 return (OCResourceHandle) pointer;
3008 OCStackResult OCDeleteResource(OCResourceHandle handle)
3012 OC_LOG(ERROR, TAG, PCF("Invalid handle for deletion"));
3013 return OC_STACK_INVALID_PARAM;
3016 OCResource *resource = findResource((OCResource *) handle);
3017 if (resource == NULL)
3019 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3020 return OC_STACK_NO_RESOURCE;
3023 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3025 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
3026 return OC_STACK_ERROR;
3032 const char *OCGetResourceUri(OCResourceHandle handle)
3034 OCResource *resource = NULL;
3036 resource = findResource((OCResource *) handle);
3039 return resource->uri;
3041 return (const char *) NULL;
3044 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3046 OCResource *resource = NULL;
3048 resource = findResource((OCResource *) handle);
3051 return resource->resourceProperties;
3053 return (OCResourceProperty)-1;
3056 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3057 uint8_t *numResourceTypes)
3059 OCResource *resource = NULL;
3060 OCResourceType *pointer = NULL;
3062 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3063 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3065 *numResourceTypes = 0;
3067 resource = findResource((OCResource *) handle);
3070 pointer = resource->rsrcType;
3073 *numResourceTypes = *numResourceTypes + 1;
3074 pointer = pointer->next;
3080 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3082 OCResourceType *resourceType = NULL;
3084 resourceType = findResourceTypeAtIndex(handle, index);
3087 return resourceType->resourcetypename;
3089 return (const char *) NULL;
3092 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3093 uint8_t *numResourceInterfaces)
3095 OCResourceInterface *pointer = NULL;
3096 OCResource *resource = NULL;
3098 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3099 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3101 *numResourceInterfaces = 0;
3102 resource = findResource((OCResource *) handle);
3105 pointer = resource->rsrcInterface;
3108 *numResourceInterfaces = *numResourceInterfaces + 1;
3109 pointer = pointer->next;
3115 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3117 OCResourceInterface *resourceInterface = NULL;
3119 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3120 if (resourceInterface)
3122 return resourceInterface->name;
3124 return (const char *) NULL;
3127 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3130 OCResource *resource = NULL;
3132 if (index >= MAX_CONTAINED_RESOURCES)
3137 resource = findResource((OCResource *) collectionHandle);
3143 return resource->rsrcResources[index];
3146 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3147 OCEntityHandler entityHandler,
3148 void* callbackParam)
3150 OCResource *resource = NULL;
3152 // Validate parameters
3153 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3155 // Use the handle to find the resource in the resource linked list
3156 resource = findResource((OCResource *)handle);
3159 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3160 return OC_STACK_ERROR;
3164 resource->entityHandler = entityHandler;
3165 resource->entityHandlerCallbackParam = callbackParam;
3167 #ifdef WITH_PRESENCE
3168 if(presenceResource.handle)
3170 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3171 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3178 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3180 OCResource *resource = NULL;
3182 resource = findResource((OCResource *)handle);
3185 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3190 return resource->entityHandler;
3193 void incrementSequenceNumber(OCResource * resPtr)
3195 // Increment the sequence number
3196 resPtr->sequenceNum += 1;
3197 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3199 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3204 #ifdef WITH_PRESENCE
3205 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3206 OCPresenceTrigger trigger)
3208 OCResource *resPtr = NULL;
3209 OCStackResult result = OC_STACK_ERROR;
3210 OCMethod method = OC_REST_PRESENCE;
3211 uint32_t maxAge = 0;
3212 resPtr = findResource((OCResource *) presenceResource.handle);
3215 return OC_STACK_NO_RESOURCE;
3218 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3220 maxAge = presenceResource.presenceTTL;
3222 result = SendAllObserverNotification(method, resPtr, maxAge,
3223 trigger, resourceType, OC_LOW_QOS);
3229 OCStackResult SendStopNotification()
3231 OCResource *resPtr = NULL;
3232 OCStackResult result = OC_STACK_ERROR;
3233 OCMethod method = OC_REST_PRESENCE;
3234 resPtr = findResource((OCResource *) presenceResource.handle);
3237 return OC_STACK_NO_RESOURCE;
3240 // maxAge is 0. ResourceType is NULL.
3241 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3247 #endif // WITH_PRESENCE
3248 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3250 OCResource *resPtr = NULL;
3251 OCStackResult result = OC_STACK_ERROR;
3252 OCMethod method = OC_REST_NOMETHOD;
3253 uint32_t maxAge = 0;
3255 OC_LOG(INFO, TAG, PCF("Notifying all observers"));
3256 #ifdef WITH_PRESENCE
3257 if(handle == presenceResource.handle)
3261 #endif // WITH_PRESENCE
3262 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3264 // Verify that the resource exists
3265 resPtr = findResource ((OCResource *) handle);
3268 return OC_STACK_NO_RESOURCE;
3272 //only increment in the case of regular observing (not presence)
3273 incrementSequenceNumber(resPtr);
3274 method = OC_REST_OBSERVE;
3275 maxAge = MAX_OBSERVE_AGE;
3276 #ifdef WITH_PRESENCE
3277 result = SendAllObserverNotification (method, resPtr, maxAge,
3278 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3280 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3287 OCNotifyListOfObservers (OCResourceHandle handle,
3288 OCObservationId *obsIdList,
3289 uint8_t numberOfIds,
3290 const OCRepPayload *payload,
3291 OCQualityOfService qos)
3293 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3295 OCResource *resPtr = NULL;
3296 //TODO: we should allow the server to define this
3297 uint32_t maxAge = MAX_OBSERVE_AGE;
3299 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3300 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3301 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3303 resPtr = findResource ((OCResource *) handle);
3304 if (NULL == resPtr || myStackMode == OC_CLIENT)
3306 return OC_STACK_NO_RESOURCE;
3310 incrementSequenceNumber(resPtr);
3312 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3313 payload, maxAge, qos));
3316 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3318 OCStackResult result = OC_STACK_ERROR;
3319 OCServerRequest *serverRequest = NULL;
3321 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3323 // Validate input parameters
3324 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3325 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3328 // Get pointer to request info
3329 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3332 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3333 result = serverRequest->ehResponseHandler(ehResponse);
3339 //-----------------------------------------------------------------------------
3340 // Private internal function definitions
3341 //-----------------------------------------------------------------------------
3342 static OCDoHandle GenerateInvocationHandle()
3344 OCDoHandle handle = NULL;
3345 // Generate token here, it will be deleted when the transaction is deleted
3346 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3349 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3355 #ifdef WITH_PRESENCE
3356 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3357 OCResourceProperty resourceProperties, uint8_t enable)
3361 return OC_STACK_INVALID_PARAM;
3363 if (resourceProperties
3364 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3366 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3367 return OC_STACK_INVALID_PARAM;
3371 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3375 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3381 OCStackResult initResources()
3383 OCStackResult result = OC_STACK_OK;
3385 headResource = NULL;
3386 tailResource = NULL;
3387 // Init Virtual Resources
3388 #ifdef WITH_PRESENCE
3389 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3391 result = OCCreateResource(&presenceResource.handle,
3392 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3394 OC_RSRVD_PRESENCE_URI,
3398 //make resource inactive
3399 result = OCChangeResourceProperty(
3400 &(((OCResource *) presenceResource.handle)->resourceProperties),
3404 if (result == OC_STACK_OK)
3406 result = SRMInitSecureResources();
3412 void insertResource(OCResource *resource)
3416 headResource = resource;
3417 tailResource = resource;
3421 tailResource->next = resource;
3422 tailResource = resource;
3424 resource->next = NULL;
3427 OCResource *findResource(OCResource *resource)
3429 OCResource *pointer = headResource;
3433 if (pointer == resource)
3437 pointer = pointer->next;
3442 void deleteAllResources()
3444 OCResource *pointer = headResource;
3445 OCResource *temp = NULL;
3449 temp = pointer->next;
3450 #ifdef WITH_PRESENCE
3451 if(pointer != (OCResource *) presenceResource.handle)
3453 #endif // WITH_PRESENCE
3454 deleteResource(pointer);
3455 #ifdef WITH_PRESENCE
3457 #endif // WITH_PRESENCE
3461 SRMDeInitSecureResources();
3463 #ifdef WITH_PRESENCE
3464 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3465 // presence notification attributed to their deletion to be processed.
3466 deleteResource((OCResource *) presenceResource.handle);
3467 #endif // WITH_PRESENCE
3470 OCStackResult deleteResource(OCResource *resource)
3472 OCResource *prev = NULL;
3473 OCResource *temp = NULL;
3476 OC_LOG_V(DEBUG,TAG,"resource is NULL");
3477 return OC_STACK_INVALID_PARAM;
3480 OC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
3482 temp = headResource;
3485 if (temp == resource)
3487 // Invalidate all Resource Properties.
3488 resource->resourceProperties = (OCResourceProperty) 0;
3489 #ifdef WITH_PRESENCE
3490 if(resource != (OCResource *) presenceResource.handle)
3492 #endif // WITH_PRESENCE
3493 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3494 #ifdef WITH_PRESENCE
3497 if(presenceResource.handle)
3499 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3500 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
3503 // Only resource in list.
3504 if (temp == headResource && temp == tailResource)
3506 headResource = NULL;
3507 tailResource = NULL;
3510 else if (temp == headResource)
3512 headResource = temp->next;
3515 else if (temp == tailResource)
3517 tailResource = prev;
3518 tailResource->next = NULL;
3522 prev->next = temp->next;
3525 deleteResourceElements(temp);
3536 return OC_STACK_ERROR;
3539 void deleteResourceElements(OCResource *resource)
3546 OICFree(resource->uri);
3547 deleteResourceType(resource->rsrcType);
3548 deleteResourceInterface(resource->rsrcInterface);
3551 void deleteResourceType(OCResourceType *resourceType)
3553 OCResourceType *pointer = resourceType;
3554 OCResourceType *next = NULL;
3558 next = pointer->next;
3559 OICFree(pointer->resourcetypename);
3565 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3567 OCResourceInterface *pointer = resourceInterface;
3568 OCResourceInterface *next = NULL;
3572 next = pointer->next;
3573 OICFree(pointer->name);
3579 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3581 OCResourceType *pointer = NULL;
3582 OCResourceType *previous = NULL;
3583 if (!resource || !resourceType)
3587 // resource type list is empty.
3588 else if (!resource->rsrcType)
3590 resource->rsrcType = resourceType;
3594 pointer = resource->rsrcType;
3598 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
3600 OC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
3601 OICFree(resourceType->resourcetypename);
3602 OICFree(resourceType);
3606 pointer = pointer->next;
3608 previous->next = resourceType;
3610 resourceType->next = NULL;
3612 OC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
3615 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3617 OCResource *resource = NULL;
3618 OCResourceType *pointer = NULL;
3620 // Find the specified resource
3621 resource = findResource((OCResource *) handle);
3627 // Make sure a resource has a resourcetype
3628 if (!resource->rsrcType)
3633 // Iterate through the list
3634 pointer = resource->rsrcType;
3635 for(uint8_t i = 0; i< index && pointer; ++i)
3637 pointer = pointer->next;
3642 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3644 if(resourceTypeList && resourceTypeName)
3646 OCResourceType * rtPointer = resourceTypeList;
3647 while(resourceTypeName && rtPointer)
3649 if(rtPointer->resourcetypename &&
3650 strcmp(resourceTypeName, (const char *)
3651 (rtPointer->resourcetypename)) == 0)
3655 rtPointer = rtPointer->next;
3663 * Insert a new interface into interface linked list only if not already present.
3664 * If alredy present, 2nd arg is free'd.
3665 * Default interface will always be first if present.
3667 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
3669 OCResourceInterface *pointer = NULL;
3670 OCResourceInterface *previous = NULL;
3672 newInterface->next = NULL;
3674 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
3676 if (!*firstInterface)
3678 *firstInterface = newInterface;
3680 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3682 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3684 OICFree(newInterface->name);
3685 OICFree(newInterface);
3690 newInterface->next = *firstInterface;
3691 *firstInterface = newInterface;
3696 pointer = *firstInterface;
3699 if (strcmp(newInterface->name, pointer->name) == 0)
3701 OICFree(newInterface->name);
3702 OICFree(newInterface);
3706 pointer = pointer->next;
3708 previous->next = newInterface;
3712 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3715 OCResource *resource = NULL;
3716 OCResourceInterface *pointer = NULL;
3718 // Find the specified resource
3719 resource = findResource((OCResource *) handle);
3725 // Make sure a resource has a resourceinterface
3726 if (!resource->rsrcInterface)
3731 // Iterate through the list
3732 pointer = resource->rsrcInterface;
3734 for (uint8_t i = 0; i < index && pointer; ++i)
3736 pointer = pointer->next;
3742 * This function splits the uri using the '?' delimiter.
3743 * "uriWithoutQuery" is the block of characters between the beginning
3744 * till the delimiter or '\0' which ever comes first.
3745 * "query" is whatever is to the right of the delimiter if present.
3746 * No delimiter sets the query to NULL.
3747 * If either are present, they will be malloc'ed into the params 2, 3.
3748 * The first param, *uri is left untouched.
3750 * NOTE: This function does not account for whitespace at the end of the uri NOR
3751 * malformed uri's with '??'. Whitespace at the end will be assumed to be
3752 * part of the query.
3754 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
3758 return OC_STACK_INVALID_URI;
3760 if(!query || !uriWithoutQuery)
3762 return OC_STACK_INVALID_PARAM;
3766 *uriWithoutQuery = NULL;
3768 size_t uriWithoutQueryLen = 0;
3769 size_t queryLen = 0;
3770 size_t uriLen = strlen(uri);
3772 char *pointerToDelimiter = strstr(uri, "?");
3774 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : pointerToDelimiter - uri;
3775 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
3777 if (uriWithoutQueryLen)
3779 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
3780 if (!*uriWithoutQuery)
3784 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
3788 *query = (char *) OICCalloc(queryLen + 1, 1);
3791 OICFree(*uriWithoutQuery);
3792 *uriWithoutQuery = NULL;
3795 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
3801 return OC_STACK_NO_MEMORY;
3804 const uint8_t* OCGetServerInstanceID(void)
3806 static bool generated = false;
3807 static ServerID sid;
3813 if (OCGenerateUuid(sid) != RAND_UUID_OK)
3815 OC_LOG(FATAL, TAG, PCF("Generate UUID for Server Instance failed!"));
3822 const char* OCGetServerInstanceIDString(void)
3824 static bool generated = false;
3825 static char sidStr[UUID_STRING_SIZE];
3832 const uint8_t* sid = OCGetServerInstanceID();
3834 if(OCConvertUuidToString(sid, sidStr) != RAND_UUID_OK)
3836 OC_LOG(FATAL, TAG, PCF("Generate UUID String for Server Instance failed!"));
3844 CAResult_t OCSelectNetwork()
3846 CAResult_t retResult = CA_STATUS_FAILED;
3847 CAResult_t caResult = CA_STATUS_OK;
3849 CATransportAdapter_t connTypes[] = {
3851 CA_ADAPTER_RFCOMM_BTEDR,
3852 CA_ADAPTER_GATT_BTLE
3855 ,CA_ADAPTER_REMOTE_ACCESS
3858 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
3860 for(int i = 0; i<numConnTypes; i++)
3862 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
3863 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
3865 caResult = CASelectNetwork(connTypes[i]);
3866 if(caResult == CA_STATUS_OK)
3868 retResult = CA_STATUS_OK;
3873 if(retResult != CA_STATUS_OK)
3875 return caResult; // Returns error of appropriate transport that failed fatally.
3881 OCStackResult CAResultToOCResult(CAResult_t caResult)
3887 case CA_STATUS_INVALID_PARAM:
3888 return OC_STACK_INVALID_PARAM;
3889 case CA_ADAPTER_NOT_ENABLED:
3890 return OC_STACK_ADAPTER_NOT_ENABLED;
3891 case CA_SERVER_STARTED_ALREADY:
3893 case CA_SERVER_NOT_STARTED:
3894 return OC_STACK_ERROR;
3895 case CA_DESTINATION_NOT_REACHABLE:
3896 return OC_STACK_COMM_ERROR;
3897 case CA_SOCKET_OPERATION_FAILED:
3898 return OC_STACK_COMM_ERROR;
3899 case CA_SEND_FAILED:
3900 return OC_STACK_COMM_ERROR;
3901 case CA_RECEIVE_FAILED:
3902 return OC_STACK_COMM_ERROR;
3903 case CA_MEMORY_ALLOC_FAILED:
3904 return OC_STACK_NO_MEMORY;
3905 case CA_REQUEST_TIMEOUT:
3906 return OC_STACK_TIMEOUT;
3907 case CA_DESTINATION_DISCONNECTED:
3908 return OC_STACK_COMM_ERROR;
3909 case CA_STATUS_FAILED:
3910 return OC_STACK_ERROR;
3911 case CA_NOT_SUPPORTED:
3912 return OC_STACK_NOTIMPL;
3914 return OC_STACK_ERROR;