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"
54 #include "coap_time.h"
60 #include <arpa/inet.h>
64 #define UINT32_MAX (0xFFFFFFFFUL)
67 //-----------------------------------------------------------------------------
69 //-----------------------------------------------------------------------------
72 OC_STACK_UNINITIALIZED = 0,
74 OC_STACK_UNINIT_IN_PROGRESS
80 OC_PRESENCE_UNINITIALIZED = 0,
81 OC_PRESENCE_INITIALIZED
85 //-----------------------------------------------------------------------------
87 //-----------------------------------------------------------------------------
88 static OCStackState stackState = OC_STACK_UNINITIALIZED;
90 OCResource *headResource = NULL;
91 static OCResource *tailResource = NULL;
93 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
94 static PresenceResource presenceResource;
95 static uint8_t PresenceTimeOutSize = 0;
96 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
99 static OCMode myStackMode;
100 OCDeviceEntityHandler defaultDeviceHandler;
101 void* defaultDeviceHandlerCallbackParameter = NULL;
103 //-----------------------------------------------------------------------------
105 //-----------------------------------------------------------------------------
106 #define TAG PCF("OCStack")
107 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
108 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
109 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
110 TAG, PCF(#arg " is NULL")); return (retVal); } }
111 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OC_LOG((logLevel), \
112 TAG, PCF(#arg " is NULL")); return; } }
113 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
116 //TODO: we should allow the server to define this
117 #define MAX_OBSERVE_AGE (0x2FFFFUL)
119 #define MILLISECONDS_PER_SECOND (1000)
121 * Parse the presence payload and extract various parameters.
122 * Note: Caller should invoke OICFree after done with resType pointer.
124 * @param payload Presence payload.
125 * @param seqNum Sequence number.
126 * @param maxAge Time To Live (in seconds).
127 * @param resType Resource type.
129 void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge,
130 OCPresenceTrigger *presenceTrigger, char** resType);
132 //-----------------------------------------------------------------------------
133 // Private internal function prototypes
134 //-----------------------------------------------------------------------------
137 * Generate handle of OCDoResource invocation for callback management.
139 * @return Generated OCDoResource handle.
141 static OCDoHandle GenerateInvocationHandle();
144 * Initialize resource data structures, variables, etc.
146 * @return ::OC_STACK_OK on success, some other value upon failure.
148 static OCStackResult initResources();
151 * Add a resource to the end of the linked list of resources.
153 * @param resource Resource to be added
155 static void insertResource(OCResource *resource);
158 * Find a resource in the linked list of resources.
160 * @param resource Resource to be found.
161 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
164 static OCResource *findResource(OCResource *resource);
167 * Insert a resource type into a resource's resource type linked list.
168 * If resource type already exists, it will not be inserted and the
169 * resourceType will be free'd.
170 * resourceType->next should be null to avoid memory leaks.
171 * Function returns silently for null args.
173 * @param resource Resource where resource type is to be inserted.
174 * @param resourceType Resource type to be inserted.
176 static void insertResourceType(OCResource *resource,
177 OCResourceType *resourceType);
180 * Get a resource type at the specified index within a resource.
182 * @param handle Handle of resource.
183 * @param index Index of resource type.
185 * @return Pointer to resource type if found, NULL otherwise.
187 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
191 * Insert a resource interface into a resource's resource interface linked list.
192 * If resource interface already exists, it will not be inserted and the
193 * resourceInterface will be free'd.
194 * resourceInterface->next should be null to avoid memory leaks.
196 * @param resource Resource where resource interface is to be inserted.
197 * @param resourceInterface Resource interface to be inserted.
199 static void insertResourceInterface(OCResource *resource,
200 OCResourceInterface *resourceInterface);
203 * Get a resource interface at the specified index within a resource.
205 * @param handle Handle of resource.
206 * @param index Index of resource interface.
208 * @return Pointer to resource interface if found, NULL otherwise.
210 static OCResourceInterface *findResourceInterfaceAtIndex(
211 OCResourceHandle handle, uint8_t index);
214 * Delete all of the dynamically allocated elements that were created for the resource type.
216 * @param resourceType Specified resource type.
218 static void deleteResourceType(OCResourceType *resourceType);
221 * Delete all of the dynamically allocated elements that were created for the resource interface.
223 * @param resourceInterface Specified resource interface.
225 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
228 * Delete all of the dynamically allocated elements that were created for the resource.
230 * @param resource Specified resource.
232 static void deleteResourceElements(OCResource *resource);
235 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
238 * @param handle Handle of resource to be deleted.
240 * @return ::OC_STACK_OK on success, some other value upon failure.
242 static OCStackResult deleteResource(OCResource *resource);
245 * Delete all of the resources in the resource list.
247 static void deleteAllResources();
250 * Increment resource sequence number. Handles rollover.
252 * @param resPtr Pointer to resource.
254 static void incrementSequenceNumber(OCResource * resPtr);
257 * Verify the lengths of the URI and the query separately.
259 * @param inputUri Input URI and query.
260 * @param uriLen The length of the initial URI with query.
261 * @return ::OC_STACK_OK on success, some other value upon failure.
263 static OCStackResult verifyUriQueryLength(const char * inputUri,
267 * Determine if a request/response must be sent in a block transfer because it is too large to be
268 * sent in a single PDU. This function can be used for either a request or a response.
269 * Note: Either the request or response parameter should be non-NULL (i.e. only one, not both).
271 * @param request NULL or pointer to request.
272 * @param response NULL or pointer to response.
273 * @param size 0 or size of the request/response. If 0, strlen is used for determining
274 * the length of the request/response.
277 * false - packet transfer NOT required (i.e. normal request/response).
278 * true - packet transfer required (i.e. block transfer needed).
280 static bool OCIsPacketTransferRequired(const char *request, const char *response, size_t size);
283 * Attempts to initialize every network interface that the CA Layer might have compiled in.
285 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
286 * return something other than @ref CA_STATUS_OK, then this function fails.
288 * @return ::CA_STATUS_OK on success, some other value upon failure.
290 static CAResult_t OCSelectNetwork();
293 * Get the CoAP ticks after the specified number of milli-seconds.
295 * @param afterMilliSeconds Milli-seconds.
299 static uint32_t GetTicks(uint32_t afterMilliSeconds);
302 * Convert CAResponseResult_t to OCStackResult.
304 * @param caCode CAResponseResult_t code.
305 * @return ::OC_STACK_OK on success, some other value upon failure.
307 static OCStackResult CAToOCStackResult(CAResponseResult_t caCode);
310 * Convert OCStackResult to CAResponseResult_t.
312 * @param caCode OCStackResult code.
313 * @return ::CA_SUCCESS on success, some other value upon failure.
315 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode);
318 * Convert OCTransportFlags_t to CATransportModifiers_t.
320 * @param ocConType OCTransportFlags_t input.
321 * @return CATransportFlags
323 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
326 * Convert CATransportFlags_t to OCTransportModifiers_t.
328 * @param caConType CATransportFlags_t input.
329 * @return OCTransportFlags
331 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
334 * Handle response from presence request.
336 * @param endPoint CA remote endpoint.
337 * @param responseInfo CA response info.
338 * @return ::OC_STACK_OK on success, some other value upon failure.
340 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
341 const CAResponseInfo_t *responseInfo);
344 * This function will be called back by CA layer when a response is received.
346 * @param endPoint CA remote endpoint.
347 * @param responseInfo CA response info.
349 static void HandleCAResponses(const CAEndpoint_t* endPoint,
350 const CAResponseInfo_t* responseInfo);
353 * This function will be called back by CA layer when a request is received.
355 * @param endPoint CA remote endpoint.
356 * @param requestInfo CA request info.
358 static void HandleCARequests(const CAEndpoint_t* endPoint,
359 const CARequestInfo_t* requestInfo);
362 * Extract query from a URI.
364 * @param uri Full URI with query.
365 * @param query Pointer to string that will contain query.
366 * @param newURI Pointer to string that will contain URI.
367 * @return ::OC_STACK_OK on success, some other value upon failure.
369 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
372 * Finds a resource type in an OCResourceType link-list.
374 * @param resourceTypeList The link-list to be searched through.
375 * @param resourceTypeName The key to search for.
377 * @return Resource type that matches the key (ie. resourceTypeName) or
378 * NULL if there is either an invalid parameter or this function was unable to find the key.
380 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
381 const char * resourceTypeName);
384 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
385 * TTL will be set to maxAge.
387 * @param cbNode Callback Node for which presence ttl is to be reset.
388 * @param maxAge New value of ttl in seconds.
390 * @return ::OC_STACK_OK on success, some other value upon failure.
392 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
394 //-----------------------------------------------------------------------------
395 // Internal functions
396 //-----------------------------------------------------------------------------
398 uint32_t GetTicks(uint32_t afterMilliSeconds)
403 // Guard against overflow of uint32_t
404 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
405 COAP_TICKS_PER_SECOND)
407 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
415 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
417 VERIFY_NON_NULL_NR(in, FATAL);
418 VERIFY_NON_NULL_NR(out, FATAL);
420 out->adapter = (OCTransportAdapter)in->adapter;
421 out->flags = CAToOCTransportFlags(in->flags);
422 strncpy(out->addr, in->addr, MAX_ADDR_STR_SIZE);
423 out->addr[MAX_ADDR_STR_SIZE - 1] = '\0';
424 out->port = in->port;
427 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
429 VERIFY_NON_NULL_NR(in, FATAL);
430 VERIFY_NON_NULL_NR(out, FATAL);
432 out->adapter = (CATransportAdapter_t)in->adapter;
433 out->flags = OCToCATransportFlags(in->flags);
434 strncpy(out->addr, in->addr, MAX_ADDR_STR_SIZE);
435 out->port = in->port;
438 static OCStackResult OCCreateEndpoint(OCDevAddr *devAddr, CAEndpoint_t **endpoint)
440 VERIFY_NON_NULL(devAddr, FATAL, OC_STACK_INVALID_PARAM);
441 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
443 CAEndpoint_t *ep = (CAEndpoint_t *)OICMalloc(sizeof (CAEndpoint_t));
446 return OC_STACK_NO_MEMORY;
449 ep->adapter = (CATransportAdapter_t)devAddr->adapter;
450 ep->flags = OCToCATransportFlags(devAddr->flags);
451 strncpy(ep->addr, devAddr->addr, MAX_ADDR_STR_SIZE_CA);
452 ep->port = devAddr->port;
459 static void OCDestroyEndpoint(CAEndpoint_t *endpoint)
464 void FixUpClientResponse(OCClientResponse *cr)
466 VERIFY_NON_NULL_NR(cr, FATAL);
468 cr->addr = &cr->devAddr;
469 cr->connType = (OCConnectivityType)
470 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
473 //-----------------------------------------------------------------------------
474 // Internal API function
475 //-----------------------------------------------------------------------------
477 // This internal function is called to update the stack with the status of
478 // observers and communication failures
479 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
481 OCStackResult result = OC_STACK_ERROR;
482 ResourceObserver * observer = NULL;
483 OCEntityHandlerRequest ehRequest = {};
487 case OC_OBSERVER_NOT_INTERESTED:
488 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
489 observer = GetObserverUsingToken (token, tokenLength);
492 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
493 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
494 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
495 if(result != OC_STACK_OK)
499 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
500 observer->resource->entityHandlerCallbackParam);
502 //observer is not observing anymore
503 result = DeleteObserverUsingToken (token, tokenLength);
504 if(result == OC_STACK_OK)
506 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
510 result = OC_STACK_OK;
511 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
514 case OC_OBSERVER_STILL_INTERESTED:
515 //observer is still interested
516 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
517 notifications, reset the failedCount"));
518 observer = GetObserverUsingToken (token, tokenLength);
521 observer->forceHighQos = 0;
522 observer->failedCommCount = 0;
523 result = OC_STACK_OK;
527 result = OC_STACK_OBSERVER_NOT_FOUND;
530 case OC_OBSERVER_FAILED_COMM:
531 //observer is not reachable
532 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
533 observer = GetObserverUsingToken (token, tokenLength);
536 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
538 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
539 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
540 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
541 if(result != OC_STACK_OK)
543 return OC_STACK_ERROR;
545 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
546 observer->resource->entityHandlerCallbackParam);
547 //observer is unreachable
548 result = DeleteObserverUsingToken (token, tokenLength);
549 if(result == OC_STACK_OK)
551 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
555 result = OC_STACK_OK;
556 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
561 observer->failedCommCount++;
562 result = OC_STACK_CONTINUE;
564 observer->forceHighQos = 1;
565 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
569 OC_LOG(ERROR, TAG, PCF("Unknown status"));
570 result = OC_STACK_ERROR;
575 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
577 OCStackResult ret = OC_STACK_ERROR;
585 ret = OC_STACK_RESOURCE_CREATED;
588 ret = OC_STACK_RESOURCE_DELETED;
591 ret = OC_STACK_INVALID_QUERY;
594 ret = OC_STACK_INVALID_OPTION;
597 ret = OC_STACK_NO_RESOURCE;
599 case CA_RETRANSMIT_TIMEOUT:
600 ret = OC_STACK_COMM_ERROR;
608 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode)
610 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
617 case OC_STACK_RESOURCE_CREATED:
620 case OC_STACK_RESOURCE_DELETED:
623 case OC_STACK_INVALID_QUERY:
626 case OC_STACK_INVALID_OPTION:
629 case OC_STACK_NO_RESOURCE:
632 case OC_STACK_COMM_ERROR:
633 ret = CA_RETRANSMIT_TIMEOUT;
641 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
643 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
645 // supply default behavior
646 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
648 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
650 if ((caFlags & OC_MASK_SCOPE) == 0)
652 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
657 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
659 return (OCTransportFlags)caFlags;
662 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
664 uint32_t lowerBound = 0;
665 uint32_t higherBound = 0;
667 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
669 return OC_STACK_INVALID_PARAM;
672 OC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
674 cbNode->presence->TTL = maxAgeSeconds;
676 for(int index = 0; index < PresenceTimeOutSize; index++)
678 // Guard against overflow
679 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
682 lowerBound = GetTicks((PresenceTimeOut[index] *
683 cbNode->presence->TTL *
684 MILLISECONDS_PER_SECOND)/100);
688 lowerBound = GetTicks(UINT32_MAX);
691 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
694 higherBound = GetTicks((PresenceTimeOut[index + 1] *
695 cbNode->presence->TTL *
696 MILLISECONDS_PER_SECOND)/100);
700 higherBound = GetTicks(UINT32_MAX);
703 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
705 OC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
706 OC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
707 OC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
710 cbNode->presence->TTLlevel = 0;
712 OC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
716 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
718 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
720 return OC_RSRVD_TRIGGER_CREATE;
722 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
724 return OC_RSRVD_TRIGGER_CHANGE;
728 return OC_RSRVD_TRIGGER_DELETE;
732 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
734 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, char *presenceUri)
755 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
756 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
757 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
761 if (endpoint->flags & CA_IPV6)
763 format = "coap://[%s]:%u%s";
767 format = "coap://%s:%u%s";
770 return snprintf(presenceUri, CA_MAX_URI_LENGTH, format, endpoint->addr,
771 endpoint->port, OC_PRESENCE_URI);
774 void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge,
775 OCPresenceTrigger *presenceTrigger, char** resType)
777 if(!payload || !seqNum || !maxAge || !presenceTrigger || !resType)
782 cJSON *repObj = cJSON_Parse(payload);
784 cJSON *presenceObj = NULL;
785 cJSON *seqNumObj = NULL;
786 cJSON *maxAgeObj = NULL;
787 cJSON *triggerObj = NULL;
788 cJSON *resObj = NULL;
791 ocObj = cJSON_GetObjectItem(repObj, OC_RSRVD_OC);
794 //Presence payloads should only carry one JSON payload. The first
795 // & only array item is retrieved.
796 presenceObj = cJSON_GetArrayItem(ocObj, 0);
799 seqNumObj = cJSON_GetObjectItem(presenceObj, OC_RSRVD_NONCE);
802 *seqNum = (uint32_t)seqNumObj->valuedouble;
806 OC_LOG(ERROR, TAG, PCF("Nonce (AKA SeqNum) not found in"
807 " JSON Presence Payload."));
810 maxAgeObj = cJSON_GetObjectItem(presenceObj, OC_RSRVD_TTL);
813 *maxAge = maxAgeObj->valueint;
817 OC_LOG(ERROR, TAG, PCF("TTL (AKA MaxAge) not found in"
818 " JSON Presence Payload."));
821 triggerObj = cJSON_GetObjectItem(presenceObj,
825 char * triggerStr = triggerObj->valuestring;
826 *presenceTrigger = convertTriggerStringToEnum(triggerStr);
830 OC_LOG(ERROR, TAG, PCF("Trigger Reason not found in"
831 " JSON Presence Payload."));
834 resObj = cJSON_GetObjectItem(presenceObj,
835 OC_RSRVD_RESOURCE_TYPE);
838 *resType = OICStrdup(resObj->valuestring);
846 OC_LOG(ERROR, TAG, PCF("Resource Type not found in"
847 " JSON Presence Payload."));
853 OC_LOG(ERROR, TAG, PCF("JSON Presence Object not found in"
854 " Presence Payload."));
861 OC_LOG(ERROR, TAG, PCF("JSON Presence Payload does not contain a"
862 " valid \"oic\" JSON representation."));
869 OC_LOG(ERROR, TAG, PCF("JSON Presence Payload does map to a valid JSON"
870 " representation."));
876 cJSON_Delete(repObj);
879 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
880 const CAResponseInfo_t *responseInfo)
882 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
883 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
885 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
886 ClientCB * cbNode = NULL;
887 char *resourceTypeName = NULL;
888 OCClientResponse response;
889 OCStackResult result = OC_STACK_ERROR;
891 OCPresenceTrigger presenceTrigger = OC_PRESENCE_TRIGGER_CHANGE;
893 char presenceUri[CA_MAX_URI_LENGTH];
895 int presenceSubscribe = 0;
896 int multicastPresenceSubscribe = 0;
898 if (responseInfo->result != CA_SUCCESS)
900 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
901 return OC_STACK_ERROR;
904 uriLen = FormCanonicalPresenceUri(endpoint, OC_PRESENCE_URI, presenceUri);
905 if (uriLen < 0 || uriLen >= sizeof (presenceUri))
907 return OC_STACK_INVALID_URI;
910 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
913 presenceSubscribe = 1;
917 strncpy(presenceUri, responseInfo->info.resourceUri, CA_MAX_URI_LENGTH);
918 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
921 multicastPresenceSubscribe = 1;
925 if (!presenceSubscribe && !multicastPresenceSubscribe)
927 OC_LOG(ERROR, TAG, PCF("Received a presence notification, but no callback, ignoring"));
931 response.resJSONPayload = responseInfo->info.payload;
932 response.result = OC_STACK_OK;
934 CopyEndpointToDevAddr(endpoint, &response.devAddr);
935 FixUpClientResponse(&response);
937 if (responseInfo->info.payload)
939 parsePresencePayload(responseInfo->info.payload,
940 &(response.sequenceNumber),
946 if (presenceSubscribe)
948 if(cbNode->sequenceNumber == response.sequenceNumber)
950 OC_LOG(INFO, TAG, PCF("No presence change"));
956 OC_LOG(INFO, TAG, PCF("Stopping presence"));
957 response.result = OC_STACK_PRESENCE_STOPPED;
960 OICFree(cbNode->presence->timeOut);
961 OICFree(cbNode->presence);
962 cbNode->presence = NULL;
967 if(!cbNode->presence)
969 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
971 if(!(cbNode->presence))
973 OC_LOG(ERROR, TAG, PCF("Could not allocate memory for cbNode->presence"));
974 result = OC_STACK_NO_MEMORY;
978 VERIFY_NON_NULL_V(cbNode->presence);
979 cbNode->presence->timeOut = NULL;
980 cbNode->presence->timeOut = (uint32_t *)
981 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
982 if(!(cbNode->presence->timeOut)){
984 PCF("Could not allocate memory for cbNode->presence->timeOut"));
985 OICFree(cbNode->presence);
986 result = OC_STACK_NO_MEMORY;
991 ResetPresenceTTL(cbNode, maxAge);
993 cbNode->sequenceNumber = response.sequenceNumber;
995 // Ensure that a filter is actually applied.
996 if(resourceTypeName && cbNode->filterResourceType)
998 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1007 // This is the multicast case
1008 OCMulticastNode* mcNode = NULL;
1009 mcNode = GetMCPresenceNode(presenceUri);
1013 if(mcNode->nonce == response.sequenceNumber)
1015 OC_LOG(INFO, TAG, PCF("No presence change (Multicast)"));
1018 mcNode->nonce = response.sequenceNumber;
1022 OC_LOG(INFO, TAG, PCF("Stopping presence"));
1023 response.result = OC_STACK_PRESENCE_STOPPED;
1028 char* uri = OICStrdup(presenceUri);
1032 PCF("No Memory for URI to store in the presence node"));
1033 result = OC_STACK_NO_MEMORY;
1037 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1038 if(result == OC_STACK_NO_MEMORY)
1041 PCF("No Memory for Multicast Presence Node"));
1045 // presence node now owns uri
1048 // Ensure that a filter is actually applied.
1049 if(resourceTypeName && cbNode->filterResourceType)
1051 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1058 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1060 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1062 FindAndDeleteClientCB(cbNode);
1066 OICFree(resourceTypeName);
1070 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1072 VERIFY_NON_NULL_NR(endPoint, FATAL);
1073 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1074 VERIFY_NON_NULL_NR(responseInfo->info.resourceUri, FATAL);
1076 if(strcmp(responseInfo->info.resourceUri, OC_PRESENCE_URI) == 0)
1078 HandlePresenceResponse(endPoint, responseInfo);
1082 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1083 responseInfo->info.tokenLength, NULL, NULL);
1084 OC_LOG_V(DEBUG, TAG, "Response has the token %s", responseInfo->info.token);
1085 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1086 responseInfo->info.tokenLength);
1090 OC_LOG(INFO, TAG, PCF("There is a cbNode associated with the response token"));
1091 if(responseInfo->result == CA_EMPTY)
1093 OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
1094 // We do not have a case for the client to receive a RESET
1095 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1097 //This is the case of receiving an ACK on a request to a slow resource!
1098 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
1099 //TODO: should we inform the client
1100 // app that at least the request was received at the server?
1103 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1105 OC_LOG(INFO, TAG, PCF("Receiving A Timeout for this token"));
1106 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1108 OCClientResponse response = {};
1109 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1110 FixUpClientResponse(&response);
1111 response.resourceUri = responseInfo->info.resourceUri;
1113 response.result = CAToOCStackResult(responseInfo->result);
1114 cbNode->callBack(cbNode->context,
1115 cbNode->handle, &response);
1116 FindAndDeleteClientCB(cbNode);
1120 OC_LOG(INFO, TAG, PCF("This is a regular response, A client call back is found"));
1121 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1123 OCClientResponse response = {};
1124 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1125 FixUpClientResponse(&response);
1126 response.resourceUri = responseInfo->info.resourceUri;
1128 response.result = CAToOCStackResult(responseInfo->result);
1129 response.resJSONPayload = (const char*)responseInfo->info.payload;
1130 response.numRcvdVendorSpecificHeaderOptions = 0;
1131 if(responseInfo->info.numOptions > 0)
1134 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1135 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1137 memcpy (&(response.sequenceNumber),
1138 &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
1139 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1144 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1147 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1149 OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
1153 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1155 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1156 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1160 if (cbNode->method == OC_REST_OBSERVE &&
1161 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1162 response.sequenceNumber <= cbNode->sequenceNumber)
1164 OC_LOG_V(INFO, TAG, PCF("Received stale notification. Number :%d"),
1165 response.sequenceNumber);
1169 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1172 cbNode->sequenceNumber = response.sequenceNumber;
1174 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1176 FindAndDeleteClientCB(cbNode);
1180 // To keep discovery callbacks active.
1181 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1182 MILLISECONDS_PER_SECOND);
1186 //Need to send ACK when the response is CON
1187 if(responseInfo->info.type == CA_MSG_CONFIRM)
1189 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1190 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0);
1198 OC_LOG(INFO, TAG, PCF("There is an observer associated with the response token"));
1199 if(responseInfo->result == CA_EMPTY)
1201 OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
1202 if(responseInfo->info.type == CA_MSG_RESET)
1204 OC_LOG(INFO, TAG, PCF("This is a RESET"));
1205 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1206 OC_OBSERVER_NOT_INTERESTED);
1208 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1210 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
1211 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1212 OC_OBSERVER_STILL_INTERESTED);
1215 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1217 OC_LOG(INFO, TAG, PCF("Receiving Time Out for an observer"));
1218 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1219 OC_OBSERVER_FAILED_COMM);
1224 if(!cbNode && !observer)
1226 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER)
1228 OC_LOG(INFO, TAG, PCF("This is a client, but no cbNode was found for token"));
1229 if(responseInfo->result == CA_EMPTY)
1231 OC_LOG(INFO, TAG, PCF("Receiving CA_EMPTY in the ocstack"));
1235 OC_LOG(INFO, TAG, PCF("Received a response or notification,\
1236 but I do not have callback. Sending RESET"));
1237 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1238 CA_MSG_RESET, 0, NULL, NULL, 0);
1242 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
1244 OC_LOG(INFO, TAG, PCF("This is a server, but no observer was found for token"));
1245 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1247 OC_LOG_V(INFO, TAG, PCF("Received ACK at server for messageId : %d"),
1248 responseInfo->info.messageId);
1250 if (responseInfo->info.type == CA_MSG_RESET)
1252 OC_LOG_V(INFO, TAG, PCF("Received RESET at server for messageId : %d"),
1253 responseInfo->info.messageId);
1259 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
1260 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
1264 * This function handles error response from CA
1265 * code shall be added to handle the errors
1267 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1269 OC_LOG(INFO, TAG, PCF("Enter HandleCAErrorResponse"));
1271 if(NULL == endPoint)
1273 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1277 if(NULL == errrorInfo)
1279 OC_LOG(ERROR, TAG, PCF("errrorInfo is NULL"));
1282 OC_LOG(INFO, TAG, PCF("Exit HandleCAErrorResponse"));
1286 * This function sends out Direct Stack Responses. These are responses that are not coming
1287 * from the application entity handler. These responses have no payload and are usually ACKs,
1288 * RESETs or some error conditions that were caught by the stack.
1290 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1291 const CAResponseResult_t responseResult, const CAMessageType_t type,
1292 const uint8_t numOptions, const CAHeaderOption_t *options,
1293 CAToken_t token, uint8_t tokenLength)
1295 CAResponseInfo_t respInfo = {};
1296 respInfo.result = responseResult;
1297 respInfo.info.messageId = coapID;
1298 respInfo.info.numOptions = numOptions;
1299 respInfo.info.options = (CAHeaderOption_t*)options;
1300 respInfo.info.payload = NULL;
1301 respInfo.info.token = token;
1302 respInfo.info.tokenLength = tokenLength;
1303 respInfo.info.type = type;
1305 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1306 if(caResult != CA_STATUS_OK)
1308 OC_LOG(ERROR, TAG, PCF("CASendResponse error"));
1309 return OC_STACK_ERROR;
1314 //This function will be called back by CA layer when a request is received
1315 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1317 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
1320 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1326 OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
1330 OCStackResult requestResult = OC_STACK_ERROR;
1332 if(myStackMode == OC_CLIENT)
1334 //TODO: should the client be responding to requests?
1338 OCServerProtocolRequest serverRequest = {};
1340 OC_LOG_V(INFO, TAG, PCF("Endpoint URI : %s\n"), requestInfo->info.resourceUri);
1342 char * newUri = NULL;
1343 char * query = NULL;
1345 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &newUri);
1347 if (requestResult != OC_STACK_OK)
1349 OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1352 OC_LOG_V(INFO, TAG, PCF("URI without query: %s\n"), newUri);
1353 OC_LOG_V(INFO, TAG, PCF("Query : %s\n"), query);
1355 if(strlen(newUri) < MAX_URI_LENGTH)
1358 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl),
1364 OC_LOG(ERROR, TAG, PCF("URI length exceeds MAX_URI_LENGTH."));
1372 if(strlen(query) < MAX_QUERY_LENGTH)
1374 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1379 OC_LOG(ERROR, TAG, PCF("Query length exceeds MAX_QUERY_LENGTH."));
1384 //copy request payload
1385 if (requestInfo->info.payload)
1387 size_t payloadLen = strlen(requestInfo->info.payload);
1388 serverRequest.reqTotalSize = payloadLen + 1;
1389 OICStrcpy(serverRequest.reqJSONPayload, sizeof(serverRequest.reqJSONPayload),
1390 requestInfo->info.payload);
1394 serverRequest.reqTotalSize = 1;
1395 serverRequest.reqJSONPayload[0] = '\0';
1398 switch (requestInfo->method)
1401 serverRequest.method = OC_REST_GET;
1404 serverRequest.method = OC_REST_PUT;
1407 serverRequest.method = OC_REST_POST;
1410 serverRequest.method = OC_REST_DELETE;
1413 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
1414 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1415 requestInfo->info.type, requestInfo->info.numOptions,
1416 requestInfo->info.options, requestInfo->info.token,
1417 requestInfo->info.tokenLength);
1421 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d",
1422 requestInfo->info.tokenLength);
1423 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1424 requestInfo->info.tokenLength);
1425 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1426 serverRequest.tokenLength = requestInfo->info.tokenLength;
1428 if (!serverRequest.requestToken)
1430 OC_LOG(FATAL, TAG, "Server Request Token is NULL");
1431 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1432 requestInfo->info.type, requestInfo->info.numOptions,
1433 requestInfo->info.options, requestInfo->info.token,
1434 requestInfo->info.tokenLength);
1437 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1439 if (requestInfo->info.type == CA_MSG_CONFIRM)
1441 serverRequest.qos = OC_HIGH_QOS;
1445 serverRequest.qos = OC_LOW_QOS;
1447 // CA does not need the following field
1448 // Are we sure CA does not need them? how is it responding to multicast
1449 serverRequest.delayedResNeeded = 0;
1451 serverRequest.coapID = requestInfo->info.messageId;
1454 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1456 // copy vendor specific header options
1457 uint8_t tempNum = (requestInfo->info.numOptions);
1458 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1459 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1462 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
1463 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1464 requestInfo->info.type, requestInfo->info.numOptions,
1465 requestInfo->info.options, requestInfo->info.token,
1466 requestInfo->info.tokenLength);
1467 OICFree(serverRequest.requestToken);
1470 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1471 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1473 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1474 sizeof(CAHeaderOption_t)*tempNum);
1477 requestResult = HandleStackRequests (&serverRequest);
1479 // Send ACK to client as precursor to slow response
1480 if(requestResult == OC_STACK_SLOW_RESOURCE)
1482 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1483 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0);
1485 else if(requestResult != OC_STACK_OK)
1487 OC_LOG_V(ERROR, TAG, PCF("HandleStackRequests failed. error: %d"), requestResult);
1489 CAResponseResult_t stackResponse = OCToCAStackResult(requestResult);
1491 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1492 requestInfo->info.type, requestInfo->info.numOptions,
1493 requestInfo->info.options, requestInfo->info.token,
1494 requestInfo->info.tokenLength);
1496 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1497 // The token is copied in there, and is thus still owned by this function.
1498 OICFree(serverRequest.requestToken);
1499 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
1502 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1504 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
1505 OCStackResult result = OC_STACK_ERROR;
1506 ResourceHandling resHandling;
1507 OCResource *resource;
1508 if(!protocolRequest)
1510 OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
1511 return OC_STACK_INVALID_PARAM;
1514 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1515 protocolRequest->tokenLength);
1518 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
1519 result = AddServerRequest(&request, protocolRequest->coapID,
1520 protocolRequest->delayedResNeeded, 0,
1521 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
1522 protocolRequest->observationOption, protocolRequest->qos,
1523 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1524 protocolRequest->reqJSONPayload, protocolRequest->requestToken,
1525 protocolRequest->tokenLength,
1526 protocolRequest->resourceUrl, protocolRequest->reqTotalSize,
1527 &protocolRequest->devAddr);
1528 if (OC_STACK_OK != result)
1530 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
1536 OC_LOG(ERROR, TAG, PCF("Out of Memory"));
1537 return OC_STACK_NO_MEMORY;
1540 if(!protocolRequest->reqMorePacket)
1542 request->requestComplete = 1;
1548 PCF("This is either a repeated or blocked Server Request"));
1551 if(request->requestComplete)
1553 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
1554 result = DetermineResourceHandling (request, &resHandling, &resource);
1555 if (result == OC_STACK_OK)
1557 result = ProcessRequest(resHandling, resource, request);
1562 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
1563 result = OC_STACK_CONTINUE;
1568 bool validatePlatformInfo(OCPlatformInfo info)
1571 if (!info.platformID)
1573 OC_LOG(ERROR, TAG, PCF("No platform ID found."));
1577 if (info.manufacturerName)
1579 size_t lenManufacturerName = strlen(info.manufacturerName);
1581 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1583 OC_LOG(ERROR, TAG, PCF("Manufacturer name fails length requirements."));
1589 OC_LOG(ERROR, TAG, PCF("No manufacturer name present"));
1593 if (info.manufacturerUrl)
1595 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1597 OC_LOG(ERROR, TAG, PCF("Manufacturer url fails length requirements."));
1604 //-----------------------------------------------------------------------------
1606 //-----------------------------------------------------------------------------
1608 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1613 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1616 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1618 if(stackState == OC_STACK_INITIALIZED)
1620 OC_LOG(INFO, TAG, PCF("Subsequent calls to OCInit() without calling \
1621 OCStop() between them are ignored."));
1625 OCStackResult result = OC_STACK_ERROR;
1626 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1629 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)))
1631 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1632 return OC_STACK_ERROR;
1636 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1637 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
1639 defaultDeviceHandler = NULL;
1640 defaultDeviceHandlerCallbackParameter = NULL;
1643 result = CAResultToOCResult(CAInitialize());
1644 VERIFY_SUCCESS(result, OC_STACK_OK);
1646 result = CAResultToOCResult(OCSelectNetwork());
1647 VERIFY_SUCCESS(result, OC_STACK_OK);
1649 switch (myStackMode)
1652 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1653 result = CAResultToOCResult(CAStartDiscoveryServer());
1654 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1657 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1658 result = CAResultToOCResult(CAStartListeningServer());
1659 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1661 case OC_CLIENT_SERVER:
1662 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1663 result = CAResultToOCResult(CAStartListeningServer());
1664 if(result == OC_STACK_OK)
1666 result = CAResultToOCResult(CAStartDiscoveryServer());
1670 VERIFY_SUCCESS(result, OC_STACK_OK);
1672 #ifdef WITH_PRESENCE
1673 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1674 #endif // WITH_PRESENCE
1676 //Update Stack state to initialized
1677 stackState = OC_STACK_INITIALIZED;
1679 // Initialize resource
1680 if(myStackMode != OC_CLIENT)
1682 result = initResources();
1685 // Initialize the SRM Policy Engine
1686 if(result == OC_STACK_OK)
1688 result = SRMInitPolicyEngine();
1689 // TODO after BeachHead delivery: consolidate into single SRMInit()
1693 if(result != OC_STACK_OK)
1695 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1696 deleteAllResources();
1698 stackState = OC_STACK_UNINITIALIZED;
1703 OCStackResult OCStop()
1705 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1707 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1709 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1712 else if (stackState != OC_STACK_INITIALIZED)
1714 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1715 return OC_STACK_ERROR;
1718 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1720 #ifdef WITH_PRESENCE
1721 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1722 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1723 presenceResource.presenceTTL = 0;
1724 #endif // WITH_PRESENCE
1726 // Free memory dynamically allocated for resources
1727 deleteAllResources();
1730 // Remove all observers
1731 DeleteObserverList();
1732 // Remove all the client callbacks
1733 DeleteClientCBList();
1735 // De-init the SRM Policy Engine
1736 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
1737 SRMDeInitPolicyEngine();
1739 stackState = OC_STACK_UNINITIALIZED;
1743 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1748 return CA_MSG_CONFIRM;
1753 return CA_MSG_NONCONFIRM;
1757 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1761 query = strchr (inputUri, '?');
1765 if((query - inputUri) > MAX_URI_LENGTH)
1767 return OC_STACK_INVALID_URI;
1770 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1772 return OC_STACK_INVALID_QUERY;
1775 else if(uriLen > MAX_URI_LENGTH)
1777 return OC_STACK_INVALID_URI;
1783 * A request uri consists of the following components in order:
1785 * optional prefix "coap://"
1787 * IPv6 address "[1234::5678]"
1788 * IPv4 address "192.168.1.1"
1789 * optional port ":5683"
1790 * resource uri "/oc/core..."
1792 * for PRESENCE requests, extract resource type.
1794 static OCStackResult ParseRequestUri(const char *fullUri,
1795 OCTransportAdapter adapter,
1796 OCTransportFlags flags,
1797 OCDevAddr **devAddr,
1799 char **resourceType)
1801 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
1803 OCStackResult result = OC_STACK_OK;
1804 OCDevAddr *da = NULL;
1808 // provide defaults for all returned values
1815 *resourceUri = NULL;
1819 *resourceType = NULL;
1822 // delimit url prefix, if any
1823 const char *start = fullUri;
1824 char *slash2 = strstr(start, "//");
1829 char *slash = strchr(start, '/');
1832 return OC_STACK_INVALID_URI;
1835 // processs url prefix, if any
1836 size_t urlLen = slash - start;
1837 if (urlLen && devAddr)
1838 { // construct OCDevAddr
1839 if (start[0] == '[')
1841 char *close = strchr(++start, ']');
1842 if (!close || close > slash)
1844 return OC_STACK_INVALID_URI;
1847 if (close[1] == ':')
1855 colon = strchr(start, ':');
1856 end = (colon && colon < slash) ? colon : slash;
1858 size_t len = end - start;
1859 if (len > MAX_ADDR_STR_SIZE)
1861 return OC_STACK_INVALID_URI;
1865 uint16_t port = 0; // use standard multicast port
1866 if (colon && colon < slash)
1868 for (colon++; colon < slash; colon++)
1871 if (c < '0' || c > '9')
1873 return OC_STACK_INVALID_URI;
1875 port = 10 * port + c - '0';
1879 da = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
1882 return OC_STACK_NO_MEMORY;
1884 strncpy(da->addr, start, len);
1886 da->adapter = adapter;
1888 if (!strncmp(fullUri, "coaps:", 6))
1890 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
1895 // process resource uri, if any
1897 { // request uri and query
1898 size_t ulen = strlen(slash); // resource uri length
1899 size_t tlen = 0; // resource type length
1902 static const char *strPresence = "/oc/presence?rt=";
1903 static const size_t lenPresence = 15; // = strlen(presence);
1904 if (!strncmp(slash, strPresence, lenPresence))
1906 type = slash + lenPresence;
1907 tlen = ulen - lenPresence;
1912 *resourceUri = (char *)OICMalloc(ulen + 1);
1915 result = OC_STACK_NO_MEMORY;
1918 strcpy(*resourceUri, slash);
1921 if (type && resourceType)
1923 *resourceType = (char *)OICMalloc(tlen + 1);
1926 result = OC_STACK_NO_MEMORY;
1929 strncpy(*resourceType, type, tlen);
1936 // free all returned values
1943 OICFree(*resourceUri);
1947 OICFree(*resourceType);
1952 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
1953 char *resourceUri, char **requestUri)
1955 char uri[CA_MAX_URI_LENGTH];
1957 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
1959 *requestUri = (char *)OICMalloc(strlen(uri) + 1);
1962 return OC_STACK_NO_MEMORY;
1965 strcpy(*requestUri, uri);
1970 * Discover or Perform requests on a specified resource
1972 OCStackResult OCDoResource(OCDoHandle *handle,
1974 const char *requestUri,
1975 const OCDevAddr *destination,
1976 const char *request,
1977 OCConnectivityType connectivityType,
1978 OCQualityOfService qos,
1979 OCCallbackData *cbData,
1980 OCHeaderOption *options,
1983 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1985 // Validate input parameters
1986 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1987 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1988 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
1990 OCStackResult result = OC_STACK_ERROR;
1991 CAResult_t caResult;
1992 CAToken_t token = NULL;
1993 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
1994 ClientCB *clientCB = NULL;
1995 OCDoHandle resHandle = NULL;
1996 CAEndpoint_t *endpoint = NULL;
1997 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
1999 OCTransportAdapter adapter;
2000 OCTransportFlags flags;
2001 // the request contents are put here
2002 CARequestInfo_t requestInfo = { CA_GET };
2003 // requestUri will be parsed into the following three variables
2004 OCDevAddr *devAddr = NULL;
2005 char *resourceUri = NULL;
2006 char *resourceType = NULL;
2008 // To track if memory is allocated for additional header options
2009 uint8_t hdrOptionMemAlloc = 0;
2011 // This validation is broken, but doesn't cause harm
2012 size_t uriLen = strlen(requestUri );
2013 if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
2018 if ((request) && (strlen(request) > MAX_REQUEST_LENGTH))
2020 result = OC_STACK_INVALID_PARAM;
2025 * Support original behavior with address on resourceUri argument.
2027 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2028 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2030 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2031 if (result != OC_STACK_OK)
2033 OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2040 case OC_REST_OBSERVE:
2041 case OC_REST_OBSERVE_ALL:
2042 case OC_REST_CANCEL_OBSERVE:
2043 requestInfo.method = CA_GET;
2046 requestInfo.method = CA_PUT;
2049 requestInfo.method = CA_POST;
2051 case OC_REST_DELETE:
2052 requestInfo.method = CA_DELETE;
2054 case OC_REST_DISCOVER:
2056 if (!destination && !devAddr)
2058 destination = &tmpDevAddr;
2060 // CA_DISCOVER will become GET and isMulticast
2061 requestInfo.method = CA_GET;
2062 requestInfo.isMulticast = true;
2064 #ifdef WITH_PRESENCE
2065 case OC_REST_PRESENCE:
2066 // Replacing method type with GET because "presence"
2067 // is a stack layer only implementation.
2068 requestInfo.method = CA_GET;
2072 result = OC_STACK_INVALID_METHOD;
2076 if (!devAddr && !destination)
2078 OC_LOG_V(DEBUG, TAG, "no devAddr and no destination");
2079 result = OC_STACK_INVALID_PARAM;
2083 /* If not original behavior, use destination argument */
2084 if (destination && !devAddr)
2086 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2089 result = OC_STACK_NO_MEMORY;
2092 *devAddr = *destination;
2095 resHandle = GenerateInvocationHandle();
2098 result = OC_STACK_NO_MEMORY;
2102 caResult = CAGenerateToken(&token, tokenLength);
2103 if (caResult != CA_STATUS_OK)
2105 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2109 // fill in request data
2110 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2111 requestInfo.info.token = token;
2112 requestInfo.info.tokenLength = tokenLength;
2113 requestInfo.info.resourceUri = resourceUri;
2114 requestInfo.info.payload = (char *)request;
2115 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2117 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2118 options, numOptions, OC_OBSERVE_REGISTER);
2119 if (result != OC_STACK_OK)
2123 hdrOptionMemAlloc = 1;
2124 requestInfo.info.numOptions = numOptions + 1;
2128 requestInfo.info.options = (CAHeaderOption_t*)options;
2129 requestInfo.info.numOptions = numOptions;
2132 // create remote endpoint
2133 result = OCCreateEndpoint(devAddr, &endpoint);
2134 if (result != OC_STACK_OK)
2136 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2140 // prepare for response
2141 #ifdef WITH_PRESENCE
2142 if (method == OC_REST_PRESENCE)
2144 char *presenceUri = NULL;
2145 result = OCPreparePresence(endpoint, resourceUri, &presenceUri);
2146 if (OC_STACK_OK != result)
2150 OICFree(resourceUri);
2151 resourceUri = presenceUri;
2155 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2156 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2157 method, devAddr, resourceUri, resourceType, ttl);
2158 if (OC_STACK_OK != result)
2163 devAddr = NULL; // Client CB list entry now owns it
2164 resourceUri = NULL; // Client CB list entry now owns it
2165 resourceType = NULL; // Client CB list entry now owns it
2168 caResult = CASendRequest(endpoint, &requestInfo);
2169 if (caResult != CA_STATUS_OK)
2171 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
2172 result = OC_STACK_COMM_ERROR;
2178 *handle = resHandle;
2182 if (result != OC_STACK_OK)
2184 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
2185 FindAndDeleteClientCB(clientCB);
2186 CADestroyToken(token);
2194 OICFree(resourceUri);
2195 OICFree(resourceType);
2197 if (hdrOptionMemAlloc)
2199 OICFree(requestInfo.info.options);
2204 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2208 * This ftn is implemented one of two ways in the case of observation:
2210 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2211 * Remove the callback associated on client side.
2212 * When the next notification comes in from server,
2213 * reply with RESET message to server.
2214 * Keep in mind that the server will react to RESET only
2215 * if the last notification was sent as CON
2217 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2218 * and it is associated with an observe request
2219 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2220 * Send CON Observe request to server with
2221 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2222 * Remove the callback associated on client side.
2224 OCStackResult ret = OC_STACK_OK;
2225 CAEndpoint_t* endpoint = NULL;
2226 CAResult_t caResult;
2227 CAInfo_t requestData = {};
2228 CARequestInfo_t requestInfo = {};
2232 return OC_STACK_INVALID_PARAM;
2235 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
2237 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2240 OC_LOG(ERROR, TAG, PCF("Client callback not found. Called OCCancel twice?"));
2244 switch (clientCB->method)
2246 case OC_REST_OBSERVE:
2247 case OC_REST_OBSERVE_ALL:
2248 OC_LOG(INFO, TAG, PCF("Canceling observation"));
2249 if (qos != OC_HIGH_QOS)
2251 FindAndDeleteClientCB(clientCB);
2255 requestData.type = qualityOfServiceToMessageType(qos);
2256 requestData.token = clientCB->token;
2257 requestData.tokenLength = clientCB->tokenLength;
2258 if (CreateObserveHeaderOption (&(requestData.options),
2259 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2261 return OC_STACK_ERROR;
2263 requestData.numOptions = numOptions + 1;
2264 requestInfo.method = CA_GET;
2265 requestInfo.info = requestData;
2267 ret = OCCreateEndpoint(clientCB->devAddr, &endpoint);
2268 if (ret != OC_STACK_OK)
2270 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2275 caResult = CASendRequest(endpoint, &requestInfo);
2276 if (caResult != CA_STATUS_OK)
2278 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2279 ret = OC_STACK_ERROR;
2281 ret = CAResultToOCResult (caResult);
2284 #ifdef WITH_PRESENCE
2285 case OC_REST_PRESENCE:
2286 FindAndDeleteClientCB(clientCB);
2291 ret = OC_STACK_INVALID_METHOD;
2296 OCDestroyEndpoint(endpoint);
2297 if (requestData.numOptions > 0)
2299 OICFree(requestData.options);
2306 * @brief Register Persistent storage callback.
2307 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2309 * OC_STACK_OK - No errors; Success
2310 * OC_STACK_INVALID_PARAM - Invalid parameter
2312 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2314 OC_LOG(INFO, TAG, PCF("RegisterPersistentStorageHandler !!"));
2315 if(!persistentStorageHandler)
2317 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2318 return OC_STACK_INVALID_PARAM;
2322 if( !persistentStorageHandler->open ||
2323 !persistentStorageHandler->close ||
2324 !persistentStorageHandler->read ||
2325 !persistentStorageHandler->unlink ||
2326 !persistentStorageHandler->write)
2328 OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2329 return OC_STACK_INVALID_PARAM;
2332 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2335 #ifdef WITH_PRESENCE
2337 OCStackResult OCProcessPresence()
2339 OCStackResult result = OC_STACK_OK;
2341 // the following line floods the log with messages that are irrelevant
2342 // to most purposes. Uncomment as needed.
2343 //OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
2344 ClientCB* cbNode = NULL;
2345 OCClientResponse clientResponse;
2346 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2348 LL_FOREACH(cbList, cbNode)
2350 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2355 uint32_t now = GetTicks(0);
2356 OC_LOG_V(DEBUG, TAG, "this TTL level %d",
2357 cbNode->presence->TTLlevel);
2358 OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2360 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
2365 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2367 OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2368 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2371 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2373 OC_LOG(DEBUG, TAG, PCF("No more timeout ticks"));
2375 clientResponse.sequenceNumber = 0;
2376 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2377 clientResponse.devAddr = *cbNode->devAddr;
2378 FixUpClientResponse(&clientResponse);
2379 clientResponse.resJSONPayload = NULL;
2381 // Increment the TTLLevel (going to a next state), so we don't keep
2382 // sending presence notification to client.
2383 cbNode->presence->TTLlevel++;
2384 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2385 cbNode->presence->TTLlevel);
2387 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2388 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2390 FindAndDeleteClientCB(cbNode);
2394 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2399 CAResult_t caResult = CA_STATUS_OK;
2400 CAEndpoint_t* endpoint = NULL;
2401 CAInfo_t requestData ={};
2402 CARequestInfo_t requestInfo = {};
2404 OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
2406 result = OCCreateEndpoint(cbNode->devAddr, &endpoint);
2407 if (result != OC_STACK_OK)
2409 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2413 requestData.type = CA_MSG_NONCONFIRM;
2414 requestData.token = cbNode->token;
2415 requestData.tokenLength = cbNode->tokenLength;
2416 requestInfo.method = CA_GET;
2417 requestInfo.info = requestData;
2419 caResult = CASendRequest(endpoint, &requestInfo);
2420 OCDestroyEndpoint(endpoint);
2422 if (caResult != CA_STATUS_OK)
2424 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2428 cbNode->presence->TTLlevel++;
2429 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2432 if (result != OC_STACK_OK)
2434 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2438 #endif // WITH_PRESENCE
2440 OCStackResult OCProcess()
2442 #ifdef WITH_PRESENCE
2443 OCProcessPresence();
2445 CAHandleRequestResponse();
2450 #ifdef WITH_PRESENCE
2451 OCStackResult OCStartPresence(const uint32_t ttl)
2453 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2454 OCChangeResourceProperty(
2455 &(((OCResource *)presenceResource.handle)->resourceProperties),
2458 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2460 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2461 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to max value"));
2465 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2466 OC_LOG(INFO, TAG, PCF("Setting Presence TTL to default value"));
2470 presenceResource.presenceTTL = ttl;
2472 OC_LOG_V(DEBUG, TAG, "Presence TTL is %lu seconds", presenceResource.presenceTTL);
2474 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2476 presenceState = OC_PRESENCE_INITIALIZED;
2478 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2479 OICStrcpy(devAddr.addr, sizeof(devAddr.addr), OC_MULTICAST_IP);
2480 devAddr.port = OC_MULTICAST_PORT;
2482 CAToken_t caToken = NULL;
2483 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2484 if (caResult != CA_STATUS_OK)
2486 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2487 CADestroyToken(caToken);
2488 return OC_STACK_ERROR;
2491 AddObserver(OC_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2492 (OCResource *)presenceResource.handle, OC_LOW_QOS, &devAddr);
2493 CADestroyToken(caToken);
2496 // Each time OCStartPresence is called
2497 // a different random 32-bit integer number is used
2498 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2500 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2501 OC_PRESENCE_TRIGGER_CREATE);
2504 OCStackResult OCStopPresence()
2506 OCStackResult result = OC_STACK_ERROR;
2508 if(presenceResource.handle)
2510 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2512 // make resource inactive
2513 result = OCChangeResourceProperty(
2514 &(((OCResource *) presenceResource.handle)->resourceProperties),
2518 if(result != OC_STACK_OK)
2521 PCF("Changing the presence resource properties to ACTIVE not successful"));
2525 return SendStopNotification();
2529 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
2530 void* callbackParameter)
2532 defaultDeviceHandler = entityHandler;
2533 defaultDeviceHandlerCallbackParameter = callbackParameter;
2538 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
2540 OC_LOG(INFO, TAG, PCF("Entering OCSetPlatformInfo"));
2542 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
2544 if (validatePlatformInfo(platformInfo))
2546 return SavePlatformInfo(platformInfo);
2550 return OC_STACK_INVALID_PARAM;
2555 return OC_STACK_ERROR;
2559 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2561 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2563 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
2565 OC_LOG(ERROR, TAG, PCF("Null or empty device name."));
2566 return OC_STACK_INVALID_PARAM;
2569 return SaveDeviceInfo(deviceInfo);
2572 OCStackResult OCCreateResource(OCResourceHandle *handle,
2573 const char *resourceTypeName,
2574 const char *resourceInterfaceName,
2575 const char *uri, OCEntityHandler entityHandler,
2576 void* callbackParam,
2577 uint8_t resourceProperties)
2580 OCResource *pointer = NULL;
2582 OCStackResult result = OC_STACK_ERROR;
2584 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2586 if(myStackMode == OC_CLIENT)
2588 return OC_STACK_INVALID_PARAM;
2590 // Validate parameters
2591 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2593 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
2594 return OC_STACK_INVALID_URI;
2596 // Is it presented during resource discovery?
2597 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
2599 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2600 return OC_STACK_INVALID_PARAM;
2603 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2605 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2608 // Make sure resourceProperties bitmask has allowed properties specified
2609 if (resourceProperties
2610 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE))
2612 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2613 return OC_STACK_INVALID_PARAM;
2616 // If the headResource is NULL, then no resources have been created...
2617 pointer = headResource;
2620 // At least one resources is in the resource list, so we need to search for
2621 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2624 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
2626 OC_LOG(ERROR, TAG, PCF("URI already in use"));
2627 return OC_STACK_INVALID_PARAM;
2629 pointer = pointer->next;
2632 // Create the pointer and insert it into the resource list
2633 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
2636 result = OC_STACK_NO_MEMORY;
2639 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2641 insertResource(pointer);
2644 str = OICStrdup(uri);
2647 result = OC_STACK_NO_MEMORY;
2652 // Set properties. Set OC_ACTIVE
2653 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2656 // Add the resourcetype to the resource
2657 result = BindResourceTypeToResource(pointer, resourceTypeName);
2658 if (result != OC_STACK_OK)
2660 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2664 // Add the resourceinterface to the resource
2665 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2666 if (result != OC_STACK_OK)
2668 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2672 // If an entity handler has been passed, attach it to the newly created
2673 // resource. Otherwise, set the default entity handler.
2676 pointer->entityHandler = entityHandler;
2677 pointer->entityHandlerCallbackParam = callbackParam;
2681 pointer->entityHandler = defaultResourceEHandler;
2682 pointer->entityHandlerCallbackParam = NULL;
2686 result = OC_STACK_OK;
2688 #ifdef WITH_PRESENCE
2689 if(presenceResource.handle)
2691 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2692 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
2696 if (result != OC_STACK_OK)
2698 // Deep delete of resource and other dynamic elements that it contains
2699 deleteResource(pointer);
2706 OCStackResult OCBindResource(
2707 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2709 OCResource *resource = NULL;
2712 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2714 // Validate parameters
2715 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2716 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2717 // Container cannot contain itself
2718 if (collectionHandle == resourceHandle)
2720 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2721 return OC_STACK_INVALID_PARAM;
2724 // Use the handle to find the resource in the resource linked list
2725 resource = findResource((OCResource *) collectionHandle);
2728 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2729 return OC_STACK_INVALID_PARAM;
2732 // Look for an open slot to add add the child resource.
2733 // If found, add it and return success
2734 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2736 if (!resource->rsrcResources[i])
2738 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2739 OC_LOG(INFO, TAG, PCF("resource bound"));
2741 #ifdef WITH_PRESENCE
2742 if(presenceResource.handle)
2744 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2745 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2746 OC_PRESENCE_TRIGGER_CHANGE);
2754 // Unable to add resourceHandle, so return error
2755 return OC_STACK_ERROR;
2758 OCStackResult OCUnBindResource(
2759 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2761 OCResource *resource = NULL;
2764 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2766 // Validate parameters
2767 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2768 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2769 // Container cannot contain itself
2770 if (collectionHandle == resourceHandle)
2772 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2773 return OC_STACK_INVALID_PARAM;
2776 // Use the handle to find the resource in the resource linked list
2777 resource = findResource((OCResource *) collectionHandle);
2780 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2781 return OC_STACK_INVALID_PARAM;
2784 // Look for an open slot to add add the child resource.
2785 // If found, add it and return success
2786 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2788 if (resourceHandle == resource->rsrcResources[i])
2790 resource->rsrcResources[i] = (OCResource *) NULL;
2791 OC_LOG(INFO, TAG, PCF("resource unbound"));
2793 // Send notification when resource is unbounded successfully.
2794 #ifdef WITH_PRESENCE
2795 if(presenceResource.handle)
2797 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2798 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2799 OC_PRESENCE_TRIGGER_CHANGE);
2806 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2808 // Unable to add resourceHandle, so return error
2809 return OC_STACK_ERROR;
2812 OCStackResult BindResourceTypeToResource(OCResource* resource,
2813 const char *resourceTypeName)
2815 OCResourceType *pointer = NULL;
2817 OCStackResult result = OC_STACK_ERROR;
2819 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
2821 // Validate parameters
2822 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2823 // TODO: Does resource attribute representation really have to be maintained in stack?
2824 // Is it presented during resource discovery?
2826 // Create the resourcetype and insert it into the resource list
2827 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
2830 result = OC_STACK_NO_MEMORY;
2834 // Set the resourceTypeName
2835 str = OICStrdup(resourceTypeName);
2838 result = OC_STACK_NO_MEMORY;
2841 pointer->resourcetypename = str;
2843 insertResourceType(resource, pointer);
2844 result = OC_STACK_OK;
2847 if (result != OC_STACK_OK)
2856 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2857 const char *resourceInterfaceName)
2859 OCResourceInterface *pointer = NULL;
2861 OCStackResult result = OC_STACK_ERROR;
2863 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2865 // Validate parameters
2866 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2868 //TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2870 // Create the resourceinterface and insert it into the resource list
2871 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
2874 result = OC_STACK_NO_MEMORY;
2878 // Set the resourceinterface name
2879 str = OICStrdup(resourceInterfaceName);
2882 result = OC_STACK_NO_MEMORY;
2885 pointer->name = str;
2887 // Bind the resourceinterface to the resource
2888 insertResourceInterface(resource, pointer);
2890 result = OC_STACK_OK;
2893 if (result != OC_STACK_OK)
2902 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2903 const char *resourceTypeName)
2906 OCStackResult result = OC_STACK_ERROR;
2907 OCResource *resource = NULL;
2909 // Make sure resource exists
2910 resource = findResource((OCResource *) handle);
2913 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2914 return OC_STACK_ERROR;
2917 // call internal function
2918 result = BindResourceTypeToResource(resource, resourceTypeName);
2920 #ifdef WITH_PRESENCE
2921 if(presenceResource.handle)
2923 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2924 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2931 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2932 const char *resourceInterfaceName)
2935 OCStackResult result = OC_STACK_ERROR;
2936 OCResource *resource = NULL;
2938 // Make sure resource exists
2939 resource = findResource((OCResource *) handle);
2942 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2943 return OC_STACK_ERROR;
2946 // call internal function
2947 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2949 #ifdef WITH_PRESENCE
2950 if(presenceResource.handle)
2952 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2953 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2960 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
2962 OCResource *pointer = headResource;
2964 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2965 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2969 *numResources = *numResources + 1;
2970 pointer = pointer->next;
2975 OCResourceHandle OCGetResourceHandle(uint8_t index)
2977 OCResource *pointer = headResource;
2979 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2981 // Iterate through the list
2982 for( uint8_t i = 0; i < index && pointer; ++i)
2984 pointer = pointer->next;
2986 return (OCResourceHandle) pointer;
2989 OCStackResult OCDeleteResource(OCResourceHandle handle)
2991 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2995 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2996 return OC_STACK_INVALID_PARAM;
2999 OCResource *resource = findResource((OCResource *) handle);
3000 if (resource == NULL)
3002 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3003 return OC_STACK_NO_RESOURCE;
3006 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3008 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
3009 return OC_STACK_ERROR;
3015 const char *OCGetResourceUri(OCResourceHandle handle)
3017 OCResource *resource = NULL;
3018 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
3020 resource = findResource((OCResource *) handle);
3023 return resource->uri;
3025 return (const char *) NULL;
3028 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3030 OCResource *resource = NULL;
3031 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
3033 resource = findResource((OCResource *) handle);
3036 return resource->resourceProperties;
3038 return (OCResourceProperty)-1;
3041 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3042 uint8_t *numResourceTypes)
3044 OCResource *resource = NULL;
3045 OCResourceType *pointer = NULL;
3047 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
3048 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3049 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3051 *numResourceTypes = 0;
3053 resource = findResource((OCResource *) handle);
3056 pointer = resource->rsrcType;
3059 *numResourceTypes = *numResourceTypes + 1;
3060 pointer = pointer->next;
3066 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3068 OCResourceType *resourceType = NULL;
3070 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
3072 resourceType = findResourceTypeAtIndex(handle, index);
3075 return resourceType->resourcetypename;
3077 return (const char *) NULL;
3080 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3081 uint8_t *numResourceInterfaces)
3083 OCResourceInterface *pointer = NULL;
3084 OCResource *resource = NULL;
3086 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
3088 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3089 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3091 *numResourceInterfaces = 0;
3092 resource = findResource((OCResource *) handle);
3095 pointer = resource->rsrcInterface;
3098 *numResourceInterfaces = *numResourceInterfaces + 1;
3099 pointer = pointer->next;
3105 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3107 OCResourceInterface *resourceInterface = NULL;
3109 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
3111 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3112 if (resourceInterface)
3114 return resourceInterface->name;
3116 return (const char *) NULL;
3119 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3122 OCResource *resource = NULL;
3124 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
3126 if (index >= MAX_CONTAINED_RESOURCES)
3131 resource = findResource((OCResource *) collectionHandle);
3137 return resource->rsrcResources[index];
3140 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3141 OCEntityHandler entityHandler,
3142 void* callbackParam)
3144 OCResource *resource = NULL;
3146 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
3148 // Validate parameters
3149 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3151 // Use the handle to find the resource in the resource linked list
3152 resource = findResource((OCResource *)handle);
3155 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3156 return OC_STACK_ERROR;
3160 resource->entityHandler = entityHandler;
3161 resource->entityHandlerCallbackParam = callbackParam;
3163 #ifdef WITH_PRESENCE
3164 if(presenceResource.handle)
3166 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3167 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3174 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3176 OCResource *resource = NULL;
3178 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
3180 // Use the handle to find the resource in the resource linked list
3181 resource = findResource((OCResource *)handle);
3184 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3189 return resource->entityHandler;
3192 void incrementSequenceNumber(OCResource * resPtr)
3194 // Increment the sequence number
3195 resPtr->sequenceNum += 1;
3196 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3198 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3203 #ifdef WITH_PRESENCE
3204 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3205 OCPresenceTrigger trigger)
3207 OCResource *resPtr = NULL;
3208 OCStackResult result = OC_STACK_ERROR;
3209 OCMethod method = OC_REST_PRESENCE;
3210 uint32_t maxAge = 0;
3211 resPtr = findResource((OCResource *) presenceResource.handle);
3214 return OC_STACK_NO_RESOURCE;
3217 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3219 maxAge = presenceResource.presenceTTL;
3221 result = SendAllObserverNotification(method, resPtr, maxAge,
3222 trigger, resourceType, OC_LOW_QOS);
3228 OCStackResult SendStopNotification()
3230 OCResource *resPtr = NULL;
3231 OCStackResult result = OC_STACK_ERROR;
3232 OCMethod method = OC_REST_PRESENCE;
3233 resPtr = findResource((OCResource *) presenceResource.handle);
3236 return OC_STACK_NO_RESOURCE;
3239 // maxAge is 0. ResourceType is NULL.
3240 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3246 #endif // WITH_PRESENCE
3247 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3250 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
3252 OCResource *resPtr = NULL;
3253 OCStackResult result = OC_STACK_ERROR;
3254 OCMethod method = OC_REST_NOMETHOD;
3255 uint32_t maxAge = 0;
3257 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
3258 #ifdef WITH_PRESENCE
3259 if(handle == presenceResource.handle)
3263 #endif // WITH_PRESENCE
3264 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3266 // Verify that the resource exists
3267 resPtr = findResource ((OCResource *) handle);
3270 return OC_STACK_NO_RESOURCE;
3274 //only increment in the case of regular observing (not presence)
3275 incrementSequenceNumber(resPtr);
3276 method = OC_REST_OBSERVE;
3277 maxAge = MAX_OBSERVE_AGE;
3278 #ifdef WITH_PRESENCE
3279 result = SendAllObserverNotification (method, resPtr, maxAge,
3280 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3282 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3289 OCNotifyListOfObservers (OCResourceHandle handle,
3290 OCObservationId *obsIdList,
3291 uint8_t numberOfIds,
3292 const char *notificationJSONPayload,
3293 OCQualityOfService qos)
3295 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3297 OCResource *resPtr = NULL;
3298 //TODO: we should allow the server to define this
3299 uint32_t maxAge = MAX_OBSERVE_AGE;
3301 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3302 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3303 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
3305 // Verify that the resource exists
3306 resPtr = findResource ((OCResource *) handle);
3307 if (NULL == resPtr || myStackMode == OC_CLIENT)
3309 return OC_STACK_NO_RESOURCE;
3313 incrementSequenceNumber(resPtr);
3315 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3316 notificationJSONPayload, maxAge, qos));
3319 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3321 OCStackResult result = OC_STACK_ERROR;
3322 OCServerRequest *serverRequest = NULL;
3324 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3326 // Validate input parameters
3327 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3328 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3330 // TODO: Placeholder for creating a response entry when implementing
3331 // block transfer feature
3333 // If a response payload is present, check if block transfer is required
3334 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
3335 (const char *)ehResponse->payload, ehResponse->payloadSize))
3337 OC_LOG(INFO, TAG, PCF("Block transfer required"));
3339 // Persistent response buffer is needed for block transfer
3340 if (!ehResponse->persistentBufferFlag)
3342 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
3343 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
3345 // TODO: Placeholder for block transfer handling
3346 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
3347 // when implementing the block transfer feature
3352 // Get pointer to request info
3353 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3356 result = serverRequest->ehResponseHandler(ehResponse);
3362 //-----------------------------------------------------------------------------
3363 // Private internal function definitions
3364 //-----------------------------------------------------------------------------
3365 static OCDoHandle GenerateInvocationHandle()
3367 OCDoHandle handle = NULL;
3368 // Generate token here, it will be deleted when the transaction is deleted
3369 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3372 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3378 #ifdef WITH_PRESENCE
3379 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3380 OCResourceProperty resourceProperties, uint8_t enable)
3384 return OC_STACK_INVALID_PARAM;
3386 if (resourceProperties
3387 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3389 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3390 return OC_STACK_INVALID_PARAM;
3394 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3398 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3404 OCStackResult initResources()
3406 OCStackResult result = OC_STACK_OK;
3407 // Init application resource vars
3408 headResource = NULL;
3409 tailResource = NULL;
3410 // Init Virtual Resources
3411 #ifdef WITH_PRESENCE
3412 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3413 //presenceResource.token = OCGenerateCoAPToken();
3414 result = OCCreateResource(&presenceResource.handle,
3415 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3421 //make resource inactive
3422 result = OCChangeResourceProperty(
3423 &(((OCResource *) presenceResource.handle)->resourceProperties),
3427 if (result == OC_STACK_OK)
3429 result = SRMInitSecureResources();
3435 void insertResource(OCResource *resource)
3439 headResource = resource;
3440 tailResource = resource;
3444 tailResource->next = resource;
3445 tailResource = resource;
3447 resource->next = NULL;
3450 OCResource *findResource(OCResource *resource)
3452 OCResource *pointer = headResource;
3456 if (pointer == resource)
3460 pointer = pointer->next;
3465 void deleteAllResources()
3467 OCResource *pointer = headResource;
3468 OCResource *temp = NULL;
3472 temp = pointer->next;
3473 #ifdef WITH_PRESENCE
3474 if(pointer != (OCResource *) presenceResource.handle)
3476 #endif // WITH_PRESENCE
3477 deleteResource(pointer);
3478 #ifdef WITH_PRESENCE
3480 #endif // WITH_PRESENCE
3484 SRMDeInitSecureResources();
3486 #ifdef WITH_PRESENCE
3487 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3488 // presence notification attributed to their deletion to be processed.
3489 deleteResource((OCResource *) presenceResource.handle);
3490 #endif // WITH_PRESENCE
3493 OCStackResult deleteResource(OCResource *resource)
3495 OCResource *prev = NULL;
3496 OCResource *temp = NULL;
3498 temp = headResource;
3501 if (temp == resource)
3503 // Invalidate all Resource Properties.
3504 resource->resourceProperties = (OCResourceProperty) 0;
3505 #ifdef WITH_PRESENCE
3506 if(resource != (OCResource *) presenceResource.handle)
3508 #endif // WITH_PRESENCE
3509 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3510 #ifdef WITH_PRESENCE
3513 if(presenceResource.handle)
3515 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3516 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
3519 // Only resource in list.
3520 if (temp == headResource && temp == tailResource)
3522 headResource = NULL;
3523 tailResource = NULL;
3526 else if (temp == headResource)
3528 headResource = temp->next;
3531 else if (temp == tailResource)
3533 tailResource = prev;
3534 tailResource->next = NULL;
3538 prev->next = temp->next;
3541 deleteResourceElements(temp);
3552 return OC_STACK_ERROR;
3555 void deleteResourceElements(OCResource *resource)
3563 OICFree(resource->uri);
3565 // Delete resourcetype linked list
3566 deleteResourceType(resource->rsrcType);
3568 // Delete resourceinterface linked list
3569 deleteResourceInterface(resource->rsrcInterface);
3572 void deleteResourceType(OCResourceType *resourceType)
3574 OCResourceType *pointer = resourceType;
3575 OCResourceType *next = NULL;
3579 next = pointer->next;
3580 OICFree(pointer->resourcetypename);
3586 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3588 OCResourceInterface *pointer = resourceInterface;
3589 OCResourceInterface *next = NULL;
3593 next = pointer->next;
3594 OICFree(pointer->name);
3600 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3602 OCResourceType *pointer = NULL;
3603 OCResourceType *previous = NULL;
3604 if (!resource || !resourceType)
3608 // resource type list is empty.
3609 else if (!resource->rsrcType)
3611 resource->rsrcType = resourceType;
3615 pointer = resource->rsrcType;
3619 // resource type already exists. Free 2nd arg and return.
3620 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
3622 OICFree(resourceType->resourcetypename);
3623 OICFree(resourceType);
3627 pointer = pointer->next;
3629 previous->next = resourceType;
3631 resourceType->next = NULL;
3634 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3636 OCResource *resource = NULL;
3637 OCResourceType *pointer = NULL;
3639 // Find the specified resource
3640 resource = findResource((OCResource *) handle);
3646 // Make sure a resource has a resourcetype
3647 if (!resource->rsrcType)
3652 // Iterate through the list
3653 pointer = resource->rsrcType;
3654 for(uint8_t i = 0; i< index && pointer; ++i)
3656 pointer = pointer->next;
3661 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3663 if(resourceTypeList && resourceTypeName)
3665 OCResourceType * rtPointer = resourceTypeList;
3666 while(resourceTypeName && rtPointer)
3668 if(rtPointer->resourcetypename &&
3669 strcmp(resourceTypeName, (const char *)
3670 (rtPointer->resourcetypename)) == 0)
3674 rtPointer = rtPointer->next;
3682 * Insert a new interface into interface linked list only if not already present.
3683 * If alredy present, 2nd arg is free'd.
3684 * Default interface will always be first if present.
3686 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
3688 OCResourceInterface *pointer = NULL;
3689 OCResourceInterface *previous = NULL;
3691 newInterface->next = NULL;
3693 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
3695 if (!*firstInterface)
3697 *firstInterface = newInterface;
3699 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3701 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3703 OICFree(newInterface->name);
3704 OICFree(newInterface);
3709 newInterface->next = *firstInterface;
3710 *firstInterface = newInterface;
3715 pointer = *firstInterface;
3718 if (strcmp(newInterface->name, pointer->name) == 0)
3720 OICFree(newInterface->name);
3721 OICFree(newInterface);
3725 pointer = pointer->next;
3727 previous->next = newInterface;
3731 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3734 OCResource *resource = NULL;
3735 OCResourceInterface *pointer = NULL;
3737 // Find the specified resource
3738 resource = findResource((OCResource *) handle);
3744 // Make sure a resource has a resourceinterface
3745 if (!resource->rsrcInterface)
3750 // Iterate through the list
3751 pointer = resource->rsrcInterface;
3753 for (uint8_t i = 0; i < index && pointer; ++i)
3755 pointer = pointer->next;
3760 bool OCIsPacketTransferRequired(const char *request, const char *response, size_t size)
3762 bool result = false;
3764 // Determine if we are checking a request or a response
3767 // If size is greater than 0, use it for the request size value, otherwise
3768 // assume request is null terminated and use strlen for size value
3769 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3776 // If size is greater than 0, use it for the response size value, otherwise
3777 // assume response is null terminated and use strlen for size value
3778 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3787 * This function splits the uri using the '?' delimiter.
3788 * "uriWithoutQuery" is the block of characters between the beginning
3789 * till the delimiter or '\0' which ever comes first.
3790 * "query" is whatever is to the right of the delimiter if present.
3791 * No delimiter sets the query to NULL.
3792 * If either are present, they will be malloc'ed into the params 2, 3.
3793 * The first param, *uri is left untouched.
3795 * NOTE: This function does not account for whitespace at the end of the uri NOR
3796 * malformed uri's with '??'. Whitespace at the end will be assumed to be
3797 * part of the query.
3799 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
3803 return OC_STACK_INVALID_URI;
3805 if(!query || !uriWithoutQuery)
3807 return OC_STACK_INVALID_PARAM;
3811 *uriWithoutQuery = NULL;
3813 size_t uriWithoutQueryLen = 0;
3814 size_t queryLen = 0;
3815 size_t uriLen = strlen(uri);
3817 char *pointerToDelimiter = strstr(uri, "?");
3819 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : pointerToDelimiter - uri;
3820 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
3822 if (uriWithoutQueryLen)
3824 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
3825 if (!*uriWithoutQuery)
3829 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
3833 *query = (char *) OICCalloc(queryLen + 1, 1);
3836 OICFree(*uriWithoutQuery);
3837 *uriWithoutQuery = NULL;
3840 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
3846 return OC_STACK_NO_MEMORY;
3849 const uint8_t* OCGetServerInstanceID(void)
3851 static bool generated = false;
3852 static ServerID sid;
3858 if (OCGenerateUuid(sid) != RAND_UUID_OK)
3860 OC_LOG(FATAL, TAG, PCF("Generate UUID for Server Instance failed!"));
3867 const char* OCGetServerInstanceIDString(void)
3869 static bool generated = false;
3870 static char sidStr[UUID_STRING_SIZE];
3877 const uint8_t* sid = OCGetServerInstanceID();
3879 if(OCConvertUuidToString(sid, sidStr) != RAND_UUID_OK)
3881 OC_LOG(FATAL, TAG, PCF("Generate UUID String for Server Instance failed!"));
3889 CAResult_t OCSelectNetwork()
3891 CAResult_t retResult = CA_STATUS_FAILED;
3892 CAResult_t caResult = CA_STATUS_OK;
3894 CATransportAdapter_t connTypes[] = {
3896 CA_ADAPTER_RFCOMM_BTEDR,
3897 CA_ADAPTER_GATT_BTLE};
3898 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
3900 for(int i = 0; i<numConnTypes; i++)
3902 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
3903 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
3905 caResult = CASelectNetwork(connTypes[i]);
3906 if(caResult == CA_STATUS_OK)
3908 retResult = CA_STATUS_OK;
3913 if(retResult != CA_STATUS_OK)
3915 return caResult; // Returns error of appropriate transport that failed fatally.
3921 OCStackResult CAResultToOCResult(CAResult_t caResult)
3927 case CA_STATUS_INVALID_PARAM:
3928 return OC_STACK_INVALID_PARAM;
3929 case CA_ADAPTER_NOT_ENABLED:
3930 return OC_STACK_ADAPTER_NOT_ENABLED;
3931 case CA_SERVER_STARTED_ALREADY:
3933 case CA_SERVER_NOT_STARTED:
3934 return OC_STACK_ERROR;
3935 case CA_DESTINATION_NOT_REACHABLE:
3936 return OC_STACK_COMM_ERROR;
3937 case CA_SOCKET_OPERATION_FAILED:
3938 return OC_STACK_COMM_ERROR;
3939 case CA_SEND_FAILED:
3940 return OC_STACK_COMM_ERROR;
3941 case CA_RECEIVE_FAILED:
3942 return OC_STACK_COMM_ERROR;
3943 case CA_MEMORY_ALLOC_FAILED:
3944 return OC_STACK_NO_MEMORY;
3945 case CA_REQUEST_TIMEOUT:
3946 return OC_STACK_TIMEOUT;
3947 case CA_DESTINATION_DISCONNECTED:
3948 return OC_STACK_COMM_ERROR;
3949 case CA_STATUS_FAILED:
3950 return OC_STACK_ERROR;
3951 case CA_NOT_SUPPORTED:
3952 return OC_STACK_NOTIMPL;
3954 return OC_STACK_ERROR;