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
33 #ifndef __STDC_FORMAT_MACROS
34 #define __STDC_FORMAT_MACROS
36 #ifndef __STDC_LIMIT_MACROS
37 #define __STDC_LIMIT_MACROS
44 #include "ocstackinternal.h"
45 #include "ocresourcehandler.h"
46 #include "occlientcb.h"
47 #include "ocobserve.h"
49 #include "oic_malloc.h"
50 #include "oic_string.h"
52 #include "ocserverrequest.h"
53 #include "secureresourcemanager.h"
54 #include "psinterface.h"
55 #include "doxmresource.h"
57 #include "cainterface.h"
58 #include "ocpayload.h"
59 #include "ocpayloadcbor.h"
60 #include "platform_features.h"
62 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
63 #include "routingutility.h"
64 #ifdef ROUTING_GATEWAY
65 #include "routingmanager.h"
70 #include "oickeepalive.h"
73 //#ifdef DIRECT_PAIRING
74 #include "directpairing.h"
77 #ifdef HAVE_ARDUINO_TIME_H
80 #ifdef HAVE_SYS_TIME_H
83 #include "coap_time.h"
87 #ifdef HAVE_ARPA_INET_H
88 #include <arpa/inet.h>
92 #define UINT32_MAX (0xFFFFFFFFUL)
95 //-----------------------------------------------------------------------------
97 //-----------------------------------------------------------------------------
100 OC_STACK_UNINITIALIZED = 0,
101 OC_STACK_INITIALIZED,
102 OC_STACK_UNINIT_IN_PROGRESS
108 OC_PRESENCE_UNINITIALIZED = 0,
109 OC_PRESENCE_INITIALIZED
113 //-----------------------------------------------------------------------------
115 //-----------------------------------------------------------------------------
116 static OCStackState stackState = OC_STACK_UNINITIALIZED;
118 OCResource *headResource = NULL;
119 static OCResource *tailResource = NULL;
120 static OCResourceHandle platformResource = {0};
121 static OCResourceHandle deviceResource = {0};
123 static OCResourceHandle brokerResource = {0};
127 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
128 static PresenceResource presenceResource = {0};
129 static uint8_t PresenceTimeOutSize = 0;
130 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
133 static OCMode myStackMode;
135 //TODO: revisit this design
136 static bool gRASetInfo = false;
138 OCDeviceEntityHandler defaultDeviceHandler;
139 void* defaultDeviceHandlerCallbackParameter = NULL;
140 static const char COAP_TCP[] = "coap+tcp:";
141 static const char COAPS_TCP[] = "coaps+tcp:";
142 static const char CORESPEC[] = "core";
144 //-----------------------------------------------------------------------------
146 //-----------------------------------------------------------------------------
147 #define TAG "OIC_RI_STACK"
148 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
149 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
150 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
151 TAG, #arg " is NULL"); return (retVal); } }
152 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
153 TAG, #arg " is NULL"); return; } }
154 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
157 //TODO: we should allow the server to define this
158 #define MAX_OBSERVE_AGE (0x2FFFFUL)
160 #define MILLISECONDS_PER_SECOND (1000)
162 //-----------------------------------------------------------------------------
163 // Private internal function prototypes
164 //-----------------------------------------------------------------------------
167 * Generate handle of OCDoResource invocation for callback management.
169 * @return Generated OCDoResource handle.
171 static OCDoHandle GenerateInvocationHandle();
174 * Initialize resource data structures, variables, etc.
176 * @return ::OC_STACK_OK on success, some other value upon failure.
178 static OCStackResult initResources();
181 * Add a resource to the end of the linked list of resources.
183 * @param resource Resource to be added
185 static void insertResource(OCResource *resource);
188 * Find a resource in the linked list of resources.
190 * @param resource Resource to be found.
191 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
194 static OCResource *findResource(OCResource *resource);
197 * Insert a resource type into a resource's resource type linked list.
198 * If resource type already exists, it will not be inserted and the
199 * resourceType will be free'd.
200 * resourceType->next should be null to avoid memory leaks.
201 * Function returns silently for null args.
203 * @param resource Resource where resource type is to be inserted.
204 * @param resourceType Resource type to be inserted.
206 static void insertResourceType(OCResource *resource,
207 OCResourceType *resourceType);
210 * Get a resource type at the specified index within a resource.
212 * @param handle Handle of resource.
213 * @param index Index of resource type.
215 * @return Pointer to resource type if found, NULL otherwise.
217 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
221 * Insert a resource interface into a resource's resource interface linked list.
222 * If resource interface already exists, it will not be inserted and the
223 * resourceInterface will be free'd.
224 * resourceInterface->next should be null to avoid memory leaks.
226 * @param resource Resource where resource interface is to be inserted.
227 * @param resourceInterface Resource interface to be inserted.
229 static void insertResourceInterface(OCResource *resource,
230 OCResourceInterface *resourceInterface);
233 * Get a resource interface at the specified index within a resource.
235 * @param handle Handle of resource.
236 * @param index Index of resource interface.
238 * @return Pointer to resource interface if found, NULL otherwise.
240 static OCResourceInterface *findResourceInterfaceAtIndex(
241 OCResourceHandle handle, uint8_t index);
244 * Delete all of the dynamically allocated elements that were created for the resource type.
246 * @param resourceType Specified resource type.
248 static void deleteResourceType(OCResourceType *resourceType);
251 * Delete all of the dynamically allocated elements that were created for the resource interface.
253 * @param resourceInterface Specified resource interface.
255 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
258 * Delete all of the dynamically allocated elements that were created for the resource.
260 * @param resource Specified resource.
262 static void deleteResourceElements(OCResource *resource);
265 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
268 * @param handle Handle of resource to be deleted.
270 * @return ::OC_STACK_OK on success, some other value upon failure.
272 static OCStackResult deleteResource(OCResource *resource);
275 * Delete all of the resources in the resource list.
277 static void deleteAllResources();
280 * Increment resource sequence number. Handles rollover.
282 * @param resPtr Pointer to resource.
284 static void incrementSequenceNumber(OCResource * resPtr);
287 * Attempts to initialize every network interface that the CA Layer might have compiled in.
289 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
290 * return something other than @ref CA_STATUS_OK, then this function fails.
292 * @return ::CA_STATUS_OK on success, some other value upon failure.
294 static CAResult_t OCSelectNetwork();
297 * Get the CoAP ticks after the specified number of milli-seconds.
299 * @param afterMilliSeconds Milli-seconds.
303 static uint32_t GetTicks(uint32_t afterMilliSeconds);
306 * Convert CAResult_t to OCStackResult.
308 * @param caResult CAResult_t code.
309 * @return ::OC_STACK_OK on success, some other value upon failure.
311 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
314 * Convert CAResponseResult_t to OCStackResult.
316 * @param caCode CAResponseResult_t code.
317 * @return ::OC_STACK_OK on success, some other value upon failure.
319 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
322 * Convert OCStackResult to CAResponseResult_t.
324 * @param caCode OCStackResult code.
325 * @param method OCMethod method the return code replies to.
326 * @return ::CA_CONTENT on OK, some other value upon failure.
328 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
331 * Convert OCTransportFlags_t to CATransportModifiers_t.
333 * @param ocConType OCTransportFlags_t input.
334 * @return CATransportFlags
336 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
339 * Convert CATransportFlags_t to OCTransportModifiers_t.
341 * @param caConType CATransportFlags_t input.
342 * @return OCTransportFlags
344 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
347 * Handle response from presence request.
349 * @param endPoint CA remote endpoint.
350 * @param responseInfo CA response info.
351 * @return ::OC_STACK_OK on success, some other value upon failure.
353 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
354 const CAResponseInfo_t *responseInfo);
357 * This function will be called back by CA layer when a response is received.
359 * @param endPoint CA remote endpoint.
360 * @param responseInfo CA response info.
362 static void HandleCAResponses(const CAEndpoint_t* endPoint,
363 const CAResponseInfo_t* responseInfo);
366 * This function will be called back by CA layer when a request is received.
368 * @param endPoint CA remote endpoint.
369 * @param requestInfo CA request info.
371 static void HandleCARequests(const CAEndpoint_t* endPoint,
372 const CARequestInfo_t* requestInfo);
375 * Extract query from a URI.
377 * @param uri Full URI with query.
378 * @param query Pointer to string that will contain query.
379 * @param newURI Pointer to string that will contain URI.
380 * @return ::OC_STACK_OK on success, some other value upon failure.
382 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
385 * Finds a resource type in an OCResourceType link-list.
387 * @param resourceTypeList The link-list to be searched through.
388 * @param resourceTypeName The key to search for.
390 * @return Resource type that matches the key (ie. resourceTypeName) or
391 * NULL if there is either an invalid parameter or this function was unable to find the key.
393 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
394 const char * resourceTypeName);
397 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
398 * TTL will be set to maxAge.
400 * @param cbNode Callback Node for which presence ttl is to be reset.
401 * @param maxAge New value of ttl in seconds.
403 * @return ::OC_STACK_OK on success, some other value upon failure.
405 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
408 * Ensure the accept header option is set appropriatly before sending the requests and routing
409 * header option is updated with destination.
411 * @param object CA remote endpoint.
412 * @param requestInfo CA request info.
414 * @return ::OC_STACK_OK on success, some other value upon failure.
416 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
418 //-----------------------------------------------------------------------------
419 // Internal functions
420 //-----------------------------------------------------------------------------
422 uint32_t GetTicks(uint32_t afterMilliSeconds)
427 // Guard against overflow of uint32_t
428 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
429 COAP_TICKS_PER_SECOND)
431 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
439 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
441 VERIFY_NON_NULL_NR(in, FATAL);
442 VERIFY_NON_NULL_NR(out, FATAL);
444 out->adapter = (OCTransportAdapter)in->adapter;
445 out->flags = CAToOCTransportFlags(in->flags);
446 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
447 out->port = in->port;
448 out->ifindex = in->ifindex;
449 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
450 /* This assert is to prevent accidental mismatch between address size macros defined in
451 * RI and CA and cause crash here. */
452 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
453 "Address size mismatch between RI and CA");
454 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
458 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
460 VERIFY_NON_NULL_NR(in, FATAL);
461 VERIFY_NON_NULL_NR(out, FATAL);
463 out->adapter = (CATransportAdapter_t)in->adapter;
464 out->flags = OCToCATransportFlags(in->flags);
465 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
466 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
467 /* This assert is to prevent accidental mismatch between address size macros defined in
468 * RI and CA and cause crash here. */
469 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
470 "Address size mismatch between RI and CA");
471 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
473 out->port = in->port;
474 out->ifindex = in->ifindex;
477 void FixUpClientResponse(OCClientResponse *cr)
479 VERIFY_NON_NULL_NR(cr, FATAL);
481 cr->addr = &cr->devAddr;
482 cr->connType = (OCConnectivityType)
483 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
486 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
488 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
489 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
491 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
492 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
493 if (OC_STACK_OK != rmResult)
495 OIC_LOG(ERROR, TAG, "Add destination option failed");
500 // OC stack prefer CBOR encoded payloads.
501 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
502 CAResult_t result = CASendRequest(object, requestInfo);
503 if(CA_STATUS_OK != result)
505 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
506 return CAResultToOCResult(result);
510 //-----------------------------------------------------------------------------
511 // Internal API function
512 //-----------------------------------------------------------------------------
514 // This internal function is called to update the stack with the status of
515 // observers and communication failures
516 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
518 OCStackResult result = OC_STACK_ERROR;
519 ResourceObserver * observer = NULL;
520 OCEntityHandlerRequest ehRequest = {0};
524 case OC_OBSERVER_NOT_INTERESTED:
525 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
526 observer = GetObserverUsingToken (token, tokenLength);
529 result = FormOCEntityHandlerRequest(&ehRequest,
530 (OCRequestHandle)NULL,
533 (OCResourceHandle)NULL,
534 NULL, PAYLOAD_TYPE_REPRESENTATION,
536 OC_OBSERVE_DEREGISTER,
539 if(result != OC_STACK_OK)
543 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
544 observer->resource->entityHandlerCallbackParam);
547 result = DeleteObserverUsingToken (token, tokenLength);
548 if(result == OC_STACK_OK)
550 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
554 result = OC_STACK_OK;
555 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
559 case OC_OBSERVER_STILL_INTERESTED:
560 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
561 observer = GetObserverUsingToken (token, tokenLength);
564 observer->forceHighQos = 0;
565 observer->failedCommCount = 0;
566 result = OC_STACK_OK;
570 result = OC_STACK_OBSERVER_NOT_FOUND;
574 case OC_OBSERVER_FAILED_COMM:
575 OIC_LOG(DEBUG, TAG, "observer is unreachable");
576 observer = GetObserverUsingToken (token, tokenLength);
579 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
581 result = FormOCEntityHandlerRequest(&ehRequest,
582 (OCRequestHandle)NULL,
585 (OCResourceHandle)NULL,
586 NULL, PAYLOAD_TYPE_REPRESENTATION,
588 OC_OBSERVE_DEREGISTER,
591 if(result != OC_STACK_OK)
593 return OC_STACK_ERROR;
595 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
596 observer->resource->entityHandlerCallbackParam);
598 result = DeleteObserverUsingToken (token, tokenLength);
599 if(result == OC_STACK_OK)
601 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
605 result = OC_STACK_OK;
606 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
611 observer->failedCommCount++;
612 result = OC_STACK_CONTINUE;
614 observer->forceHighQos = 1;
615 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
619 OIC_LOG(ERROR, TAG, "Unknown status");
620 result = OC_STACK_ERROR;
626 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
628 OCStackResult ret = OC_STACK_ERROR;
632 case CA_ADAPTER_NOT_ENABLED:
633 case CA_SERVER_NOT_STARTED:
634 ret = OC_STACK_ADAPTER_NOT_ENABLED;
636 case CA_MEMORY_ALLOC_FAILED:
637 ret = OC_STACK_NO_MEMORY;
639 case CA_STATUS_INVALID_PARAM:
640 ret = OC_STACK_INVALID_PARAM;
648 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
650 OCStackResult ret = OC_STACK_ERROR;
654 ret = OC_STACK_RESOURCE_CREATED;
657 ret = OC_STACK_RESOURCE_DELETED;
660 ret = OC_STACK_RESOURCE_CHANGED;
667 ret = OC_STACK_INVALID_QUERY;
669 case CA_UNAUTHORIZED_REQ:
670 ret = OC_STACK_UNAUTHORIZED_REQ;
673 ret = OC_STACK_INVALID_OPTION;
676 ret = OC_STACK_NO_RESOURCE;
678 case CA_RETRANSMIT_TIMEOUT:
679 ret = OC_STACK_COMM_ERROR;
681 case CA_REQUEST_ENTITY_TOO_LARGE:
682 ret = OC_STACK_TOO_LARGE_REQ;
690 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
692 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
701 // This Response Code is like HTTP 204 "No Content" but only used in
702 // response to POST and PUT requests.
706 // This Response Code is like HTTP 200 "OK" but only used in response to
711 // This should not happen but,
712 // give it a value just in case but output an error
714 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
718 case OC_STACK_RESOURCE_CREATED:
721 case OC_STACK_RESOURCE_DELETED:
724 case OC_STACK_RESOURCE_CHANGED:
727 case OC_STACK_INVALID_QUERY:
730 case OC_STACK_INVALID_OPTION:
733 case OC_STACK_NO_RESOURCE:
736 case OC_STACK_COMM_ERROR:
737 ret = CA_RETRANSMIT_TIMEOUT;
739 case OC_STACK_UNAUTHORIZED_REQ:
740 ret = CA_UNAUTHORIZED_REQ;
748 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
750 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
752 // supply default behavior.
753 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
755 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
757 if ((caFlags & OC_MASK_SCOPE) == 0)
759 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
764 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
766 return (OCTransportFlags)caFlags;
769 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
771 uint32_t lowerBound = 0;
772 uint32_t higherBound = 0;
774 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
776 return OC_STACK_INVALID_PARAM;
779 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
781 cbNode->presence->TTL = maxAgeSeconds;
783 for (int index = 0; index < PresenceTimeOutSize; index++)
785 // Guard against overflow
786 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
789 lowerBound = GetTicks((PresenceTimeOut[index] *
790 cbNode->presence->TTL *
791 MILLISECONDS_PER_SECOND)/100);
795 lowerBound = GetTicks(UINT32_MAX);
798 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
801 higherBound = GetTicks((PresenceTimeOut[index + 1] *
802 cbNode->presence->TTL *
803 MILLISECONDS_PER_SECOND)/100);
807 higherBound = GetTicks(UINT32_MAX);
810 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
812 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
813 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
814 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
817 cbNode->presence->TTLlevel = 0;
819 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
823 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
825 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
827 return OC_RSRVD_TRIGGER_CREATE;
829 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
831 return OC_RSRVD_TRIGGER_CHANGE;
835 return OC_RSRVD_TRIGGER_DELETE;
839 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
843 return OC_PRESENCE_TRIGGER_CREATE;
845 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
847 return OC_PRESENCE_TRIGGER_CREATE;
849 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
851 return OC_PRESENCE_TRIGGER_CHANGE;
855 return OC_PRESENCE_TRIGGER_DELETE;
860 * Encode an address string to match RFC 6874.
862 * @param outputAddress a char array to be written with the encoded string.
864 * @param outputSize size of outputAddress buffer.
866 * @param inputAddress a char array of size <= CA_MAX_URI_LENGTH
867 * containing a valid IPv6 address string.
869 * @return OC_STACK_OK if encoding succeeded.
870 * Else an error occured.
872 OCStackResult encodeAddressForRFC6874(char *outputAddress,
874 const char *inputAddress)
876 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
877 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
879 size_t inputLength = strnlen(inputAddress, outputSize);
881 // inputSize includes the null terminator
882 size_t inputSize = inputLength + 1;
884 if (inputSize > outputSize)
886 OIC_LOG_V(ERROR, TAG,
887 "encodeAddressForRFC6874 failed: "
888 "outputSize (%d) < inputSize (%d)",
889 outputSize, inputSize);
891 return OC_STACK_ERROR;
894 char* percentChar = strchr(inputAddress, '%');
896 // If there is no '%' character, then no change is required to the string.
897 if (NULL == percentChar)
899 OICStrcpy(outputAddress, outputSize, inputAddress);
903 const char* addressPart = &inputAddress[0];
904 const char* scopeIdPart = percentChar + 1;
906 // Sanity check to make sure this string doesn't have more '%' characters
907 if (NULL != strchr(scopeIdPart, '%'))
909 return OC_STACK_ERROR;
912 // If no string follows the first '%', then the input was invalid.
913 if (scopeIdPart[0] == '\0')
915 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
916 return OC_STACK_ERROR;
919 // Check to see if the string is already encoded
920 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
922 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
923 return OC_STACK_ERROR;
926 // Fail if we don't have room for encoded string's two additional chars
927 if (outputSize < (inputSize + 2))
929 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: encoded output will not fit!");
930 return OC_STACK_ERROR;
933 // Restore the null terminator with an escaped '%' character, per RFC 6874
934 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
935 strcat(outputAddress, "%25");
936 strcat(outputAddress, scopeIdPart);
942 * The cononical presence allows constructed URIs to be string compared.
944 * requestUri must be a char array of size CA_MAX_URI_LENGTH
946 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
949 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
950 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
951 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
953 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
955 if (ep->adapter == CA_ADAPTER_IP)
957 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
959 if ('\0' == ep->addr[0]) // multicast
961 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
965 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
967 OCStackResult result = encodeAddressForRFC6874(addressEncoded,
968 sizeof(addressEncoded),
971 if (OC_STACK_OK != result)
976 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
977 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
982 if ('\0' == ep->addr[0]) // multicast
984 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
985 ep->port = OC_MULTICAST_PORT;
987 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
988 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
992 // might work for other adapters (untested, but better than nothing)
993 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
994 OC_RSRVD_PRESENCE_URI);
998 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
999 const CAResponseInfo_t *responseInfo)
1001 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1002 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1004 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1005 ClientCB * cbNode = NULL;
1006 char *resourceTypeName = NULL;
1007 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1008 OCStackResult result = OC_STACK_ERROR;
1009 uint32_t maxAge = 0;
1011 char presenceUri[CA_MAX_URI_LENGTH];
1013 int presenceSubscribe = 0;
1014 int multicastPresenceSubscribe = 0;
1016 if (responseInfo->result != CA_CONTENT)
1018 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1019 return OC_STACK_ERROR;
1022 // check for unicast presence
1023 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
1024 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1026 return OC_STACK_INVALID_URI;
1029 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1032 presenceSubscribe = 1;
1036 // check for multiicast presence
1037 CAEndpoint_t ep = { .adapter = endpoint->adapter,
1038 .flags = endpoint->flags };
1040 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
1042 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1045 multicastPresenceSubscribe = 1;
1049 if (!presenceSubscribe && !multicastPresenceSubscribe)
1051 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1055 response.payload = NULL;
1056 response.result = OC_STACK_OK;
1058 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1059 FixUpClientResponse(&response);
1061 if (responseInfo->info.payload)
1063 result = OCParsePayload(&response.payload,
1064 PAYLOAD_TYPE_PRESENCE,
1065 responseInfo->info.payload,
1066 responseInfo->info.payloadSize);
1068 if(result != OC_STACK_OK)
1070 OIC_LOG(ERROR, TAG, "Presence parse failed");
1073 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1075 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1076 result = OC_STACK_ERROR;
1079 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1080 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1081 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1084 if (presenceSubscribe)
1086 if(cbNode->sequenceNumber == response.sequenceNumber)
1088 OIC_LOG(INFO, TAG, "No presence change");
1089 ResetPresenceTTL(cbNode, maxAge);
1090 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1096 OIC_LOG(INFO, TAG, "Stopping presence");
1097 response.result = OC_STACK_PRESENCE_STOPPED;
1098 if(cbNode->presence)
1100 OICFree(cbNode->presence->timeOut);
1101 OICFree(cbNode->presence);
1102 cbNode->presence = NULL;
1107 if(!cbNode->presence)
1109 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1111 if(!(cbNode->presence))
1113 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1114 result = OC_STACK_NO_MEMORY;
1118 VERIFY_NON_NULL_V(cbNode->presence);
1119 cbNode->presence->timeOut = NULL;
1120 cbNode->presence->timeOut = (uint32_t *)
1121 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1122 if(!(cbNode->presence->timeOut)){
1124 "Could not allocate memory for cbNode->presence->timeOut");
1125 OICFree(cbNode->presence);
1126 result = OC_STACK_NO_MEMORY;
1131 ResetPresenceTTL(cbNode, maxAge);
1133 cbNode->sequenceNumber = response.sequenceNumber;
1135 // Ensure that a filter is actually applied.
1136 if( resourceTypeName && cbNode->filterResourceType)
1138 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1147 // This is the multicast case
1148 OCMulticastNode* mcNode = NULL;
1149 mcNode = GetMCPresenceNode(presenceUri);
1153 if(mcNode->nonce == response.sequenceNumber)
1155 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1158 mcNode->nonce = response.sequenceNumber;
1162 OIC_LOG(INFO, TAG, "Stopping presence");
1163 response.result = OC_STACK_PRESENCE_STOPPED;
1168 char* uri = OICStrdup(presenceUri);
1172 "No Memory for URI to store in the presence node");
1173 result = OC_STACK_NO_MEMORY;
1177 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1178 if(result == OC_STACK_NO_MEMORY)
1181 "No Memory for Multicast Presence Node");
1185 // presence node now owns uri
1188 // Ensure that a filter is actually applied.
1189 if(resourceTypeName && cbNode->filterResourceType)
1191 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1198 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1200 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1202 FindAndDeleteClientCB(cbNode);
1206 OCPayloadDestroy(response.payload);
1210 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1212 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1214 if(responseInfo->info.resourceUri &&
1215 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1217 HandlePresenceResponse(endPoint, responseInfo);
1221 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1222 responseInfo->info.tokenLength, NULL, NULL);
1224 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1225 responseInfo->info.tokenLength);
1229 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1230 if(responseInfo->result == CA_EMPTY)
1232 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1233 // We do not have a case for the client to receive a RESET
1234 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1236 //This is the case of receiving an ACK on a request to a slow resource!
1237 OIC_LOG(INFO, TAG, "This is a pure ACK");
1238 //TODO: should we inform the client
1239 // app that at least the request was received at the server?
1242 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1244 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1245 OIC_LOG(INFO, TAG, "Calling into application address space");
1247 OCClientResponse response =
1248 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1249 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1250 FixUpClientResponse(&response);
1251 response.resourceUri = responseInfo->info.resourceUri;
1252 memcpy(response.identity.id, responseInfo->info.identity.id,
1253 sizeof (response.identity.id));
1254 response.identity.id_length = responseInfo->info.identity.id_length;
1256 response.result = CAResponseToOCStackResult(responseInfo->result);
1257 cbNode->callBack(cbNode->context,
1258 cbNode->handle, &response);
1259 FindAndDeleteClientCB(cbNode);
1263 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1264 OIC_LOG(INFO, TAG, "Calling into application address space");
1266 OCClientResponse response =
1267 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1268 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1269 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1270 FixUpClientResponse(&response);
1271 response.resourceUri = responseInfo->info.resourceUri;
1272 memcpy(response.identity.id, responseInfo->info.identity.id,
1273 sizeof (response.identity.id));
1274 response.identity.id_length = responseInfo->info.identity.id_length;
1276 response.result = CAResponseToOCStackResult(responseInfo->result);
1278 if(responseInfo->info.payload &&
1279 responseInfo->info.payloadSize)
1281 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1282 // check the security resource
1283 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1285 type = PAYLOAD_TYPE_SECURITY;
1287 else if (cbNode->method == OC_REST_DISCOVER)
1289 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1290 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1292 type = PAYLOAD_TYPE_DISCOVERY;
1295 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1297 type = PAYLOAD_TYPE_DISCOVERY;
1300 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1302 type = PAYLOAD_TYPE_DEVICE;
1304 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1306 type = PAYLOAD_TYPE_PLATFORM;
1308 #ifdef ROUTING_GATEWAY
1309 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1311 type = PAYLOAD_TYPE_REPRESENTATION;
1314 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1316 type = PAYLOAD_TYPE_RD;
1319 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1321 type = PAYLOAD_TYPE_REPRESENTATION;
1326 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1327 cbNode->method, cbNode->requestUri);
1331 else if (cbNode->method == OC_REST_GET ||
1332 cbNode->method == OC_REST_PUT ||
1333 cbNode->method == OC_REST_POST ||
1334 cbNode->method == OC_REST_OBSERVE ||
1335 cbNode->method == OC_REST_OBSERVE_ALL ||
1336 cbNode->method == OC_REST_DELETE)
1338 char targetUri[MAX_URI_LENGTH];
1339 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1340 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1341 if (strcmp(targetUri, cbNode->requestUri) == 0)
1343 type = PAYLOAD_TYPE_RD;
1345 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1347 type = PAYLOAD_TYPE_PLATFORM;
1349 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1351 type = PAYLOAD_TYPE_DEVICE;
1353 if (type == PAYLOAD_TYPE_INVALID)
1355 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1356 cbNode->method, cbNode->requestUri);
1357 type = PAYLOAD_TYPE_REPRESENTATION;
1362 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1363 cbNode->method, cbNode->requestUri);
1367 if(OC_STACK_OK != OCParsePayload(&response.payload,
1369 responseInfo->info.payload,
1370 responseInfo->info.payloadSize))
1372 OIC_LOG(ERROR, TAG, "Error converting payload");
1373 OCPayloadDestroy(response.payload);
1378 response.numRcvdVendorSpecificHeaderOptions = 0;
1379 if(responseInfo->info.numOptions > 0)
1382 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1383 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1386 uint32_t observationOption;
1387 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1388 for (observationOption=0, i=0;
1389 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1393 (observationOption << 8) | optionData[i];
1395 response.sequenceNumber = observationOption;
1396 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1401 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1404 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1406 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1407 OCPayloadDestroy(response.payload);
1411 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1413 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1414 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1418 if (cbNode->method == OC_REST_OBSERVE &&
1419 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1420 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1421 response.sequenceNumber <= cbNode->sequenceNumber)
1423 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1424 response.sequenceNumber);
1428 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1431 cbNode->sequenceNumber = response.sequenceNumber;
1433 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1435 FindAndDeleteClientCB(cbNode);
1439 // To keep discovery callbacks active.
1440 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1441 MILLISECONDS_PER_SECOND);
1445 //Need to send ACK when the response is CON
1446 if(responseInfo->info.type == CA_MSG_CONFIRM)
1448 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1449 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1452 OCPayloadDestroy(response.payload);
1459 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1460 if(responseInfo->result == CA_EMPTY)
1462 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1463 if(responseInfo->info.type == CA_MSG_RESET)
1465 OIC_LOG(INFO, TAG, "This is a RESET");
1466 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1467 OC_OBSERVER_NOT_INTERESTED);
1469 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1471 OIC_LOG(INFO, TAG, "This is a pure ACK");
1472 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1473 OC_OBSERVER_STILL_INTERESTED);
1476 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1478 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1479 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1480 OC_OBSERVER_FAILED_COMM);
1485 if(!cbNode && !observer)
1487 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1488 || myStackMode == OC_GATEWAY)
1490 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1491 if(responseInfo->result == CA_EMPTY)
1493 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1497 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1498 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1499 CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1503 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1504 || myStackMode == OC_GATEWAY)
1506 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1507 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1509 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1510 responseInfo->info.messageId);
1512 if (responseInfo->info.type == CA_MSG_RESET)
1514 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1515 responseInfo->info.messageId);
1523 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1525 VERIFY_NON_NULL_NR(endPoint, FATAL);
1526 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1528 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1530 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1531 #ifdef ROUTING_GATEWAY
1532 bool needRIHandling = false;
1534 * Routing manager is going to update either of endpoint or response or both.
1535 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1536 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1539 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1541 if(ret != OC_STACK_OK || !needRIHandling)
1543 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1549 * Put source in sender endpoint so that the next packet from application can be routed to
1550 * proper destination and remove "RM" coap header option before passing request / response to
1551 * RI as this option will make no sense to either RI or application.
1553 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1554 (uint8_t *) &(responseInfo->info.numOptions),
1555 (CAEndpoint_t *) endPoint);
1558 OCHandleResponse(endPoint, responseInfo);
1560 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1564 * This function handles error response from CA
1565 * code shall be added to handle the errors
1567 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1569 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1571 if (NULL == endPoint)
1573 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1577 if (NULL == errorInfo)
1579 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1583 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1584 errorInfo->info.tokenLength, NULL, NULL);
1587 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1588 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1589 FixUpClientResponse(&response);
1590 response.resourceUri = errorInfo->info.resourceUri;
1591 memcpy(response.identity.id, errorInfo->info.identity.id,
1592 sizeof (response.identity.id));
1593 response.identity.id_length = errorInfo->info.identity.id_length;
1594 response.result = CAResultToOCStackResult(errorInfo->result);
1596 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1599 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1603 * This function sends out Direct Stack Responses. These are responses that are not coming
1604 * from the application entity handler. These responses have no payload and are usually ACKs,
1605 * RESETs or some error conditions that were caught by the stack.
1607 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1608 const CAResponseResult_t responseResult, const CAMessageType_t type,
1609 const uint8_t numOptions, const CAHeaderOption_t *options,
1610 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1611 CADataType_t dataType)
1613 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1614 CAResponseInfo_t respInfo = {
1615 .result = responseResult
1617 respInfo.info.messageId = coapID;
1618 respInfo.info.numOptions = numOptions;
1620 if (respInfo.info.numOptions)
1622 respInfo.info.options =
1623 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1624 memcpy (respInfo.info.options, options,
1625 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1629 respInfo.info.payload = NULL;
1630 respInfo.info.token = token;
1631 respInfo.info.tokenLength = tokenLength;
1632 respInfo.info.type = type;
1633 respInfo.info.resourceUri = OICStrdup (resourceUri);
1634 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1635 respInfo.info.dataType = dataType;
1637 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1638 // Add the destination to route option from the endpoint->routeData.
1639 bool doPost = false;
1640 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1641 if(OC_STACK_OK != result)
1643 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1648 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1649 CARequestInfo_t reqInfo = {.method = CA_POST };
1650 /* The following initialization is not done in a single initializer block as in
1651 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1652 * does not have designated initalizers. This is a work-around for now.
1654 reqInfo.info.type = CA_MSG_NONCONFIRM;
1655 reqInfo.info.messageId = coapID;
1656 reqInfo.info.tokenLength = tokenLength;
1657 reqInfo.info.token = token;
1658 reqInfo.info.numOptions = respInfo.info.numOptions;
1659 reqInfo.info.payload = NULL;
1660 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1661 if (reqInfo.info.numOptions)
1663 reqInfo.info.options =
1664 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1665 if (NULL == reqInfo.info.options)
1667 OIC_LOG(ERROR, TAG, "Calloc failed");
1668 return OC_STACK_NO_MEMORY;
1670 memcpy (reqInfo.info.options, respInfo.info.options,
1671 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1674 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1675 OICFree (reqInfo.info.resourceUri);
1676 OICFree (reqInfo.info.options);
1677 OICFree (respInfo.info.resourceUri);
1678 OICFree (respInfo.info.options);
1679 if (CA_STATUS_OK != caResult)
1681 OIC_LOG(ERROR, TAG, "CASendRequest error");
1682 return CAResultToOCResult(caResult);
1688 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1690 // resourceUri in the info field is cloned in the CA layer and
1691 // thus ownership is still here.
1692 OICFree (respInfo.info.resourceUri);
1693 OICFree (respInfo.info.options);
1694 if(CA_STATUS_OK != caResult)
1696 OIC_LOG(ERROR, TAG, "CASendResponse error");
1697 return CAResultToOCResult(caResult);
1700 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1704 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1706 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1707 OCStackResult result = OC_STACK_ERROR;
1708 if(!protocolRequest)
1710 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1711 return OC_STACK_INVALID_PARAM;
1714 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1715 protocolRequest->tokenLength);
1718 OIC_LOG(INFO, TAG, "This is a new Server Request");
1719 result = AddServerRequest(&request, protocolRequest->coapID,
1720 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1721 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1722 protocolRequest->observationOption, protocolRequest->qos,
1723 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1724 protocolRequest->payload, protocolRequest->requestToken,
1725 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1726 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1727 &protocolRequest->devAddr);
1728 if (OC_STACK_OK != result)
1730 OIC_LOG(ERROR, TAG, "Error adding server request");
1736 OIC_LOG(ERROR, TAG, "Out of Memory");
1737 return OC_STACK_NO_MEMORY;
1740 if(!protocolRequest->reqMorePacket)
1742 request->requestComplete = 1;
1747 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1750 if(request->requestComplete)
1752 OIC_LOG(INFO, TAG, "This Server Request is complete");
1753 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1754 OCResource *resource = NULL;
1755 result = DetermineResourceHandling (request, &resHandling, &resource);
1756 if (result == OC_STACK_OK)
1758 result = ProcessRequest(resHandling, resource, request);
1763 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1764 result = OC_STACK_CONTINUE;
1769 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1771 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1774 if (requestInfo->info.resourceUri &&
1775 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1777 HandleKeepAliveRequest(endPoint, requestInfo);
1782 OCStackResult requestResult = OC_STACK_ERROR;
1784 if(myStackMode == OC_CLIENT)
1786 //TODO: should the client be responding to requests?
1790 OCServerProtocolRequest serverRequest = {0};
1792 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1794 char * uriWithoutQuery = NULL;
1795 char * query = NULL;
1797 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1799 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1801 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1804 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1805 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1807 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1809 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1810 OICFree(uriWithoutQuery);
1814 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1815 OICFree(uriWithoutQuery);
1822 if(strlen(query) < MAX_QUERY_LENGTH)
1824 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1829 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1835 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1837 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1838 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1839 if (!serverRequest.payload)
1841 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1844 memcpy (serverRequest.payload, requestInfo->info.payload,
1845 requestInfo->info.payloadSize);
1849 serverRequest.reqTotalSize = 0;
1852 switch (requestInfo->method)
1855 serverRequest.method = OC_REST_GET;
1858 serverRequest.method = OC_REST_PUT;
1861 serverRequest.method = OC_REST_POST;
1864 serverRequest.method = OC_REST_DELETE;
1867 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1868 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1869 requestInfo->info.type, requestInfo->info.numOptions,
1870 requestInfo->info.options, requestInfo->info.token,
1871 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1873 OICFree(serverRequest.payload);
1877 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1878 requestInfo->info.tokenLength);
1880 serverRequest.tokenLength = requestInfo->info.tokenLength;
1881 if (serverRequest.tokenLength) {
1883 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1885 if (!serverRequest.requestToken)
1887 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1888 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1889 requestInfo->info.type, requestInfo->info.numOptions,
1890 requestInfo->info.options, requestInfo->info.token,
1891 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1893 OICFree(serverRequest.payload);
1896 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1899 switch (requestInfo->info.acceptFormat)
1901 case CA_FORMAT_APPLICATION_CBOR:
1902 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1904 case CA_FORMAT_UNDEFINED:
1905 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1908 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1911 if (requestInfo->info.type == CA_MSG_CONFIRM)
1913 serverRequest.qos = OC_HIGH_QOS;
1917 serverRequest.qos = OC_LOW_QOS;
1919 // CA does not need the following field
1920 // Are we sure CA does not need them? how is it responding to multicast
1921 serverRequest.delayedResNeeded = 0;
1923 serverRequest.coapID = requestInfo->info.messageId;
1925 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1927 // copy vendor specific header options
1928 uint8_t tempNum = (requestInfo->info.numOptions);
1930 // Assume no observation requested and it is a pure GET.
1931 // If obs registration/de-registration requested it'll be fetched from the
1932 // options in GetObserveHeaderOption()
1933 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1935 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1936 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1939 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1940 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1941 requestInfo->info.type, requestInfo->info.numOptions,
1942 requestInfo->info.options, requestInfo->info.token,
1943 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1945 OICFree(serverRequest.payload);
1946 OICFree(serverRequest.requestToken);
1949 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1950 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1952 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1953 sizeof(CAHeaderOption_t)*tempNum);
1956 requestResult = HandleStackRequests (&serverRequest);
1958 // Send ACK to client as precursor to slow response
1959 if (requestResult == OC_STACK_SLOW_RESOURCE)
1961 if (requestInfo->info.type == CA_MSG_CONFIRM)
1963 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1964 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
1968 else if(!OCResultToSuccess(requestResult))
1970 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1972 CAResponseResult_t stackResponse =
1973 OCToCAStackResult(requestResult, serverRequest.method);
1975 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1976 requestInfo->info.type, requestInfo->info.numOptions,
1977 requestInfo->info.options, requestInfo->info.token,
1978 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1981 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1982 // The token is copied in there, and is thus still owned by this function.
1983 OICFree(serverRequest.payload);
1984 OICFree(serverRequest.requestToken);
1985 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1988 //This function will be called back by CA layer when a request is received
1989 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1991 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1994 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2000 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2004 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2005 #ifdef ROUTING_GATEWAY
2006 bool needRIHandling = false;
2007 bool isEmptyMsg = false;
2009 * Routing manager is going to update either of endpoint or request or both.
2010 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2011 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2012 * destination. It can also remove "RM" coap header option before passing request / response to
2013 * RI as this option will make no sense to either RI or application.
2015 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2016 &needRIHandling, &isEmptyMsg);
2017 if(OC_STACK_OK != ret || !needRIHandling)
2019 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2025 * Put source in sender endpoint so that the next packet from application can be routed to
2026 * proper destination and remove RM header option.
2028 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2029 (uint8_t *) &(requestInfo->info.numOptions),
2030 (CAEndpoint_t *) endPoint);
2032 #ifdef ROUTING_GATEWAY
2036 * In Gateways, the MSGType in route option is used to check if the actual
2037 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2038 * EMPTY response is sent in the form of POST request which need to be changed
2039 * to a EMPTY response by RM. This translation is done in this part of the code.
2041 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2042 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2043 .info.messageId = requestInfo->info.messageId,
2044 .info.type = CA_MSG_ACKNOWLEDGE};
2045 OCHandleResponse(endPoint, &respInfo);
2051 // Normal handling of the packet
2052 OCHandleRequests(endPoint, requestInfo);
2054 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2057 bool validatePlatformInfo(OCPlatformInfo info)
2060 if (!info.platformID)
2062 OIC_LOG(ERROR, TAG, "No platform ID found.");
2066 if (info.manufacturerName)
2068 size_t lenManufacturerName = strlen(info.manufacturerName);
2070 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2072 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2078 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2082 if (info.manufacturerUrl)
2084 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2086 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2093 //-----------------------------------------------------------------------------
2095 //-----------------------------------------------------------------------------
2097 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2100 !raInfo->username ||
2101 !raInfo->hostname ||
2102 !raInfo->xmpp_domain)
2105 return OC_STACK_INVALID_PARAM;
2107 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2108 gRASetInfo = (result == OC_STACK_OK)? true : false;
2114 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2118 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2121 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2123 if(stackState == OC_STACK_INITIALIZED)
2125 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2126 OCStop() between them are ignored.");
2130 #ifndef ROUTING_GATEWAY
2131 if (OC_GATEWAY == mode)
2133 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2134 return OC_STACK_INVALID_PARAM;
2141 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2142 return OC_STACK_ERROR;
2146 OCStackResult result = OC_STACK_ERROR;
2147 OIC_LOG(INFO, TAG, "Entering OCInit");
2150 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2151 || (mode == OC_GATEWAY)))
2153 OIC_LOG(ERROR, TAG, "Invalid mode");
2154 return OC_STACK_ERROR;
2158 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2160 caglobals.client = true;
2162 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2164 caglobals.server = true;
2167 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2168 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2170 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2172 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2173 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2175 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2178 defaultDeviceHandler = NULL;
2179 defaultDeviceHandlerCallbackParameter = NULL;
2181 result = CAResultToOCResult(CAInitialize());
2182 VERIFY_SUCCESS(result, OC_STACK_OK);
2184 result = CAResultToOCResult(OCSelectNetwork());
2185 VERIFY_SUCCESS(result, OC_STACK_OK);
2187 switch (myStackMode)
2190 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2191 result = CAResultToOCResult(CAStartDiscoveryServer());
2192 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2195 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2196 result = CAResultToOCResult(CAStartListeningServer());
2197 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2199 case OC_CLIENT_SERVER:
2201 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2202 result = CAResultToOCResult(CAStartListeningServer());
2203 if(result == OC_STACK_OK)
2205 result = CAResultToOCResult(CAStartDiscoveryServer());
2209 VERIFY_SUCCESS(result, OC_STACK_OK);
2212 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2215 #ifdef WITH_PRESENCE
2216 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2217 #endif // WITH_PRESENCE
2219 //Update Stack state to initialized
2220 stackState = OC_STACK_INITIALIZED;
2222 // Initialize resource
2223 if(myStackMode != OC_CLIENT)
2225 result = initResources();
2228 // Initialize the SRM Policy Engine
2229 if(result == OC_STACK_OK)
2231 result = SRMInitPolicyEngine();
2232 // TODO after BeachHead delivery: consolidate into single SRMInit()
2234 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2235 RMSetStackMode(mode);
2236 #ifdef ROUTING_GATEWAY
2237 if (OC_GATEWAY == myStackMode)
2239 result = RMInitialize();
2245 if (result == OC_STACK_OK)
2247 result = InitializeKeepAlive(myStackMode);
2252 if(result != OC_STACK_OK)
2254 OIC_LOG(ERROR, TAG, "Stack initialization error");
2255 deleteAllResources();
2257 stackState = OC_STACK_UNINITIALIZED;
2262 OCStackResult OCStop()
2264 OIC_LOG(INFO, TAG, "Entering OCStop");
2266 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2268 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2271 else if (stackState != OC_STACK_INITIALIZED)
2273 OIC_LOG(ERROR, TAG, "Stack not initialized");
2274 return OC_STACK_ERROR;
2277 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2279 #ifdef WITH_PRESENCE
2280 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2281 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2282 presenceResource.presenceTTL = 0;
2283 #endif // WITH_PRESENCE
2285 #ifdef ROUTING_GATEWAY
2286 if (OC_GATEWAY == myStackMode)
2293 TerminateKeepAlive(myStackMode);
2296 // Free memory dynamically allocated for resources
2297 deleteAllResources();
2299 DeletePlatformInfo();
2301 // Remove all observers
2302 DeleteObserverList();
2303 // Remove all the client callbacks
2304 DeleteClientCBList();
2306 // De-init the SRM Policy Engine
2307 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2308 SRMDeInitPolicyEngine();
2311 stackState = OC_STACK_UNINITIALIZED;
2315 OCStackResult OCStartMulticastServer()
2317 if(stackState != OC_STACK_INITIALIZED)
2319 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2320 return OC_STACK_ERROR;
2322 CAResult_t ret = CAStartListeningServer();
2323 if (CA_STATUS_OK != ret)
2325 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2326 return OC_STACK_ERROR;
2331 OCStackResult OCStopMulticastServer()
2333 CAResult_t ret = CAStopListeningServer();
2334 if (CA_STATUS_OK != ret)
2336 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2337 return OC_STACK_ERROR;
2342 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2347 return CA_MSG_CONFIRM;
2352 return CA_MSG_NONCONFIRM;
2357 * A request uri consists of the following components in order:
2360 * CoAP over UDP prefix "coap://"
2361 * CoAP over TCP prefix "coap+tcp://"
2362 * CoAP over DTLS prefix "coaps://"
2363 * CoAP over TLS prefix "coaps+tcp://"
2365 * IPv6 address "[1234::5678]"
2366 * IPv4 address "192.168.1.1"
2367 * optional port ":5683"
2368 * resource uri "/oc/core..."
2370 * for PRESENCE requests, extract resource type.
2372 static OCStackResult ParseRequestUri(const char *fullUri,
2373 OCTransportAdapter adapter,
2374 OCTransportFlags flags,
2375 OCDevAddr **devAddr,
2377 char **resourceType)
2379 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2381 OCStackResult result = OC_STACK_OK;
2382 OCDevAddr *da = NULL;
2386 // provide defaults for all returned values
2393 *resourceUri = NULL;
2397 *resourceType = NULL;
2400 // delimit url prefix, if any
2401 const char *start = fullUri;
2402 char *slash2 = strstr(start, "//");
2407 char *slash = strchr(start, '/');
2410 return OC_STACK_INVALID_URI;
2413 // process url scheme
2414 size_t prefixLen = slash2 - fullUri;
2418 if (((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2419 || ((prefixLen == sizeof(COAPS_TCP) - 1) && (!strncmp(fullUri, COAPS_TCP, prefixLen))))
2425 // TODO: this logic should come in with unit tests exercising the various strings
2426 // processs url prefix, if any
2427 size_t urlLen = slash - start;
2431 if (urlLen && devAddr)
2432 { // construct OCDevAddr
2433 if (start[0] == '[')
2435 char *close = strchr(++start, ']');
2436 if (!close || close > slash)
2438 return OC_STACK_INVALID_URI;
2441 if (close[1] == ':')
2448 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2452 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2454 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2458 char *dot = strchr(start, '.');
2459 if (dot && dot < slash)
2461 colon = strchr(start, ':');
2462 end = (colon && colon < slash) ? colon : slash;
2467 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2471 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2473 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2481 if (len >= sizeof(da->addr))
2483 return OC_STACK_INVALID_URI;
2485 // collect port, if any
2486 if (colon && colon < slash)
2488 for (colon++; colon < slash; colon++)
2491 if (c < '0' || c > '9')
2493 return OC_STACK_INVALID_URI;
2495 port = 10 * port + c - '0';
2500 if (len >= sizeof(da->addr))
2502 return OC_STACK_INVALID_URI;
2505 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2508 return OC_STACK_NO_MEMORY;
2510 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2512 da->adapter = adapter;
2514 if (!strncmp(fullUri, "coaps", 5))
2516 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2521 // process resource uri, if any
2523 { // request uri and query
2524 size_t ulen = strlen(slash); // resource uri length
2525 size_t tlen = 0; // resource type length
2528 static const char strPresence[] = "/oic/ad?rt=";
2529 static const size_t lenPresence = sizeof(strPresence) - 1;
2530 if (!strncmp(slash, strPresence, lenPresence))
2532 type = slash + lenPresence;
2533 tlen = ulen - lenPresence;
2538 *resourceUri = (char *)OICMalloc(ulen + 1);
2541 result = OC_STACK_NO_MEMORY;
2544 strcpy(*resourceUri, slash);
2547 if (type && resourceType)
2549 *resourceType = (char *)OICMalloc(tlen + 1);
2552 result = OC_STACK_NO_MEMORY;
2556 OICStrcpy(*resourceType, (tlen+1), type);
2563 // free all returned values
2570 OICFree(*resourceUri);
2574 OICFree(*resourceType);
2579 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2580 char *resourceUri, char **requestUri)
2582 char uri[CA_MAX_URI_LENGTH];
2584 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2586 *requestUri = OICStrdup(uri);
2589 return OC_STACK_NO_MEMORY;
2596 * Discover or Perform requests on a specified resource
2598 OCStackResult OCDoResource(OCDoHandle *handle,
2600 const char *requestUri,
2601 const OCDevAddr *destination,
2603 OCConnectivityType connectivityType,
2604 OCQualityOfService qos,
2605 OCCallbackData *cbData,
2606 OCHeaderOption *options,
2609 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2611 // Validate input parameters
2612 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2613 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2614 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2616 OCStackResult result = OC_STACK_ERROR;
2617 CAResult_t caResult;
2618 CAToken_t token = NULL;
2619 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2620 ClientCB *clientCB = NULL;
2621 OCDoHandle resHandle = NULL;
2622 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2623 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2625 OCTransportAdapter adapter;
2626 OCTransportFlags flags;
2627 // the request contents are put here
2628 CARequestInfo_t requestInfo = {.method = CA_GET};
2629 // requestUri will be parsed into the following three variables
2630 OCDevAddr *devAddr = NULL;
2631 char *resourceUri = NULL;
2632 char *resourceType = NULL;
2635 * Support original behavior with address on resourceUri argument.
2637 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2638 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2640 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2642 if (result != OC_STACK_OK)
2644 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2651 case OC_REST_OBSERVE:
2652 case OC_REST_OBSERVE_ALL:
2653 case OC_REST_CANCEL_OBSERVE:
2654 requestInfo.method = CA_GET;
2657 requestInfo.method = CA_PUT;
2660 requestInfo.method = CA_POST;
2662 case OC_REST_DELETE:
2663 requestInfo.method = CA_DELETE;
2665 case OC_REST_DISCOVER:
2667 if (destination || devAddr)
2669 requestInfo.isMulticast = false;
2673 tmpDevAddr.adapter = adapter;
2674 tmpDevAddr.flags = flags;
2675 destination = &tmpDevAddr;
2676 requestInfo.isMulticast = true;
2678 // CA_DISCOVER will become GET and isMulticast
2679 requestInfo.method = CA_GET;
2681 #ifdef WITH_PRESENCE
2682 case OC_REST_PRESENCE:
2683 // Replacing method type with GET because "presence"
2684 // is a stack layer only implementation.
2685 requestInfo.method = CA_GET;
2689 result = OC_STACK_INVALID_METHOD;
2693 if (!devAddr && !destination)
2695 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2696 result = OC_STACK_INVALID_PARAM;
2700 /* If not original behavior, use destination argument */
2701 if (destination && !devAddr)
2703 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2706 result = OC_STACK_NO_MEMORY;
2709 *devAddr = *destination;
2712 resHandle = GenerateInvocationHandle();
2715 result = OC_STACK_NO_MEMORY;
2719 caResult = CAGenerateToken(&token, tokenLength);
2720 if (caResult != CA_STATUS_OK)
2722 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2723 result= OC_STACK_ERROR;
2727 // fill in request data
2728 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2729 requestInfo.info.token = token;
2730 requestInfo.info.tokenLength = tokenLength;
2731 requestInfo.info.resourceUri = resourceUri;
2733 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2735 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2736 options, numOptions, OC_OBSERVE_REGISTER);
2737 if (result != OC_STACK_OK)
2741 requestInfo.info.numOptions = numOptions + 1;
2745 requestInfo.info.numOptions = numOptions;
2746 requestInfo.info.options =
2747 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2748 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2749 numOptions * sizeof(CAHeaderOption_t));
2752 CopyDevAddrToEndpoint(devAddr, &endpoint);
2757 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2760 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2763 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2767 requestInfo.info.payload = NULL;
2768 requestInfo.info.payloadSize = 0;
2769 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2772 // prepare for response
2773 #ifdef WITH_PRESENCE
2774 if (method == OC_REST_PRESENCE)
2776 char *presenceUri = NULL;
2777 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2778 if (OC_STACK_OK != result)
2783 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2784 // Presence notification will form a canonical uri to
2785 // look for callbacks into the application.
2786 resourceUri = presenceUri;
2790 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2791 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2792 method, devAddr, resourceUri, resourceType, ttl);
2793 if (OC_STACK_OK != result)
2798 devAddr = NULL; // Client CB list entry now owns it
2799 resourceUri = NULL; // Client CB list entry now owns it
2800 resourceType = NULL; // Client CB list entry now owns it
2803 result = OCSendRequest(&endpoint, &requestInfo);
2804 if (OC_STACK_OK != result)
2811 *handle = resHandle;
2815 if (result != OC_STACK_OK)
2817 OIC_LOG(ERROR, TAG, "OCDoResource error");
2818 FindAndDeleteClientCB(clientCB);
2819 CADestroyToken(token);
2827 // This is the owner of the payload object, so we free it
2828 OCPayloadDestroy(payload);
2829 OICFree(requestInfo.info.payload);
2831 OICFree(resourceUri);
2832 OICFree(resourceType);
2833 OICFree(requestInfo.info.options);
2837 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2841 * This ftn is implemented one of two ways in the case of observation:
2843 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2844 * Remove the callback associated on client side.
2845 * When the next notification comes in from server,
2846 * reply with RESET message to server.
2847 * Keep in mind that the server will react to RESET only
2848 * if the last notification was sent as CON
2850 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2851 * and it is associated with an observe request
2852 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2853 * Send CON Observe request to server with
2854 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2855 * Remove the callback associated on client side.
2857 OCStackResult ret = OC_STACK_OK;
2858 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2859 CARequestInfo_t requestInfo = {.method = CA_GET};
2863 return OC_STACK_INVALID_PARAM;
2866 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2869 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2870 return OC_STACK_ERROR;
2873 switch (clientCB->method)
2875 case OC_REST_OBSERVE:
2876 case OC_REST_OBSERVE_ALL:
2878 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2880 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2882 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2884 FindAndDeleteClientCB(clientCB);
2888 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2890 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2891 requestInfo.info.token = clientCB->token;
2892 requestInfo.info.tokenLength = clientCB->tokenLength;
2894 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2895 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2897 return OC_STACK_ERROR;
2899 requestInfo.info.numOptions = numOptions + 1;
2900 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2903 ret = OCSendRequest(&endpoint, &requestInfo);
2905 if (requestInfo.info.options)
2907 OICFree (requestInfo.info.options);
2909 if (requestInfo.info.resourceUri)
2911 OICFree (requestInfo.info.resourceUri);
2916 case OC_REST_DISCOVER:
2917 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2918 clientCB->requestUri);
2919 FindAndDeleteClientCB(clientCB);
2922 #ifdef WITH_PRESENCE
2923 case OC_REST_PRESENCE:
2924 FindAndDeleteClientCB(clientCB);
2929 ret = OC_STACK_INVALID_METHOD;
2937 * @brief Register Persistent storage callback.
2938 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2940 * OC_STACK_OK - No errors; Success
2941 * OC_STACK_INVALID_PARAM - Invalid parameter
2943 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2945 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2946 if(!persistentStorageHandler)
2948 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2949 return OC_STACK_INVALID_PARAM;
2953 if( !persistentStorageHandler->open ||
2954 !persistentStorageHandler->close ||
2955 !persistentStorageHandler->read ||
2956 !persistentStorageHandler->unlink ||
2957 !persistentStorageHandler->write)
2959 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2960 return OC_STACK_INVALID_PARAM;
2963 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2966 #ifdef WITH_PRESENCE
2968 OCStackResult OCProcessPresence()
2970 OCStackResult result = OC_STACK_OK;
2972 // the following line floods the log with messages that are irrelevant
2973 // to most purposes. Uncomment as needed.
2974 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2975 ClientCB* cbNode = NULL;
2976 OCClientResponse clientResponse;
2977 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2979 LL_FOREACH(cbList, cbNode)
2981 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2986 uint32_t now = GetTicks(0);
2987 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2988 cbNode->presence->TTLlevel);
2989 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2991 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2996 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2998 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2999 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3001 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3003 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3005 clientResponse.sequenceNumber = 0;
3006 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3007 clientResponse.devAddr = *cbNode->devAddr;
3008 FixUpClientResponse(&clientResponse);
3009 clientResponse.payload = NULL;
3011 // Increment the TTLLevel (going to a next state), so we don't keep
3012 // sending presence notification to client.
3013 cbNode->presence->TTLlevel++;
3014 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3015 cbNode->presence->TTLlevel);
3017 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3018 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3020 FindAndDeleteClientCB(cbNode);
3024 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3029 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3030 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3031 CARequestInfo_t requestInfo = {.method = CA_GET};
3033 OIC_LOG(DEBUG, TAG, "time to test server presence");
3035 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3037 requestData.type = CA_MSG_NONCONFIRM;
3038 requestData.token = cbNode->token;
3039 requestData.tokenLength = cbNode->tokenLength;
3040 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3041 requestInfo.method = CA_GET;
3042 requestInfo.info = requestData;
3044 result = OCSendRequest(&endpoint, &requestInfo);
3045 if (OC_STACK_OK != result)
3050 cbNode->presence->TTLlevel++;
3051 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3054 if (result != OC_STACK_OK)
3056 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3061 #endif // WITH_PRESENCE
3063 OCStackResult OCProcess()
3065 #ifdef WITH_PRESENCE
3066 OCProcessPresence();
3068 CAHandleRequestResponse();
3070 #ifdef ROUTING_GATEWAY
3080 #ifdef WITH_PRESENCE
3081 OCStackResult OCStartPresence(const uint32_t ttl)
3083 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3084 OCChangeResourceProperty(
3085 &(((OCResource *)presenceResource.handle)->resourceProperties),
3088 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3090 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3091 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3095 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3096 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3100 presenceResource.presenceTTL = ttl;
3102 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3104 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3106 presenceState = OC_PRESENCE_INITIALIZED;
3108 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3110 CAToken_t caToken = NULL;
3111 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3112 if (caResult != CA_STATUS_OK)
3114 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3115 CADestroyToken(caToken);
3116 return OC_STACK_ERROR;
3119 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3120 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3121 CADestroyToken(caToken);
3124 // Each time OCStartPresence is called
3125 // a different random 32-bit integer number is used
3126 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3128 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3129 OC_PRESENCE_TRIGGER_CREATE);
3132 OCStackResult OCStopPresence()
3134 OCStackResult result = OC_STACK_ERROR;
3136 if(presenceResource.handle)
3138 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3140 // make resource inactive
3141 result = OCChangeResourceProperty(
3142 &(((OCResource *) presenceResource.handle)->resourceProperties),
3146 if(result != OC_STACK_OK)
3149 "Changing the presence resource properties to ACTIVE not successful");
3153 return SendStopNotification();
3157 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3158 void* callbackParameter)
3160 defaultDeviceHandler = entityHandler;
3161 defaultDeviceHandlerCallbackParameter = callbackParameter;
3166 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3168 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3170 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3172 if (validatePlatformInfo(platformInfo))
3174 return SavePlatformInfo(platformInfo);
3178 return OC_STACK_INVALID_PARAM;
3183 return OC_STACK_ERROR;
3187 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3189 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3191 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3193 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3194 return OC_STACK_INVALID_PARAM;
3197 if (deviceInfo.types)
3199 OCStringLL *type = deviceInfo.types;
3200 OCResource *resource = findResource((OCResource *) deviceResource);
3203 return OC_STACK_INVALID_PARAM;
3208 OCBindResourceTypeToResource(deviceResource, type->value);
3212 return SaveDeviceInfo(deviceInfo);
3215 OCStackResult OCCreateResource(OCResourceHandle *handle,
3216 const char *resourceTypeName,
3217 const char *resourceInterfaceName,
3218 const char *uri, OCEntityHandler entityHandler,
3219 void* callbackParam,
3220 uint8_t resourceProperties)
3223 OCResource *pointer = NULL;
3224 OCStackResult result = OC_STACK_ERROR;
3226 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3228 if(myStackMode == OC_CLIENT)
3230 return OC_STACK_INVALID_PARAM;
3232 // Validate parameters
3233 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3235 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3236 return OC_STACK_INVALID_URI;
3238 // Is it presented during resource discovery?
3239 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3241 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3242 return OC_STACK_INVALID_PARAM;
3245 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3247 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3251 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3253 // Make sure resourceProperties bitmask has allowed properties specified
3254 if (resourceProperties
3255 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3256 OC_EXPLICIT_DISCOVERABLE
3265 OIC_LOG(ERROR, TAG, "Invalid property");
3266 return OC_STACK_INVALID_PARAM;
3269 // If the headResource is NULL, then no resources have been created...
3270 pointer = headResource;
3273 // At least one resources is in the resource list, so we need to search for
3274 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3277 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3279 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3280 return OC_STACK_INVALID_PARAM;
3282 pointer = pointer->next;
3285 // Create the pointer and insert it into the resource list
3286 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3289 result = OC_STACK_NO_MEMORY;
3292 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3294 insertResource(pointer);
3297 pointer->uri = OICStrdup(uri);
3300 result = OC_STACK_NO_MEMORY;
3304 // Set properties. Set OC_ACTIVE
3305 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3308 // Add the resourcetype to the resource
3309 result = BindResourceTypeToResource(pointer, resourceTypeName);
3310 if (result != OC_STACK_OK)
3312 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3316 // Add the resourceinterface to the resource
3317 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3318 if (result != OC_STACK_OK)
3320 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3324 // If an entity handler has been passed, attach it to the newly created
3325 // resource. Otherwise, set the default entity handler.
3328 pointer->entityHandler = entityHandler;
3329 pointer->entityHandlerCallbackParam = callbackParam;
3333 pointer->entityHandler = defaultResourceEHandler;
3334 pointer->entityHandlerCallbackParam = NULL;
3337 // Initialize a pointer indicating child resources in case of collection
3338 pointer->rsrcChildResourcesHead = NULL;
3341 result = OC_STACK_OK;
3343 #ifdef WITH_PRESENCE
3344 if (presenceResource.handle)
3346 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3347 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3351 if (result != OC_STACK_OK)
3353 // Deep delete of resource and other dynamic elements that it contains
3354 deleteResource(pointer);
3359 OCStackResult OCBindResource(
3360 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3362 OCResource *resource = NULL;
3363 OCChildResource *tempChildResource = NULL;
3364 OCChildResource *newChildResource = NULL;
3366 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3368 // Validate parameters
3369 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3370 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3371 // Container cannot contain itself
3372 if (collectionHandle == resourceHandle)
3374 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3375 return OC_STACK_INVALID_PARAM;
3378 // Use the handle to find the resource in the resource linked list
3379 resource = findResource((OCResource *) collectionHandle);
3382 OIC_LOG(ERROR, TAG, "Collection handle not found");
3383 return OC_STACK_INVALID_PARAM;
3386 // Look for an open slot to add add the child resource.
3387 // If found, add it and return success
3389 tempChildResource = resource->rsrcChildResourcesHead;
3391 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3393 // TODO: what if one of child resource was deregistered without unbinding?
3394 tempChildResource = tempChildResource->next;
3397 // Do memory allocation for child resource
3398 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3399 if(!newChildResource)
3401 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3402 return OC_STACK_ERROR;
3405 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3406 newChildResource->next = NULL;
3408 if(!resource->rsrcChildResourcesHead)
3410 resource->rsrcChildResourcesHead = newChildResource;
3413 tempChildResource->next = newChildResource;
3416 OIC_LOG(INFO, TAG, "resource bound");
3418 #ifdef WITH_PRESENCE
3419 if (presenceResource.handle)
3421 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3422 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3423 OC_PRESENCE_TRIGGER_CHANGE);
3430 OCStackResult OCUnBindResource(
3431 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3433 OCResource *resource = NULL;
3434 OCChildResource *tempChildResource = NULL;
3435 OCChildResource *tempLastChildResource = NULL;
3437 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3439 // Validate parameters
3440 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3441 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3442 // Container cannot contain itself
3443 if (collectionHandle == resourceHandle)
3445 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3446 return OC_STACK_INVALID_PARAM;
3449 // Use the handle to find the resource in the resource linked list
3450 resource = findResource((OCResource *) collectionHandle);
3453 OIC_LOG(ERROR, TAG, "Collection handle not found");
3454 return OC_STACK_INVALID_PARAM;
3457 // Look for an open slot to add add the child resource.
3458 // If found, add it and return success
3459 if(!resource->rsrcChildResourcesHead)
3461 OIC_LOG(INFO, TAG, "resource not found in collection");
3463 // Unable to add resourceHandle, so return error
3464 return OC_STACK_ERROR;
3468 tempChildResource = resource->rsrcChildResourcesHead;
3470 while (tempChildResource)
3472 if(tempChildResource->rsrcResource == resourceHandle)
3474 // if resource going to be unbinded is the head one.
3475 if( tempChildResource == resource->rsrcChildResourcesHead )
3477 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3478 OICFree(resource->rsrcChildResourcesHead);
3479 resource->rsrcChildResourcesHead = temp;
3484 OCChildResource *temp = tempChildResource->next;
3485 OICFree(tempChildResource);
3486 tempLastChildResource->next = temp;
3490 OIC_LOG(INFO, TAG, "resource unbound");
3492 // Send notification when resource is unbounded successfully.
3493 #ifdef WITH_PRESENCE
3494 if (presenceResource.handle)
3496 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3497 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3498 OC_PRESENCE_TRIGGER_CHANGE);
3501 tempChildResource = NULL;
3502 tempLastChildResource = NULL;
3508 tempLastChildResource = tempChildResource;
3509 tempChildResource = tempChildResource->next;
3512 OIC_LOG(INFO, TAG, "resource not found in collection");
3514 tempChildResource = NULL;
3515 tempLastChildResource = NULL;
3517 // Unable to add resourceHandle, so return error
3518 return OC_STACK_ERROR;
3521 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3523 if (!resourceItemName)
3527 // Per RFC 6690 only registered values must follow the first rule below.
3528 // At this point in time the only values registered begin with "core", and
3529 // all other values are specified as opaque strings where multiple values
3530 // are separated by a space.
3531 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3533 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3535 if (resourceItemName[index] != '.'
3536 && resourceItemName[index] != '-'
3537 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3538 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3546 for (size_t index = 0; resourceItemName[index]; ++index)
3548 if (resourceItemName[index] == ' '
3549 || resourceItemName[index] == '\t'
3550 || resourceItemName[index] == '\r'
3551 || resourceItemName[index] == '\n')
3561 OCStackResult BindResourceTypeToResource(OCResource* resource,
3562 const char *resourceTypeName)
3564 OCResourceType *pointer = NULL;
3566 OCStackResult result = OC_STACK_ERROR;
3568 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3570 if (!ValidateResourceTypeInterface(resourceTypeName))
3572 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3573 return OC_STACK_INVALID_PARAM;
3576 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3579 result = OC_STACK_NO_MEMORY;
3583 str = OICStrdup(resourceTypeName);
3586 result = OC_STACK_NO_MEMORY;
3589 pointer->resourcetypename = str;
3590 pointer->next = NULL;
3592 insertResourceType(resource, pointer);
3593 result = OC_STACK_OK;
3596 if (result != OC_STACK_OK)
3605 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3606 const char *resourceInterfaceName)
3608 OCResourceInterface *pointer = NULL;
3610 OCStackResult result = OC_STACK_ERROR;
3612 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3614 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3616 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3617 return OC_STACK_INVALID_PARAM;
3620 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3622 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3625 result = OC_STACK_NO_MEMORY;
3629 str = OICStrdup(resourceInterfaceName);
3632 result = OC_STACK_NO_MEMORY;
3635 pointer->name = str;
3637 // Bind the resourceinterface to the resource
3638 insertResourceInterface(resource, pointer);
3640 result = OC_STACK_OK;
3643 if (result != OC_STACK_OK)
3652 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3653 const char *resourceTypeName)
3656 OCStackResult result = OC_STACK_ERROR;
3657 OCResource *resource = NULL;
3659 resource = findResource((OCResource *) handle);
3662 OIC_LOG(ERROR, TAG, "Resource not found");
3663 return OC_STACK_ERROR;
3666 result = BindResourceTypeToResource(resource, resourceTypeName);
3668 #ifdef WITH_PRESENCE
3669 if(presenceResource.handle)
3671 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3672 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3679 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3680 const char *resourceInterfaceName)
3683 OCStackResult result = OC_STACK_ERROR;
3684 OCResource *resource = NULL;
3686 resource = findResource((OCResource *) handle);
3689 OIC_LOG(ERROR, TAG, "Resource not found");
3690 return OC_STACK_ERROR;
3693 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3695 #ifdef WITH_PRESENCE
3696 if (presenceResource.handle)
3698 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3699 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3706 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3708 OCResource *pointer = headResource;
3710 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3714 *numResources = *numResources + 1;
3715 pointer = pointer->next;
3720 OCResourceHandle OCGetResourceHandle(uint8_t index)
3722 OCResource *pointer = headResource;
3724 for( uint8_t i = 0; i < index && pointer; ++i)
3726 pointer = pointer->next;
3728 return (OCResourceHandle) pointer;
3731 OCStackResult OCDeleteResource(OCResourceHandle handle)
3735 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3736 return OC_STACK_INVALID_PARAM;
3739 OCResource *resource = findResource((OCResource *) handle);
3740 if (resource == NULL)
3742 OIC_LOG(ERROR, TAG, "Resource not found");
3743 return OC_STACK_NO_RESOURCE;
3746 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3748 OIC_LOG(ERROR, TAG, "Error deleting resource");
3749 return OC_STACK_ERROR;
3755 const char *OCGetResourceUri(OCResourceHandle handle)
3757 OCResource *resource = NULL;
3759 resource = findResource((OCResource *) handle);
3762 return resource->uri;
3764 return (const char *) NULL;
3767 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3769 OCResource *resource = NULL;
3771 resource = findResource((OCResource *) handle);
3774 return resource->resourceProperties;
3776 return (OCResourceProperty)-1;
3779 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3780 uint8_t *numResourceTypes)
3782 OCResource *resource = NULL;
3783 OCResourceType *pointer = NULL;
3785 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3786 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3788 *numResourceTypes = 0;
3790 resource = findResource((OCResource *) handle);
3793 pointer = resource->rsrcType;
3796 *numResourceTypes = *numResourceTypes + 1;
3797 pointer = pointer->next;
3803 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3805 OCResourceType *resourceType = NULL;
3807 resourceType = findResourceTypeAtIndex(handle, index);
3810 return resourceType->resourcetypename;
3812 return (const char *) NULL;
3815 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3816 uint8_t *numResourceInterfaces)
3818 OCResourceInterface *pointer = NULL;
3819 OCResource *resource = NULL;
3821 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3822 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3824 *numResourceInterfaces = 0;
3825 resource = findResource((OCResource *) handle);
3828 pointer = resource->rsrcInterface;
3831 *numResourceInterfaces = *numResourceInterfaces + 1;
3832 pointer = pointer->next;
3838 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3840 OCResourceInterface *resourceInterface = NULL;
3842 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3843 if (resourceInterface)
3845 return resourceInterface->name;
3847 return (const char *) NULL;
3850 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3853 OCResource *resource = NULL;
3854 OCChildResource *tempChildResource = NULL;
3857 resource = findResource((OCResource *) collectionHandle);
3863 tempChildResource = resource->rsrcChildResourcesHead;
3865 while(tempChildResource)
3869 return tempChildResource->rsrcResource;
3872 tempChildResource = tempChildResource->next;
3875 // In this case, the number of resource handles in the collection exceeds the index
3876 tempChildResource = NULL;
3880 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3881 OCEntityHandler entityHandler,
3882 void* callbackParam)
3884 OCResource *resource = NULL;
3886 // Validate parameters
3887 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3889 // Use the handle to find the resource in the resource linked list
3890 resource = findResource((OCResource *)handle);
3893 OIC_LOG(ERROR, TAG, "Resource not found");
3894 return OC_STACK_ERROR;
3898 resource->entityHandler = entityHandler;
3899 resource->entityHandlerCallbackParam = callbackParam;
3901 #ifdef WITH_PRESENCE
3902 if (presenceResource.handle)
3904 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3905 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3912 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3914 OCResource *resource = NULL;
3916 resource = findResource((OCResource *)handle);
3919 OIC_LOG(ERROR, TAG, "Resource not found");
3924 return resource->entityHandler;
3927 void incrementSequenceNumber(OCResource * resPtr)
3929 // Increment the sequence number
3930 resPtr->sequenceNum += 1;
3931 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3933 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3938 #ifdef WITH_PRESENCE
3939 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3940 OCPresenceTrigger trigger)
3942 OCResource *resPtr = NULL;
3943 OCStackResult result = OC_STACK_ERROR;
3944 OCMethod method = OC_REST_PRESENCE;
3945 uint32_t maxAge = 0;
3946 resPtr = findResource((OCResource *) presenceResource.handle);
3949 return OC_STACK_NO_RESOURCE;
3952 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3954 maxAge = presenceResource.presenceTTL;
3956 result = SendAllObserverNotification(method, resPtr, maxAge,
3957 trigger, resourceType, OC_LOW_QOS);
3963 OCStackResult SendStopNotification()
3965 OCResource *resPtr = NULL;
3966 OCStackResult result = OC_STACK_ERROR;
3967 OCMethod method = OC_REST_PRESENCE;
3968 resPtr = findResource((OCResource *) presenceResource.handle);
3971 return OC_STACK_NO_RESOURCE;
3974 // maxAge is 0. ResourceType is NULL.
3975 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3981 #endif // WITH_PRESENCE
3982 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3984 OCResource *resPtr = NULL;
3985 OCStackResult result = OC_STACK_ERROR;
3986 OCMethod method = OC_REST_NOMETHOD;
3987 uint32_t maxAge = 0;
3989 OIC_LOG(INFO, TAG, "Notifying all observers");
3990 #ifdef WITH_PRESENCE
3991 if(handle == presenceResource.handle)
3995 #endif // WITH_PRESENCE
3996 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3998 // Verify that the resource exists
3999 resPtr = findResource ((OCResource *) handle);
4002 return OC_STACK_NO_RESOURCE;
4006 //only increment in the case of regular observing (not presence)
4007 incrementSequenceNumber(resPtr);
4008 method = OC_REST_OBSERVE;
4009 maxAge = MAX_OBSERVE_AGE;
4010 #ifdef WITH_PRESENCE
4011 result = SendAllObserverNotification (method, resPtr, maxAge,
4012 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4014 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4021 OCNotifyListOfObservers (OCResourceHandle handle,
4022 OCObservationId *obsIdList,
4023 uint8_t numberOfIds,
4024 const OCRepPayload *payload,
4025 OCQualityOfService qos)
4027 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4029 OCResource *resPtr = NULL;
4030 //TODO: we should allow the server to define this
4031 uint32_t maxAge = MAX_OBSERVE_AGE;
4033 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4034 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4035 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4037 resPtr = findResource ((OCResource *) handle);
4038 if (NULL == resPtr || myStackMode == OC_CLIENT)
4040 return OC_STACK_NO_RESOURCE;
4044 incrementSequenceNumber(resPtr);
4046 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4047 payload, maxAge, qos));
4050 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4052 OCStackResult result = OC_STACK_ERROR;
4053 OCServerRequest *serverRequest = NULL;
4055 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4057 // Validate input parameters
4058 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4059 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4062 // Get pointer to request info
4063 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4066 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4067 result = serverRequest->ehResponseHandler(ehResponse);
4073 //#ifdef DIRECT_PAIRING
4074 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4076 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4077 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4079 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4083 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4086 const OCDPDev_t* OCGetDirectPairedDevices()
4088 return (const OCDPDev_t*)DPGetPairedDevices();
4091 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4092 OCDirectPairingCB resultCallback)
4094 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4095 if(NULL == peer || NULL == pinNumber)
4097 OIC_LOG(ERROR, TAG, "Invalid parameters");
4098 return OC_STACK_INVALID_PARAM;
4100 if (NULL == resultCallback)
4102 OIC_LOG(ERROR, TAG, "Invalid callback");
4103 return OC_STACK_INVALID_CALLBACK;
4106 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4107 pinNumber, (OCDirectPairingResultCB)resultCallback);
4109 //#endif // DIRECT_PAIRING
4111 //-----------------------------------------------------------------------------
4112 // Private internal function definitions
4113 //-----------------------------------------------------------------------------
4114 static OCDoHandle GenerateInvocationHandle()
4116 OCDoHandle handle = NULL;
4117 // Generate token here, it will be deleted when the transaction is deleted
4118 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4121 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4127 #ifdef WITH_PRESENCE
4128 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4129 OCResourceProperty resourceProperties, uint8_t enable)
4133 return OC_STACK_INVALID_PARAM;
4135 if (resourceProperties
4136 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4138 OIC_LOG(ERROR, TAG, "Invalid property");
4139 return OC_STACK_INVALID_PARAM;
4143 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4147 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4153 OCStackResult initResources()
4155 OCStackResult result = OC_STACK_OK;
4157 headResource = NULL;
4158 tailResource = NULL;
4159 // Init Virtual Resources
4160 #ifdef WITH_PRESENCE
4161 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4163 result = OCCreateResource(&presenceResource.handle,
4164 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4166 OC_RSRVD_PRESENCE_URI,
4170 //make resource inactive
4171 result = OCChangeResourceProperty(
4172 &(((OCResource *) presenceResource.handle)->resourceProperties),
4175 #ifndef WITH_ARDUINO
4176 if (result == OC_STACK_OK)
4178 result = SRMInitSecureResources();
4182 if(result == OC_STACK_OK)
4184 CreateResetProfile();
4185 result = OCCreateResource(&deviceResource,
4186 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4187 OC_RSRVD_INTERFACE_DEFAULT,
4188 OC_RSRVD_DEVICE_URI,
4192 if(result == OC_STACK_OK)
4194 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4195 OC_RSRVD_INTERFACE_READ);
4199 if(result == OC_STACK_OK)
4201 result = OCCreateResource(&platformResource,
4202 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4203 OC_RSRVD_INTERFACE_DEFAULT,
4204 OC_RSRVD_PLATFORM_URI,
4208 if(result == OC_STACK_OK)
4210 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4211 OC_RSRVD_INTERFACE_READ);
4218 void insertResource(OCResource *resource)
4222 headResource = resource;
4223 tailResource = resource;
4227 tailResource->next = resource;
4228 tailResource = resource;
4230 resource->next = NULL;
4233 OCResource *findResource(OCResource *resource)
4235 OCResource *pointer = headResource;
4239 if (pointer == resource)
4243 pointer = pointer->next;
4248 void deleteAllResources()
4250 OCResource *pointer = headResource;
4251 OCResource *temp = NULL;
4255 temp = pointer->next;
4256 #ifdef WITH_PRESENCE
4257 if (pointer != (OCResource *) presenceResource.handle)
4259 #endif // WITH_PRESENCE
4260 deleteResource(pointer);
4261 #ifdef WITH_PRESENCE
4263 #endif // WITH_PRESENCE
4266 memset(&platformResource, 0, sizeof(platformResource));
4267 memset(&deviceResource, 0, sizeof(deviceResource));
4269 memset(&brokerResource, 0, sizeof(brokerResource));
4272 SRMDeInitSecureResources();
4274 #ifdef WITH_PRESENCE
4275 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4276 // presence notification attributed to their deletion to be processed.
4277 deleteResource((OCResource *) presenceResource.handle);
4278 memset(&presenceResource, 0, sizeof(presenceResource));
4279 #endif // WITH_PRESENCE
4282 OCStackResult deleteResource(OCResource *resource)
4284 OCResource *prev = NULL;
4285 OCResource *temp = NULL;
4288 OIC_LOG(DEBUG,TAG,"resource is NULL");
4289 return OC_STACK_INVALID_PARAM;
4292 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4294 temp = headResource;
4297 if (temp == resource)
4299 // Invalidate all Resource Properties.
4300 resource->resourceProperties = (OCResourceProperty) 0;
4301 #ifdef WITH_PRESENCE
4302 if(resource != (OCResource *) presenceResource.handle)
4304 #endif // WITH_PRESENCE
4305 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4306 #ifdef WITH_PRESENCE
4309 if(presenceResource.handle)
4311 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4312 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4315 // Only resource in list.
4316 if (temp == headResource && temp == tailResource)
4318 headResource = NULL;
4319 tailResource = NULL;
4322 else if (temp == headResource)
4324 headResource = temp->next;
4327 else if (temp == tailResource)
4329 tailResource = prev;
4330 tailResource->next = NULL;
4334 prev->next = temp->next;
4337 deleteResourceElements(temp);
4348 return OC_STACK_ERROR;
4351 void deleteResourceElements(OCResource *resource)
4358 OICFree(resource->uri);
4359 deleteResourceType(resource->rsrcType);
4360 deleteResourceInterface(resource->rsrcInterface);
4363 void deleteResourceType(OCResourceType *resourceType)
4365 OCResourceType *pointer = resourceType;
4366 OCResourceType *next = NULL;
4370 next = pointer->next;
4371 OICFree(pointer->resourcetypename);
4377 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4379 OCResourceInterface *pointer = resourceInterface;
4380 OCResourceInterface *next = NULL;
4384 next = pointer->next;
4385 OICFree(pointer->name);
4391 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4393 OCResourceType *pointer = NULL;
4394 OCResourceType *previous = NULL;
4395 if (!resource || !resourceType)
4399 // resource type list is empty.
4400 else if (!resource->rsrcType)
4402 resource->rsrcType = resourceType;
4406 pointer = resource->rsrcType;
4410 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4412 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4413 OICFree(resourceType->resourcetypename);
4414 OICFree(resourceType);
4418 pointer = pointer->next;
4423 previous->next = resourceType;
4426 resourceType->next = NULL;
4428 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4431 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4433 OCResource *resource = NULL;
4434 OCResourceType *pointer = NULL;
4436 // Find the specified resource
4437 resource = findResource((OCResource *) handle);
4443 // Make sure a resource has a resourcetype
4444 if (!resource->rsrcType)
4449 // Iterate through the list
4450 pointer = resource->rsrcType;
4451 for(uint8_t i = 0; i< index && pointer; ++i)
4453 pointer = pointer->next;
4458 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4460 if(resourceTypeList && resourceTypeName)
4462 OCResourceType * rtPointer = resourceTypeList;
4463 while(resourceTypeName && rtPointer)
4465 if(rtPointer->resourcetypename &&
4466 strcmp(resourceTypeName, (const char *)
4467 (rtPointer->resourcetypename)) == 0)
4471 rtPointer = rtPointer->next;
4479 * Insert a new interface into interface linked list only if not already present.
4480 * If alredy present, 2nd arg is free'd.
4481 * Default interface will always be first if present.
4483 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4485 OCResourceInterface *pointer = NULL;
4486 OCResourceInterface *previous = NULL;
4488 newInterface->next = NULL;
4490 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4492 if (!*firstInterface)
4494 // If first interface is not oic.if.baseline, by default add it as first interface type.
4495 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4497 *firstInterface = newInterface;
4501 OCStackResult result = BindResourceInterfaceToResource(resource,
4502 OC_RSRVD_INTERFACE_DEFAULT);
4503 if (result != OC_STACK_OK)
4505 OICFree(newInterface->name);
4506 OICFree(newInterface);
4509 if (*firstInterface)
4511 (*firstInterface)->next = newInterface;
4515 // If once add oic.if.baseline, later too below code take care of freeing memory.
4516 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4518 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4520 OICFree(newInterface->name);
4521 OICFree(newInterface);
4524 // This code will not hit anymore, keeping
4527 newInterface->next = *firstInterface;
4528 *firstInterface = newInterface;
4533 pointer = *firstInterface;
4536 if (strcmp(newInterface->name, pointer->name) == 0)
4538 OICFree(newInterface->name);
4539 OICFree(newInterface);
4543 pointer = pointer->next;
4548 previous->next = newInterface;
4553 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4556 OCResource *resource = NULL;
4557 OCResourceInterface *pointer = NULL;
4559 // Find the specified resource
4560 resource = findResource((OCResource *) handle);
4566 // Make sure a resource has a resourceinterface
4567 if (!resource->rsrcInterface)
4572 // Iterate through the list
4573 pointer = resource->rsrcInterface;
4575 for (uint8_t i = 0; i < index && pointer; ++i)
4577 pointer = pointer->next;
4583 * This function splits the uri using the '?' delimiter.
4584 * "uriWithoutQuery" is the block of characters between the beginning
4585 * till the delimiter or '\0' which ever comes first.
4586 * "query" is whatever is to the right of the delimiter if present.
4587 * No delimiter sets the query to NULL.
4588 * If either are present, they will be malloc'ed into the params 2, 3.
4589 * The first param, *uri is left untouched.
4591 * NOTE: This function does not account for whitespace at the end of the uri NOR
4592 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4593 * part of the query.
4595 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4599 return OC_STACK_INVALID_URI;
4601 if(!query || !uriWithoutQuery)
4603 return OC_STACK_INVALID_PARAM;
4607 *uriWithoutQuery = NULL;
4609 size_t uriWithoutQueryLen = 0;
4610 size_t queryLen = 0;
4611 size_t uriLen = strlen(uri);
4613 char *pointerToDelimiter = strstr(uri, "?");
4615 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4616 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4618 if (uriWithoutQueryLen)
4620 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4621 if (!*uriWithoutQuery)
4625 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4629 *query = (char *) OICCalloc(queryLen + 1, 1);
4632 OICFree(*uriWithoutQuery);
4633 *uriWithoutQuery = NULL;
4636 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4642 return OC_STACK_NO_MEMORY;
4645 static const OicUuid_t* OCGetServerInstanceID(void)
4647 static bool generated = false;
4648 static OicUuid_t sid;
4654 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4656 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4663 const char* OCGetServerInstanceIDString(void)
4665 static bool generated = false;
4666 static char sidStr[UUID_STRING_SIZE];
4673 const OicUuid_t *sid = OCGetServerInstanceID();
4674 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4676 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4684 CAResult_t OCSelectNetwork()
4686 CAResult_t retResult = CA_STATUS_FAILED;
4687 CAResult_t caResult = CA_STATUS_OK;
4689 CATransportAdapter_t connTypes[] = {
4691 CA_ADAPTER_RFCOMM_BTEDR,
4692 CA_ADAPTER_GATT_BTLE,
4695 ,CA_ADAPTER_REMOTE_ACCESS
4702 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4704 for(int i = 0; i < numConnTypes; i++)
4706 // If CA status is not initialized, CASelectNetwork() will not be called.
4707 if (caResult != CA_STATUS_NOT_INITIALIZED)
4709 caResult = CASelectNetwork(connTypes[i]);
4710 if (caResult == CA_STATUS_OK)
4712 retResult = CA_STATUS_OK;
4717 if (retResult != CA_STATUS_OK)
4719 return caResult; // Returns error of appropriate transport that failed fatally.
4725 OCStackResult CAResultToOCResult(CAResult_t caResult)
4731 case CA_STATUS_INVALID_PARAM:
4732 return OC_STACK_INVALID_PARAM;
4733 case CA_ADAPTER_NOT_ENABLED:
4734 return OC_STACK_ADAPTER_NOT_ENABLED;
4735 case CA_SERVER_STARTED_ALREADY:
4737 case CA_SERVER_NOT_STARTED:
4738 return OC_STACK_ERROR;
4739 case CA_DESTINATION_NOT_REACHABLE:
4740 return OC_STACK_COMM_ERROR;
4741 case CA_SOCKET_OPERATION_FAILED:
4742 return OC_STACK_COMM_ERROR;
4743 case CA_SEND_FAILED:
4744 return OC_STACK_COMM_ERROR;
4745 case CA_RECEIVE_FAILED:
4746 return OC_STACK_COMM_ERROR;
4747 case CA_MEMORY_ALLOC_FAILED:
4748 return OC_STACK_NO_MEMORY;
4749 case CA_REQUEST_TIMEOUT:
4750 return OC_STACK_TIMEOUT;
4751 case CA_DESTINATION_DISCONNECTED:
4752 return OC_STACK_COMM_ERROR;
4753 case CA_STATUS_FAILED:
4754 return OC_STACK_ERROR;
4755 case CA_NOT_SUPPORTED:
4756 return OC_STACK_NOTIMPL;
4758 return OC_STACK_ERROR;
4762 bool OCResultToSuccess(OCStackResult ocResult)
4767 case OC_STACK_RESOURCE_CREATED:
4768 case OC_STACK_RESOURCE_DELETED:
4769 case OC_STACK_CONTINUE:
4770 case OC_STACK_RESOURCE_CHANGED:
4771 case OC_STACK_SLOW_RESOURCE:
4778 #if defined(RD_CLIENT) || defined(RD_SERVER)
4779 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
4781 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4783 OCResource *resource = NULL;
4785 resource = findResource((OCResource *) handle);
4788 OIC_LOG(ERROR, TAG, "Resource not found");
4789 return OC_STACK_ERROR;
4792 resource->ins = ins;
4797 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
4801 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
4805 OCResource *pointer = headResource;
4809 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
4811 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
4814 pointer = pointer->next;
4819 OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
4821 OCResource *resource = NULL;
4823 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4824 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
4826 resource = findResource((OCResource *) handle);
4829 *ins = resource->ins;
4832 return OC_STACK_ERROR;