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);
1597 FindAndDeleteClientCB(cbNode);
1600 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1604 * This function sends out Direct Stack Responses. These are responses that are not coming
1605 * from the application entity handler. These responses have no payload and are usually ACKs,
1606 * RESETs or some error conditions that were caught by the stack.
1608 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1609 const CAResponseResult_t responseResult, const CAMessageType_t type,
1610 const uint8_t numOptions, const CAHeaderOption_t *options,
1611 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1612 CADataType_t dataType)
1614 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1615 CAResponseInfo_t respInfo = {
1616 .result = responseResult
1618 respInfo.info.messageId = coapID;
1619 respInfo.info.numOptions = numOptions;
1621 if (respInfo.info.numOptions)
1623 respInfo.info.options =
1624 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1625 memcpy (respInfo.info.options, options,
1626 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1630 respInfo.info.payload = NULL;
1631 respInfo.info.token = token;
1632 respInfo.info.tokenLength = tokenLength;
1633 respInfo.info.type = type;
1634 respInfo.info.resourceUri = OICStrdup (resourceUri);
1635 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1636 respInfo.info.dataType = dataType;
1638 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1639 // Add the destination to route option from the endpoint->routeData.
1640 bool doPost = false;
1641 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1642 if(OC_STACK_OK != result)
1644 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1649 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1650 CARequestInfo_t reqInfo = {.method = CA_POST };
1651 /* The following initialization is not done in a single initializer block as in
1652 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1653 * does not have designated initalizers. This is a work-around for now.
1655 reqInfo.info.type = CA_MSG_NONCONFIRM;
1656 reqInfo.info.messageId = coapID;
1657 reqInfo.info.tokenLength = tokenLength;
1658 reqInfo.info.token = token;
1659 reqInfo.info.numOptions = respInfo.info.numOptions;
1660 reqInfo.info.payload = NULL;
1661 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1662 if (reqInfo.info.numOptions)
1664 reqInfo.info.options =
1665 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1666 if (NULL == reqInfo.info.options)
1668 OIC_LOG(ERROR, TAG, "Calloc failed");
1669 return OC_STACK_NO_MEMORY;
1671 memcpy (reqInfo.info.options, respInfo.info.options,
1672 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1675 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1676 OICFree (reqInfo.info.resourceUri);
1677 OICFree (reqInfo.info.options);
1678 OICFree (respInfo.info.resourceUri);
1679 OICFree (respInfo.info.options);
1680 if (CA_STATUS_OK != caResult)
1682 OIC_LOG(ERROR, TAG, "CASendRequest error");
1683 return CAResultToOCResult(caResult);
1689 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1691 // resourceUri in the info field is cloned in the CA layer and
1692 // thus ownership is still here.
1693 OICFree (respInfo.info.resourceUri);
1694 OICFree (respInfo.info.options);
1695 if(CA_STATUS_OK != caResult)
1697 OIC_LOG(ERROR, TAG, "CASendResponse error");
1698 return CAResultToOCResult(caResult);
1701 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1705 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1707 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1708 OCStackResult result = OC_STACK_ERROR;
1709 if(!protocolRequest)
1711 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1712 return OC_STACK_INVALID_PARAM;
1715 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1716 protocolRequest->tokenLength);
1719 OIC_LOG(INFO, TAG, "This is a new Server Request");
1720 result = AddServerRequest(&request, protocolRequest->coapID,
1721 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1722 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1723 protocolRequest->observationOption, protocolRequest->qos,
1724 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1725 protocolRequest->payload, protocolRequest->requestToken,
1726 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1727 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1728 &protocolRequest->devAddr);
1729 if (OC_STACK_OK != result)
1731 OIC_LOG(ERROR, TAG, "Error adding server request");
1737 OIC_LOG(ERROR, TAG, "Out of Memory");
1738 return OC_STACK_NO_MEMORY;
1741 if(!protocolRequest->reqMorePacket)
1743 request->requestComplete = 1;
1748 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1751 if(request->requestComplete)
1753 OIC_LOG(INFO, TAG, "This Server Request is complete");
1754 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1755 OCResource *resource = NULL;
1756 result = DetermineResourceHandling (request, &resHandling, &resource);
1757 if (result == OC_STACK_OK)
1759 result = ProcessRequest(resHandling, resource, request);
1764 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1765 result = OC_STACK_CONTINUE;
1770 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1772 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1775 if (requestInfo->info.resourceUri &&
1776 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1778 HandleKeepAliveRequest(endPoint, requestInfo);
1783 OCStackResult requestResult = OC_STACK_ERROR;
1785 if(myStackMode == OC_CLIENT)
1787 //TODO: should the client be responding to requests?
1791 OCServerProtocolRequest serverRequest = {0};
1793 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1795 char * uriWithoutQuery = NULL;
1796 char * query = NULL;
1798 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1800 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1802 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1805 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1806 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1808 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1810 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1811 OICFree(uriWithoutQuery);
1815 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1816 OICFree(uriWithoutQuery);
1823 if(strlen(query) < MAX_QUERY_LENGTH)
1825 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1830 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1836 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1838 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1839 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1840 if (!serverRequest.payload)
1842 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1845 memcpy (serverRequest.payload, requestInfo->info.payload,
1846 requestInfo->info.payloadSize);
1850 serverRequest.reqTotalSize = 0;
1853 switch (requestInfo->method)
1856 serverRequest.method = OC_REST_GET;
1859 serverRequest.method = OC_REST_PUT;
1862 serverRequest.method = OC_REST_POST;
1865 serverRequest.method = OC_REST_DELETE;
1868 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1869 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1870 requestInfo->info.type, requestInfo->info.numOptions,
1871 requestInfo->info.options, requestInfo->info.token,
1872 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1874 OICFree(serverRequest.payload);
1878 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1879 requestInfo->info.tokenLength);
1881 serverRequest.tokenLength = requestInfo->info.tokenLength;
1882 if (serverRequest.tokenLength) {
1884 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1886 if (!serverRequest.requestToken)
1888 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1889 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1890 requestInfo->info.type, requestInfo->info.numOptions,
1891 requestInfo->info.options, requestInfo->info.token,
1892 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1894 OICFree(serverRequest.payload);
1897 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1900 switch (requestInfo->info.acceptFormat)
1902 case CA_FORMAT_APPLICATION_CBOR:
1903 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1905 case CA_FORMAT_UNDEFINED:
1906 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1909 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1912 if (requestInfo->info.type == CA_MSG_CONFIRM)
1914 serverRequest.qos = OC_HIGH_QOS;
1918 serverRequest.qos = OC_LOW_QOS;
1920 // CA does not need the following field
1921 // Are we sure CA does not need them? how is it responding to multicast
1922 serverRequest.delayedResNeeded = 0;
1924 serverRequest.coapID = requestInfo->info.messageId;
1926 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1928 // copy vendor specific header options
1929 uint8_t tempNum = (requestInfo->info.numOptions);
1931 // Assume no observation requested and it is a pure GET.
1932 // If obs registration/de-registration requested it'll be fetched from the
1933 // options in GetObserveHeaderOption()
1934 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1936 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1937 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1940 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1941 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1942 requestInfo->info.type, requestInfo->info.numOptions,
1943 requestInfo->info.options, requestInfo->info.token,
1944 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1946 OICFree(serverRequest.payload);
1947 OICFree(serverRequest.requestToken);
1950 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1951 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1953 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1954 sizeof(CAHeaderOption_t)*tempNum);
1957 requestResult = HandleStackRequests (&serverRequest);
1959 // Send ACK to client as precursor to slow response
1960 if (requestResult == OC_STACK_SLOW_RESOURCE)
1962 if (requestInfo->info.type == CA_MSG_CONFIRM)
1964 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1965 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
1969 else if(!OCResultToSuccess(requestResult))
1971 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1973 CAResponseResult_t stackResponse =
1974 OCToCAStackResult(requestResult, serverRequest.method);
1976 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1977 requestInfo->info.type, requestInfo->info.numOptions,
1978 requestInfo->info.options, requestInfo->info.token,
1979 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1982 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1983 // The token is copied in there, and is thus still owned by this function.
1984 OICFree(serverRequest.payload);
1985 OICFree(serverRequest.requestToken);
1986 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1989 //This function will be called back by CA layer when a request is received
1990 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1992 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1995 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2001 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2005 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2006 #ifdef ROUTING_GATEWAY
2007 bool needRIHandling = false;
2008 bool isEmptyMsg = false;
2010 * Routing manager is going to update either of endpoint or request or both.
2011 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2012 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2013 * destination. It can also remove "RM" coap header option before passing request / response to
2014 * RI as this option will make no sense to either RI or application.
2016 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2017 &needRIHandling, &isEmptyMsg);
2018 if(OC_STACK_OK != ret || !needRIHandling)
2020 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2026 * Put source in sender endpoint so that the next packet from application can be routed to
2027 * proper destination and remove RM header option.
2029 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2030 (uint8_t *) &(requestInfo->info.numOptions),
2031 (CAEndpoint_t *) endPoint);
2033 #ifdef ROUTING_GATEWAY
2037 * In Gateways, the MSGType in route option is used to check if the actual
2038 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2039 * EMPTY response is sent in the form of POST request which need to be changed
2040 * to a EMPTY response by RM. This translation is done in this part of the code.
2042 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2043 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2044 .info.messageId = requestInfo->info.messageId,
2045 .info.type = CA_MSG_ACKNOWLEDGE};
2046 OCHandleResponse(endPoint, &respInfo);
2052 // Normal handling of the packet
2053 OCHandleRequests(endPoint, requestInfo);
2055 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2058 bool validatePlatformInfo(OCPlatformInfo info)
2061 if (!info.platformID)
2063 OIC_LOG(ERROR, TAG, "No platform ID found.");
2067 if (info.manufacturerName)
2069 size_t lenManufacturerName = strlen(info.manufacturerName);
2071 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2073 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2079 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2083 if (info.manufacturerUrl)
2085 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2087 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2094 //-----------------------------------------------------------------------------
2096 //-----------------------------------------------------------------------------
2098 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2101 !raInfo->username ||
2102 !raInfo->hostname ||
2103 !raInfo->xmpp_domain)
2106 return OC_STACK_INVALID_PARAM;
2108 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2109 gRASetInfo = (result == OC_STACK_OK)? true : false;
2115 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2119 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2122 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2124 if(stackState == OC_STACK_INITIALIZED)
2126 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2127 OCStop() between them are ignored.");
2131 #ifndef ROUTING_GATEWAY
2132 if (OC_GATEWAY == mode)
2134 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2135 return OC_STACK_INVALID_PARAM;
2142 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2143 return OC_STACK_ERROR;
2147 OCStackResult result = OC_STACK_ERROR;
2148 OIC_LOG(INFO, TAG, "Entering OCInit");
2151 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2152 || (mode == OC_GATEWAY)))
2154 OIC_LOG(ERROR, TAG, "Invalid mode");
2155 return OC_STACK_ERROR;
2159 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2161 caglobals.client = true;
2163 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2165 caglobals.server = true;
2168 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2169 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2171 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2173 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2174 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2176 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2179 defaultDeviceHandler = NULL;
2180 defaultDeviceHandlerCallbackParameter = NULL;
2182 result = CAResultToOCResult(CAInitialize());
2183 VERIFY_SUCCESS(result, OC_STACK_OK);
2185 result = CAResultToOCResult(OCSelectNetwork());
2186 VERIFY_SUCCESS(result, OC_STACK_OK);
2188 switch (myStackMode)
2191 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2192 result = CAResultToOCResult(CAStartDiscoveryServer());
2193 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2196 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2197 result = CAResultToOCResult(CAStartListeningServer());
2198 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2200 case OC_CLIENT_SERVER:
2202 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2203 result = CAResultToOCResult(CAStartListeningServer());
2204 if(result == OC_STACK_OK)
2206 result = CAResultToOCResult(CAStartDiscoveryServer());
2210 VERIFY_SUCCESS(result, OC_STACK_OK);
2213 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2216 #ifdef WITH_PRESENCE
2217 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2218 #endif // WITH_PRESENCE
2220 //Update Stack state to initialized
2221 stackState = OC_STACK_INITIALIZED;
2223 // Initialize resource
2224 if(myStackMode != OC_CLIENT)
2226 result = initResources();
2229 // Initialize the SRM Policy Engine
2230 if(result == OC_STACK_OK)
2232 result = SRMInitPolicyEngine();
2233 // TODO after BeachHead delivery: consolidate into single SRMInit()
2235 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2236 RMSetStackMode(mode);
2237 #ifdef ROUTING_GATEWAY
2238 if (OC_GATEWAY == myStackMode)
2240 result = RMInitialize();
2246 if (result == OC_STACK_OK)
2248 result = InitializeKeepAlive(myStackMode);
2253 if(result != OC_STACK_OK)
2255 OIC_LOG(ERROR, TAG, "Stack initialization error");
2256 deleteAllResources();
2258 stackState = OC_STACK_UNINITIALIZED;
2263 OCStackResult OCStop()
2265 OIC_LOG(INFO, TAG, "Entering OCStop");
2267 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2269 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2272 else if (stackState != OC_STACK_INITIALIZED)
2274 OIC_LOG(ERROR, TAG, "Stack not initialized");
2275 return OC_STACK_ERROR;
2278 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2280 #ifdef WITH_PRESENCE
2281 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2282 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2283 presenceResource.presenceTTL = 0;
2284 #endif // WITH_PRESENCE
2286 #ifdef ROUTING_GATEWAY
2287 if (OC_GATEWAY == myStackMode)
2294 TerminateKeepAlive(myStackMode);
2297 // Free memory dynamically allocated for resources
2298 deleteAllResources();
2300 DeletePlatformInfo();
2302 // Remove all observers
2303 DeleteObserverList();
2304 // Remove all the client callbacks
2305 DeleteClientCBList();
2307 // De-init the SRM Policy Engine
2308 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2309 SRMDeInitPolicyEngine();
2312 stackState = OC_STACK_UNINITIALIZED;
2316 OCStackResult OCStartMulticastServer()
2318 if(stackState != OC_STACK_INITIALIZED)
2320 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2321 return OC_STACK_ERROR;
2323 CAResult_t ret = CAStartListeningServer();
2324 if (CA_STATUS_OK != ret)
2326 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2327 return OC_STACK_ERROR;
2332 OCStackResult OCStopMulticastServer()
2334 CAResult_t ret = CAStopListeningServer();
2335 if (CA_STATUS_OK != ret)
2337 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2338 return OC_STACK_ERROR;
2343 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2348 return CA_MSG_CONFIRM;
2353 return CA_MSG_NONCONFIRM;
2358 * A request uri consists of the following components in order:
2361 * CoAP over UDP prefix "coap://"
2362 * CoAP over TCP prefix "coap+tcp://"
2363 * CoAP over DTLS prefix "coaps://"
2364 * CoAP over TLS prefix "coaps+tcp://"
2366 * IPv6 address "[1234::5678]"
2367 * IPv4 address "192.168.1.1"
2368 * optional port ":5683"
2369 * resource uri "/oc/core..."
2371 * for PRESENCE requests, extract resource type.
2373 static OCStackResult ParseRequestUri(const char *fullUri,
2374 OCTransportAdapter adapter,
2375 OCTransportFlags flags,
2376 OCDevAddr **devAddr,
2378 char **resourceType)
2380 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2382 OCStackResult result = OC_STACK_OK;
2383 OCDevAddr *da = NULL;
2387 // provide defaults for all returned values
2394 *resourceUri = NULL;
2398 *resourceType = NULL;
2401 // delimit url prefix, if any
2402 const char *start = fullUri;
2403 char *slash2 = strstr(start, "//");
2408 char *slash = strchr(start, '/');
2411 return OC_STACK_INVALID_URI;
2414 // process url scheme
2415 size_t prefixLen = slash2 - fullUri;
2419 if (((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2420 || ((prefixLen == sizeof(COAPS_TCP) - 1) && (!strncmp(fullUri, COAPS_TCP, prefixLen))))
2426 // TODO: this logic should come in with unit tests exercising the various strings
2427 // processs url prefix, if any
2428 size_t urlLen = slash - start;
2432 if (urlLen && devAddr)
2433 { // construct OCDevAddr
2434 if (start[0] == '[')
2436 char *close = strchr(++start, ']');
2437 if (!close || close > slash)
2439 return OC_STACK_INVALID_URI;
2442 if (close[1] == ':')
2449 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2453 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2455 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2459 char *dot = strchr(start, '.');
2460 if (dot && dot < slash)
2462 colon = strchr(start, ':');
2463 end = (colon && colon < slash) ? colon : slash;
2468 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2472 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2474 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2482 if (len >= sizeof(da->addr))
2484 return OC_STACK_INVALID_URI;
2486 // collect port, if any
2487 if (colon && colon < slash)
2489 for (colon++; colon < slash; colon++)
2492 if (c < '0' || c > '9')
2494 return OC_STACK_INVALID_URI;
2496 port = 10 * port + c - '0';
2501 if (len >= sizeof(da->addr))
2503 return OC_STACK_INVALID_URI;
2506 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2509 return OC_STACK_NO_MEMORY;
2511 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2513 da->adapter = adapter;
2515 if (!strncmp(fullUri, "coaps", 5))
2517 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2522 // process resource uri, if any
2524 { // request uri and query
2525 size_t ulen = strlen(slash); // resource uri length
2526 size_t tlen = 0; // resource type length
2529 static const char strPresence[] = "/oic/ad?rt=";
2530 static const size_t lenPresence = sizeof(strPresence) - 1;
2531 if (!strncmp(slash, strPresence, lenPresence))
2533 type = slash + lenPresence;
2534 tlen = ulen - lenPresence;
2539 *resourceUri = (char *)OICMalloc(ulen + 1);
2542 result = OC_STACK_NO_MEMORY;
2545 strcpy(*resourceUri, slash);
2548 if (type && resourceType)
2550 *resourceType = (char *)OICMalloc(tlen + 1);
2553 result = OC_STACK_NO_MEMORY;
2557 OICStrcpy(*resourceType, (tlen+1), type);
2564 // free all returned values
2571 OICFree(*resourceUri);
2575 OICFree(*resourceType);
2580 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2581 char *resourceUri, char **requestUri)
2583 char uri[CA_MAX_URI_LENGTH];
2585 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2587 *requestUri = OICStrdup(uri);
2590 return OC_STACK_NO_MEMORY;
2597 * Discover or Perform requests on a specified resource
2599 OCStackResult OCDoResource(OCDoHandle *handle,
2601 const char *requestUri,
2602 const OCDevAddr *destination,
2604 OCConnectivityType connectivityType,
2605 OCQualityOfService qos,
2606 OCCallbackData *cbData,
2607 OCHeaderOption *options,
2610 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2612 // Validate input parameters
2613 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2614 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2615 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2617 OCStackResult result = OC_STACK_ERROR;
2618 CAResult_t caResult;
2619 CAToken_t token = NULL;
2620 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2621 ClientCB *clientCB = NULL;
2622 OCDoHandle resHandle = NULL;
2623 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2624 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2626 OCTransportAdapter adapter;
2627 OCTransportFlags flags;
2628 // the request contents are put here
2629 CARequestInfo_t requestInfo = {.method = CA_GET};
2630 // requestUri will be parsed into the following three variables
2631 OCDevAddr *devAddr = NULL;
2632 char *resourceUri = NULL;
2633 char *resourceType = NULL;
2636 * Support original behavior with address on resourceUri argument.
2638 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2639 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2641 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2643 if (result != OC_STACK_OK)
2645 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2652 case OC_REST_OBSERVE:
2653 case OC_REST_OBSERVE_ALL:
2654 case OC_REST_CANCEL_OBSERVE:
2655 requestInfo.method = CA_GET;
2658 requestInfo.method = CA_PUT;
2661 requestInfo.method = CA_POST;
2663 case OC_REST_DELETE:
2664 requestInfo.method = CA_DELETE;
2666 case OC_REST_DISCOVER:
2668 if (destination || devAddr)
2670 requestInfo.isMulticast = false;
2674 tmpDevAddr.adapter = adapter;
2675 tmpDevAddr.flags = flags;
2676 destination = &tmpDevAddr;
2677 requestInfo.isMulticast = true;
2679 // CA_DISCOVER will become GET and isMulticast
2680 requestInfo.method = CA_GET;
2682 #ifdef WITH_PRESENCE
2683 case OC_REST_PRESENCE:
2684 // Replacing method type with GET because "presence"
2685 // is a stack layer only implementation.
2686 requestInfo.method = CA_GET;
2690 result = OC_STACK_INVALID_METHOD;
2694 if (!devAddr && !destination)
2696 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2697 result = OC_STACK_INVALID_PARAM;
2701 /* If not original behavior, use destination argument */
2702 if (destination && !devAddr)
2704 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2707 result = OC_STACK_NO_MEMORY;
2710 *devAddr = *destination;
2713 resHandle = GenerateInvocationHandle();
2716 result = OC_STACK_NO_MEMORY;
2720 caResult = CAGenerateToken(&token, tokenLength);
2721 if (caResult != CA_STATUS_OK)
2723 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2724 result= OC_STACK_ERROR;
2728 // fill in request data
2729 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2730 requestInfo.info.token = token;
2731 requestInfo.info.tokenLength = tokenLength;
2732 requestInfo.info.resourceUri = resourceUri;
2734 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2736 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2737 options, numOptions, OC_OBSERVE_REGISTER);
2738 if (result != OC_STACK_OK)
2742 requestInfo.info.numOptions = numOptions + 1;
2746 requestInfo.info.numOptions = numOptions;
2747 requestInfo.info.options =
2748 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2749 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2750 numOptions * sizeof(CAHeaderOption_t));
2753 CopyDevAddrToEndpoint(devAddr, &endpoint);
2758 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2761 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2764 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2768 requestInfo.info.payload = NULL;
2769 requestInfo.info.payloadSize = 0;
2770 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2773 // prepare for response
2774 #ifdef WITH_PRESENCE
2775 if (method == OC_REST_PRESENCE)
2777 char *presenceUri = NULL;
2778 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2779 if (OC_STACK_OK != result)
2784 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2785 // Presence notification will form a canonical uri to
2786 // look for callbacks into the application.
2787 resourceUri = presenceUri;
2791 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2792 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2793 method, devAddr, resourceUri, resourceType, ttl);
2794 if (OC_STACK_OK != result)
2799 devAddr = NULL; // Client CB list entry now owns it
2800 resourceUri = NULL; // Client CB list entry now owns it
2801 resourceType = NULL; // Client CB list entry now owns it
2804 result = OCSendRequest(&endpoint, &requestInfo);
2805 if (OC_STACK_OK != result)
2812 *handle = resHandle;
2816 if (result != OC_STACK_OK)
2818 OIC_LOG(ERROR, TAG, "OCDoResource error");
2819 FindAndDeleteClientCB(clientCB);
2820 CADestroyToken(token);
2828 // This is the owner of the payload object, so we free it
2829 OCPayloadDestroy(payload);
2830 OICFree(requestInfo.info.payload);
2832 OICFree(resourceUri);
2833 OICFree(resourceType);
2834 OICFree(requestInfo.info.options);
2838 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2842 * This ftn is implemented one of two ways in the case of observation:
2844 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2845 * Remove the callback associated on client side.
2846 * When the next notification comes in from server,
2847 * reply with RESET message to server.
2848 * Keep in mind that the server will react to RESET only
2849 * if the last notification was sent as CON
2851 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2852 * and it is associated with an observe request
2853 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2854 * Send CON Observe request to server with
2855 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2856 * Remove the callback associated on client side.
2858 OCStackResult ret = OC_STACK_OK;
2859 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2860 CARequestInfo_t requestInfo = {.method = CA_GET};
2864 return OC_STACK_INVALID_PARAM;
2867 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2870 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2871 return OC_STACK_ERROR;
2874 switch (clientCB->method)
2876 case OC_REST_OBSERVE:
2877 case OC_REST_OBSERVE_ALL:
2879 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2881 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2883 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2885 FindAndDeleteClientCB(clientCB);
2889 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2891 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2892 requestInfo.info.token = clientCB->token;
2893 requestInfo.info.tokenLength = clientCB->tokenLength;
2895 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2896 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2898 return OC_STACK_ERROR;
2900 requestInfo.info.numOptions = numOptions + 1;
2901 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2904 ret = OCSendRequest(&endpoint, &requestInfo);
2906 if (requestInfo.info.options)
2908 OICFree (requestInfo.info.options);
2910 if (requestInfo.info.resourceUri)
2912 OICFree (requestInfo.info.resourceUri);
2917 case OC_REST_DISCOVER:
2918 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2919 clientCB->requestUri);
2920 FindAndDeleteClientCB(clientCB);
2923 #ifdef WITH_PRESENCE
2924 case OC_REST_PRESENCE:
2925 FindAndDeleteClientCB(clientCB);
2930 ret = OC_STACK_INVALID_METHOD;
2938 * @brief Register Persistent storage callback.
2939 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2941 * OC_STACK_OK - No errors; Success
2942 * OC_STACK_INVALID_PARAM - Invalid parameter
2944 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2946 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2947 if(!persistentStorageHandler)
2949 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2950 return OC_STACK_INVALID_PARAM;
2954 if( !persistentStorageHandler->open ||
2955 !persistentStorageHandler->close ||
2956 !persistentStorageHandler->read ||
2957 !persistentStorageHandler->unlink ||
2958 !persistentStorageHandler->write)
2960 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2961 return OC_STACK_INVALID_PARAM;
2964 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2967 #ifdef WITH_PRESENCE
2969 OCStackResult OCProcessPresence()
2971 OCStackResult result = OC_STACK_OK;
2973 // the following line floods the log with messages that are irrelevant
2974 // to most purposes. Uncomment as needed.
2975 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2976 ClientCB* cbNode = NULL;
2977 OCClientResponse clientResponse;
2978 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2980 LL_FOREACH(cbList, cbNode)
2982 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2987 uint32_t now = GetTicks(0);
2988 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2989 cbNode->presence->TTLlevel);
2990 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2992 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2997 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2999 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3000 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3002 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3004 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3006 clientResponse.sequenceNumber = 0;
3007 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3008 clientResponse.devAddr = *cbNode->devAddr;
3009 FixUpClientResponse(&clientResponse);
3010 clientResponse.payload = NULL;
3012 // Increment the TTLLevel (going to a next state), so we don't keep
3013 // sending presence notification to client.
3014 cbNode->presence->TTLlevel++;
3015 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3016 cbNode->presence->TTLlevel);
3018 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3019 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3021 FindAndDeleteClientCB(cbNode);
3025 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3030 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3031 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3032 CARequestInfo_t requestInfo = {.method = CA_GET};
3034 OIC_LOG(DEBUG, TAG, "time to test server presence");
3036 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3038 requestData.type = CA_MSG_NONCONFIRM;
3039 requestData.token = cbNode->token;
3040 requestData.tokenLength = cbNode->tokenLength;
3041 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3042 requestInfo.method = CA_GET;
3043 requestInfo.info = requestData;
3045 result = OCSendRequest(&endpoint, &requestInfo);
3046 if (OC_STACK_OK != result)
3051 cbNode->presence->TTLlevel++;
3052 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3055 if (result != OC_STACK_OK)
3057 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3062 #endif // WITH_PRESENCE
3064 OCStackResult OCProcess()
3066 #ifdef WITH_PRESENCE
3067 OCProcessPresence();
3069 CAHandleRequestResponse();
3071 #ifdef ROUTING_GATEWAY
3081 #ifdef WITH_PRESENCE
3082 OCStackResult OCStartPresence(const uint32_t ttl)
3084 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3085 OCChangeResourceProperty(
3086 &(((OCResource *)presenceResource.handle)->resourceProperties),
3089 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3091 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3092 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3096 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3097 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3101 presenceResource.presenceTTL = ttl;
3103 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3105 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3107 presenceState = OC_PRESENCE_INITIALIZED;
3109 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3111 CAToken_t caToken = NULL;
3112 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3113 if (caResult != CA_STATUS_OK)
3115 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3116 CADestroyToken(caToken);
3117 return OC_STACK_ERROR;
3120 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3121 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3122 CADestroyToken(caToken);
3125 // Each time OCStartPresence is called
3126 // a different random 32-bit integer number is used
3127 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3129 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3130 OC_PRESENCE_TRIGGER_CREATE);
3133 OCStackResult OCStopPresence()
3135 OCStackResult result = OC_STACK_ERROR;
3137 if(presenceResource.handle)
3139 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3141 // make resource inactive
3142 result = OCChangeResourceProperty(
3143 &(((OCResource *) presenceResource.handle)->resourceProperties),
3147 if(result != OC_STACK_OK)
3150 "Changing the presence resource properties to ACTIVE not successful");
3154 return SendStopNotification();
3158 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3159 void* callbackParameter)
3161 defaultDeviceHandler = entityHandler;
3162 defaultDeviceHandlerCallbackParameter = callbackParameter;
3167 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3169 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3171 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3173 if (validatePlatformInfo(platformInfo))
3175 return SavePlatformInfo(platformInfo);
3179 return OC_STACK_INVALID_PARAM;
3184 return OC_STACK_ERROR;
3188 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3190 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3192 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3194 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3195 return OC_STACK_INVALID_PARAM;
3198 if (deviceInfo.types)
3200 OCStringLL *type = deviceInfo.types;
3201 OCResource *resource = findResource((OCResource *) deviceResource);
3204 return OC_STACK_INVALID_PARAM;
3209 OCBindResourceTypeToResource(deviceResource, type->value);
3213 return SaveDeviceInfo(deviceInfo);
3216 OCStackResult OCCreateResource(OCResourceHandle *handle,
3217 const char *resourceTypeName,
3218 const char *resourceInterfaceName,
3219 const char *uri, OCEntityHandler entityHandler,
3220 void* callbackParam,
3221 uint8_t resourceProperties)
3224 OCResource *pointer = NULL;
3225 OCStackResult result = OC_STACK_ERROR;
3227 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3229 if(myStackMode == OC_CLIENT)
3231 return OC_STACK_INVALID_PARAM;
3233 // Validate parameters
3234 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3236 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3237 return OC_STACK_INVALID_URI;
3239 // Is it presented during resource discovery?
3240 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3242 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3243 return OC_STACK_INVALID_PARAM;
3246 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3248 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3252 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3254 // Make sure resourceProperties bitmask has allowed properties specified
3255 if (resourceProperties
3256 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3257 OC_EXPLICIT_DISCOVERABLE
3266 OIC_LOG(ERROR, TAG, "Invalid property");
3267 return OC_STACK_INVALID_PARAM;
3270 // If the headResource is NULL, then no resources have been created...
3271 pointer = headResource;
3274 // At least one resources is in the resource list, so we need to search for
3275 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3278 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3280 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3281 return OC_STACK_INVALID_PARAM;
3283 pointer = pointer->next;
3286 // Create the pointer and insert it into the resource list
3287 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3290 result = OC_STACK_NO_MEMORY;
3293 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3295 insertResource(pointer);
3298 pointer->uri = OICStrdup(uri);
3301 result = OC_STACK_NO_MEMORY;
3305 // Set properties. Set OC_ACTIVE
3306 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3309 // Add the resourcetype to the resource
3310 result = BindResourceTypeToResource(pointer, resourceTypeName);
3311 if (result != OC_STACK_OK)
3313 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3317 // Add the resourceinterface to the resource
3318 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3319 if (result != OC_STACK_OK)
3321 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3325 // If an entity handler has been passed, attach it to the newly created
3326 // resource. Otherwise, set the default entity handler.
3329 pointer->entityHandler = entityHandler;
3330 pointer->entityHandlerCallbackParam = callbackParam;
3334 pointer->entityHandler = defaultResourceEHandler;
3335 pointer->entityHandlerCallbackParam = NULL;
3338 // Initialize a pointer indicating child resources in case of collection
3339 pointer->rsrcChildResourcesHead = NULL;
3342 result = OC_STACK_OK;
3344 #ifdef WITH_PRESENCE
3345 if (presenceResource.handle)
3347 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3348 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3352 if (result != OC_STACK_OK)
3354 // Deep delete of resource and other dynamic elements that it contains
3355 deleteResource(pointer);
3360 OCStackResult OCBindResource(
3361 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3363 OCResource *resource = NULL;
3364 OCChildResource *tempChildResource = NULL;
3365 OCChildResource *newChildResource = NULL;
3367 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3369 // Validate parameters
3370 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3371 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3372 // Container cannot contain itself
3373 if (collectionHandle == resourceHandle)
3375 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3376 return OC_STACK_INVALID_PARAM;
3379 // Use the handle to find the resource in the resource linked list
3380 resource = findResource((OCResource *) collectionHandle);
3383 OIC_LOG(ERROR, TAG, "Collection handle not found");
3384 return OC_STACK_INVALID_PARAM;
3387 // Look for an open slot to add add the child resource.
3388 // If found, add it and return success
3390 tempChildResource = resource->rsrcChildResourcesHead;
3392 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3394 // TODO: what if one of child resource was deregistered without unbinding?
3395 tempChildResource = tempChildResource->next;
3398 // Do memory allocation for child resource
3399 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3400 if(!newChildResource)
3402 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3403 return OC_STACK_ERROR;
3406 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3407 newChildResource->next = NULL;
3409 if(!resource->rsrcChildResourcesHead)
3411 resource->rsrcChildResourcesHead = newChildResource;
3414 tempChildResource->next = newChildResource;
3417 OIC_LOG(INFO, TAG, "resource bound");
3419 #ifdef WITH_PRESENCE
3420 if (presenceResource.handle)
3422 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3423 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3424 OC_PRESENCE_TRIGGER_CHANGE);
3431 OCStackResult OCUnBindResource(
3432 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3434 OCResource *resource = NULL;
3435 OCChildResource *tempChildResource = NULL;
3436 OCChildResource *tempLastChildResource = NULL;
3438 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3440 // Validate parameters
3441 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3442 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3443 // Container cannot contain itself
3444 if (collectionHandle == resourceHandle)
3446 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3447 return OC_STACK_INVALID_PARAM;
3450 // Use the handle to find the resource in the resource linked list
3451 resource = findResource((OCResource *) collectionHandle);
3454 OIC_LOG(ERROR, TAG, "Collection handle not found");
3455 return OC_STACK_INVALID_PARAM;
3458 // Look for an open slot to add add the child resource.
3459 // If found, add it and return success
3460 if(!resource->rsrcChildResourcesHead)
3462 OIC_LOG(INFO, TAG, "resource not found in collection");
3464 // Unable to add resourceHandle, so return error
3465 return OC_STACK_ERROR;
3469 tempChildResource = resource->rsrcChildResourcesHead;
3471 while (tempChildResource)
3473 if(tempChildResource->rsrcResource == resourceHandle)
3475 // if resource going to be unbinded is the head one.
3476 if( tempChildResource == resource->rsrcChildResourcesHead )
3478 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3479 OICFree(resource->rsrcChildResourcesHead);
3480 resource->rsrcChildResourcesHead = temp;
3485 OCChildResource *temp = tempChildResource->next;
3486 OICFree(tempChildResource);
3487 tempLastChildResource->next = temp;
3491 OIC_LOG(INFO, TAG, "resource unbound");
3493 // Send notification when resource is unbounded successfully.
3494 #ifdef WITH_PRESENCE
3495 if (presenceResource.handle)
3497 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3498 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3499 OC_PRESENCE_TRIGGER_CHANGE);
3502 tempChildResource = NULL;
3503 tempLastChildResource = NULL;
3509 tempLastChildResource = tempChildResource;
3510 tempChildResource = tempChildResource->next;
3513 OIC_LOG(INFO, TAG, "resource not found in collection");
3515 tempChildResource = NULL;
3516 tempLastChildResource = NULL;
3518 // Unable to add resourceHandle, so return error
3519 return OC_STACK_ERROR;
3522 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3524 if (!resourceItemName)
3528 // Per RFC 6690 only registered values must follow the first rule below.
3529 // At this point in time the only values registered begin with "core", and
3530 // all other values are specified as opaque strings where multiple values
3531 // are separated by a space.
3532 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3534 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3536 if (resourceItemName[index] != '.'
3537 && resourceItemName[index] != '-'
3538 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3539 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3547 for (size_t index = 0; resourceItemName[index]; ++index)
3549 if (resourceItemName[index] == ' '
3550 || resourceItemName[index] == '\t'
3551 || resourceItemName[index] == '\r'
3552 || resourceItemName[index] == '\n')
3562 OCStackResult BindResourceTypeToResource(OCResource* resource,
3563 const char *resourceTypeName)
3565 OCResourceType *pointer = NULL;
3567 OCStackResult result = OC_STACK_ERROR;
3569 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3571 if (!ValidateResourceTypeInterface(resourceTypeName))
3573 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3574 return OC_STACK_INVALID_PARAM;
3577 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3580 result = OC_STACK_NO_MEMORY;
3584 str = OICStrdup(resourceTypeName);
3587 result = OC_STACK_NO_MEMORY;
3590 pointer->resourcetypename = str;
3591 pointer->next = NULL;
3593 insertResourceType(resource, pointer);
3594 result = OC_STACK_OK;
3597 if (result != OC_STACK_OK)
3606 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3607 const char *resourceInterfaceName)
3609 OCResourceInterface *pointer = NULL;
3611 OCStackResult result = OC_STACK_ERROR;
3613 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3615 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3617 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3618 return OC_STACK_INVALID_PARAM;
3621 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3623 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3626 result = OC_STACK_NO_MEMORY;
3630 str = OICStrdup(resourceInterfaceName);
3633 result = OC_STACK_NO_MEMORY;
3636 pointer->name = str;
3638 // Bind the resourceinterface to the resource
3639 insertResourceInterface(resource, pointer);
3641 result = OC_STACK_OK;
3644 if (result != OC_STACK_OK)
3653 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3654 const char *resourceTypeName)
3657 OCStackResult result = OC_STACK_ERROR;
3658 OCResource *resource = NULL;
3660 resource = findResource((OCResource *) handle);
3663 OIC_LOG(ERROR, TAG, "Resource not found");
3664 return OC_STACK_ERROR;
3667 result = BindResourceTypeToResource(resource, resourceTypeName);
3669 #ifdef WITH_PRESENCE
3670 if(presenceResource.handle)
3672 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3673 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3680 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3681 const char *resourceInterfaceName)
3684 OCStackResult result = OC_STACK_ERROR;
3685 OCResource *resource = NULL;
3687 resource = findResource((OCResource *) handle);
3690 OIC_LOG(ERROR, TAG, "Resource not found");
3691 return OC_STACK_ERROR;
3694 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3696 #ifdef WITH_PRESENCE
3697 if (presenceResource.handle)
3699 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3700 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3707 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3709 OCResource *pointer = headResource;
3711 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3715 *numResources = *numResources + 1;
3716 pointer = pointer->next;
3721 OCResourceHandle OCGetResourceHandle(uint8_t index)
3723 OCResource *pointer = headResource;
3725 for( uint8_t i = 0; i < index && pointer; ++i)
3727 pointer = pointer->next;
3729 return (OCResourceHandle) pointer;
3732 OCStackResult OCDeleteResource(OCResourceHandle handle)
3736 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3737 return OC_STACK_INVALID_PARAM;
3740 OCResource *resource = findResource((OCResource *) handle);
3741 if (resource == NULL)
3743 OIC_LOG(ERROR, TAG, "Resource not found");
3744 return OC_STACK_NO_RESOURCE;
3747 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3749 OIC_LOG(ERROR, TAG, "Error deleting resource");
3750 return OC_STACK_ERROR;
3756 const char *OCGetResourceUri(OCResourceHandle handle)
3758 OCResource *resource = NULL;
3760 resource = findResource((OCResource *) handle);
3763 return resource->uri;
3765 return (const char *) NULL;
3768 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3770 OCResource *resource = NULL;
3772 resource = findResource((OCResource *) handle);
3775 return resource->resourceProperties;
3777 return (OCResourceProperty)-1;
3780 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3781 uint8_t *numResourceTypes)
3783 OCResource *resource = NULL;
3784 OCResourceType *pointer = NULL;
3786 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3787 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3789 *numResourceTypes = 0;
3791 resource = findResource((OCResource *) handle);
3794 pointer = resource->rsrcType;
3797 *numResourceTypes = *numResourceTypes + 1;
3798 pointer = pointer->next;
3804 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3806 OCResourceType *resourceType = NULL;
3808 resourceType = findResourceTypeAtIndex(handle, index);
3811 return resourceType->resourcetypename;
3813 return (const char *) NULL;
3816 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3817 uint8_t *numResourceInterfaces)
3819 OCResourceInterface *pointer = NULL;
3820 OCResource *resource = NULL;
3822 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3823 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3825 *numResourceInterfaces = 0;
3826 resource = findResource((OCResource *) handle);
3829 pointer = resource->rsrcInterface;
3832 *numResourceInterfaces = *numResourceInterfaces + 1;
3833 pointer = pointer->next;
3839 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3841 OCResourceInterface *resourceInterface = NULL;
3843 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3844 if (resourceInterface)
3846 return resourceInterface->name;
3848 return (const char *) NULL;
3851 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3854 OCResource *resource = NULL;
3855 OCChildResource *tempChildResource = NULL;
3858 resource = findResource((OCResource *) collectionHandle);
3864 tempChildResource = resource->rsrcChildResourcesHead;
3866 while(tempChildResource)
3870 return tempChildResource->rsrcResource;
3873 tempChildResource = tempChildResource->next;
3876 // In this case, the number of resource handles in the collection exceeds the index
3877 tempChildResource = NULL;
3881 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3882 OCEntityHandler entityHandler,
3883 void* callbackParam)
3885 OCResource *resource = NULL;
3887 // Validate parameters
3888 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3890 // Use the handle to find the resource in the resource linked list
3891 resource = findResource((OCResource *)handle);
3894 OIC_LOG(ERROR, TAG, "Resource not found");
3895 return OC_STACK_ERROR;
3899 resource->entityHandler = entityHandler;
3900 resource->entityHandlerCallbackParam = callbackParam;
3902 #ifdef WITH_PRESENCE
3903 if (presenceResource.handle)
3905 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3906 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3913 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3915 OCResource *resource = NULL;
3917 resource = findResource((OCResource *)handle);
3920 OIC_LOG(ERROR, TAG, "Resource not found");
3925 return resource->entityHandler;
3928 void incrementSequenceNumber(OCResource * resPtr)
3930 // Increment the sequence number
3931 resPtr->sequenceNum += 1;
3932 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3934 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3939 #ifdef WITH_PRESENCE
3940 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3941 OCPresenceTrigger trigger)
3943 OCResource *resPtr = NULL;
3944 OCStackResult result = OC_STACK_ERROR;
3945 OCMethod method = OC_REST_PRESENCE;
3946 uint32_t maxAge = 0;
3947 resPtr = findResource((OCResource *) presenceResource.handle);
3950 return OC_STACK_NO_RESOURCE;
3953 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3955 maxAge = presenceResource.presenceTTL;
3957 result = SendAllObserverNotification(method, resPtr, maxAge,
3958 trigger, resourceType, OC_LOW_QOS);
3964 OCStackResult SendStopNotification()
3966 OCResource *resPtr = NULL;
3967 OCStackResult result = OC_STACK_ERROR;
3968 OCMethod method = OC_REST_PRESENCE;
3969 resPtr = findResource((OCResource *) presenceResource.handle);
3972 return OC_STACK_NO_RESOURCE;
3975 // maxAge is 0. ResourceType is NULL.
3976 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3982 #endif // WITH_PRESENCE
3983 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3985 OCResource *resPtr = NULL;
3986 OCStackResult result = OC_STACK_ERROR;
3987 OCMethod method = OC_REST_NOMETHOD;
3988 uint32_t maxAge = 0;
3990 OIC_LOG(INFO, TAG, "Notifying all observers");
3991 #ifdef WITH_PRESENCE
3992 if(handle == presenceResource.handle)
3996 #endif // WITH_PRESENCE
3997 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3999 // Verify that the resource exists
4000 resPtr = findResource ((OCResource *) handle);
4003 return OC_STACK_NO_RESOURCE;
4007 //only increment in the case of regular observing (not presence)
4008 incrementSequenceNumber(resPtr);
4009 method = OC_REST_OBSERVE;
4010 maxAge = MAX_OBSERVE_AGE;
4011 #ifdef WITH_PRESENCE
4012 result = SendAllObserverNotification (method, resPtr, maxAge,
4013 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4015 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4022 OCNotifyListOfObservers (OCResourceHandle handle,
4023 OCObservationId *obsIdList,
4024 uint8_t numberOfIds,
4025 const OCRepPayload *payload,
4026 OCQualityOfService qos)
4028 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4030 OCResource *resPtr = NULL;
4031 //TODO: we should allow the server to define this
4032 uint32_t maxAge = MAX_OBSERVE_AGE;
4034 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4035 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4036 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4038 resPtr = findResource ((OCResource *) handle);
4039 if (NULL == resPtr || myStackMode == OC_CLIENT)
4041 return OC_STACK_NO_RESOURCE;
4045 incrementSequenceNumber(resPtr);
4047 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4048 payload, maxAge, qos));
4051 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4053 OCStackResult result = OC_STACK_ERROR;
4054 OCServerRequest *serverRequest = NULL;
4056 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4058 // Validate input parameters
4059 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4060 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4063 // Get pointer to request info
4064 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4067 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4068 result = serverRequest->ehResponseHandler(ehResponse);
4074 //#ifdef DIRECT_PAIRING
4075 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4077 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4078 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4080 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4084 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4087 const OCDPDev_t* OCGetDirectPairedDevices()
4089 return (const OCDPDev_t*)DPGetPairedDevices();
4092 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4093 OCDirectPairingCB resultCallback)
4095 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4096 if(NULL == peer || NULL == pinNumber)
4098 OIC_LOG(ERROR, TAG, "Invalid parameters");
4099 return OC_STACK_INVALID_PARAM;
4101 if (NULL == resultCallback)
4103 OIC_LOG(ERROR, TAG, "Invalid callback");
4104 return OC_STACK_INVALID_CALLBACK;
4107 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4108 pinNumber, (OCDirectPairingResultCB)resultCallback);
4110 //#endif // DIRECT_PAIRING
4112 //-----------------------------------------------------------------------------
4113 // Private internal function definitions
4114 //-----------------------------------------------------------------------------
4115 static OCDoHandle GenerateInvocationHandle()
4117 OCDoHandle handle = NULL;
4118 // Generate token here, it will be deleted when the transaction is deleted
4119 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4122 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4128 #ifdef WITH_PRESENCE
4129 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4130 OCResourceProperty resourceProperties, uint8_t enable)
4134 return OC_STACK_INVALID_PARAM;
4136 if (resourceProperties
4137 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4139 OIC_LOG(ERROR, TAG, "Invalid property");
4140 return OC_STACK_INVALID_PARAM;
4144 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4148 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4154 OCStackResult initResources()
4156 OCStackResult result = OC_STACK_OK;
4158 headResource = NULL;
4159 tailResource = NULL;
4160 // Init Virtual Resources
4161 #ifdef WITH_PRESENCE
4162 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4164 result = OCCreateResource(&presenceResource.handle,
4165 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4167 OC_RSRVD_PRESENCE_URI,
4171 //make resource inactive
4172 result = OCChangeResourceProperty(
4173 &(((OCResource *) presenceResource.handle)->resourceProperties),
4176 #ifndef WITH_ARDUINO
4177 if (result == OC_STACK_OK)
4179 result = SRMInitSecureResources();
4183 if(result == OC_STACK_OK)
4185 CreateResetProfile();
4186 result = OCCreateResource(&deviceResource,
4187 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4188 OC_RSRVD_INTERFACE_DEFAULT,
4189 OC_RSRVD_DEVICE_URI,
4193 if(result == OC_STACK_OK)
4195 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4196 OC_RSRVD_INTERFACE_READ);
4200 if(result == OC_STACK_OK)
4202 result = OCCreateResource(&platformResource,
4203 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4204 OC_RSRVD_INTERFACE_DEFAULT,
4205 OC_RSRVD_PLATFORM_URI,
4209 if(result == OC_STACK_OK)
4211 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4212 OC_RSRVD_INTERFACE_READ);
4219 void insertResource(OCResource *resource)
4223 headResource = resource;
4224 tailResource = resource;
4228 tailResource->next = resource;
4229 tailResource = resource;
4231 resource->next = NULL;
4234 OCResource *findResource(OCResource *resource)
4236 OCResource *pointer = headResource;
4240 if (pointer == resource)
4244 pointer = pointer->next;
4249 void deleteAllResources()
4251 OCResource *pointer = headResource;
4252 OCResource *temp = NULL;
4256 temp = pointer->next;
4257 #ifdef WITH_PRESENCE
4258 if (pointer != (OCResource *) presenceResource.handle)
4260 #endif // WITH_PRESENCE
4261 deleteResource(pointer);
4262 #ifdef WITH_PRESENCE
4264 #endif // WITH_PRESENCE
4267 memset(&platformResource, 0, sizeof(platformResource));
4268 memset(&deviceResource, 0, sizeof(deviceResource));
4270 memset(&brokerResource, 0, sizeof(brokerResource));
4273 SRMDeInitSecureResources();
4275 #ifdef WITH_PRESENCE
4276 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4277 // presence notification attributed to their deletion to be processed.
4278 deleteResource((OCResource *) presenceResource.handle);
4279 memset(&presenceResource, 0, sizeof(presenceResource));
4280 #endif // WITH_PRESENCE
4283 OCStackResult deleteResource(OCResource *resource)
4285 OCResource *prev = NULL;
4286 OCResource *temp = NULL;
4289 OIC_LOG(DEBUG,TAG,"resource is NULL");
4290 return OC_STACK_INVALID_PARAM;
4293 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4295 temp = headResource;
4298 if (temp == resource)
4300 // Invalidate all Resource Properties.
4301 resource->resourceProperties = (OCResourceProperty) 0;
4302 #ifdef WITH_PRESENCE
4303 if(resource != (OCResource *) presenceResource.handle)
4305 #endif // WITH_PRESENCE
4306 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4307 #ifdef WITH_PRESENCE
4310 if(presenceResource.handle)
4312 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4313 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4316 // Only resource in list.
4317 if (temp == headResource && temp == tailResource)
4319 headResource = NULL;
4320 tailResource = NULL;
4323 else if (temp == headResource)
4325 headResource = temp->next;
4328 else if (temp == tailResource)
4330 tailResource = prev;
4331 tailResource->next = NULL;
4335 prev->next = temp->next;
4338 deleteResourceElements(temp);
4349 return OC_STACK_ERROR;
4352 void deleteResourceElements(OCResource *resource)
4359 OICFree(resource->uri);
4360 deleteResourceType(resource->rsrcType);
4361 deleteResourceInterface(resource->rsrcInterface);
4364 void deleteResourceType(OCResourceType *resourceType)
4366 OCResourceType *pointer = resourceType;
4367 OCResourceType *next = NULL;
4371 next = pointer->next;
4372 OICFree(pointer->resourcetypename);
4378 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4380 OCResourceInterface *pointer = resourceInterface;
4381 OCResourceInterface *next = NULL;
4385 next = pointer->next;
4386 OICFree(pointer->name);
4392 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4394 OCResourceType *pointer = NULL;
4395 OCResourceType *previous = NULL;
4396 if (!resource || !resourceType)
4400 // resource type list is empty.
4401 else if (!resource->rsrcType)
4403 resource->rsrcType = resourceType;
4407 pointer = resource->rsrcType;
4411 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4413 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4414 OICFree(resourceType->resourcetypename);
4415 OICFree(resourceType);
4419 pointer = pointer->next;
4424 previous->next = resourceType;
4427 resourceType->next = NULL;
4429 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4432 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4434 OCResource *resource = NULL;
4435 OCResourceType *pointer = NULL;
4437 // Find the specified resource
4438 resource = findResource((OCResource *) handle);
4444 // Make sure a resource has a resourcetype
4445 if (!resource->rsrcType)
4450 // Iterate through the list
4451 pointer = resource->rsrcType;
4452 for(uint8_t i = 0; i< index && pointer; ++i)
4454 pointer = pointer->next;
4459 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4461 if(resourceTypeList && resourceTypeName)
4463 OCResourceType * rtPointer = resourceTypeList;
4464 while(resourceTypeName && rtPointer)
4466 if(rtPointer->resourcetypename &&
4467 strcmp(resourceTypeName, (const char *)
4468 (rtPointer->resourcetypename)) == 0)
4472 rtPointer = rtPointer->next;
4480 * Insert a new interface into interface linked list only if not already present.
4481 * If alredy present, 2nd arg is free'd.
4482 * Default interface will always be first if present.
4484 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4486 OCResourceInterface *pointer = NULL;
4487 OCResourceInterface *previous = NULL;
4489 newInterface->next = NULL;
4491 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4493 if (!*firstInterface)
4495 // If first interface is not oic.if.baseline, by default add it as first interface type.
4496 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4498 *firstInterface = newInterface;
4502 OCStackResult result = BindResourceInterfaceToResource(resource,
4503 OC_RSRVD_INTERFACE_DEFAULT);
4504 if (result != OC_STACK_OK)
4506 OICFree(newInterface->name);
4507 OICFree(newInterface);
4510 if (*firstInterface)
4512 (*firstInterface)->next = newInterface;
4516 // If once add oic.if.baseline, later too below code take care of freeing memory.
4517 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4519 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4521 OICFree(newInterface->name);
4522 OICFree(newInterface);
4525 // This code will not hit anymore, keeping
4528 newInterface->next = *firstInterface;
4529 *firstInterface = newInterface;
4534 pointer = *firstInterface;
4537 if (strcmp(newInterface->name, pointer->name) == 0)
4539 OICFree(newInterface->name);
4540 OICFree(newInterface);
4544 pointer = pointer->next;
4549 previous->next = newInterface;
4554 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4557 OCResource *resource = NULL;
4558 OCResourceInterface *pointer = NULL;
4560 // Find the specified resource
4561 resource = findResource((OCResource *) handle);
4567 // Make sure a resource has a resourceinterface
4568 if (!resource->rsrcInterface)
4573 // Iterate through the list
4574 pointer = resource->rsrcInterface;
4576 for (uint8_t i = 0; i < index && pointer; ++i)
4578 pointer = pointer->next;
4584 * This function splits the uri using the '?' delimiter.
4585 * "uriWithoutQuery" is the block of characters between the beginning
4586 * till the delimiter or '\0' which ever comes first.
4587 * "query" is whatever is to the right of the delimiter if present.
4588 * No delimiter sets the query to NULL.
4589 * If either are present, they will be malloc'ed into the params 2, 3.
4590 * The first param, *uri is left untouched.
4592 * NOTE: This function does not account for whitespace at the end of the uri NOR
4593 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4594 * part of the query.
4596 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4600 return OC_STACK_INVALID_URI;
4602 if(!query || !uriWithoutQuery)
4604 return OC_STACK_INVALID_PARAM;
4608 *uriWithoutQuery = NULL;
4610 size_t uriWithoutQueryLen = 0;
4611 size_t queryLen = 0;
4612 size_t uriLen = strlen(uri);
4614 char *pointerToDelimiter = strstr(uri, "?");
4616 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4617 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4619 if (uriWithoutQueryLen)
4621 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4622 if (!*uriWithoutQuery)
4626 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4630 *query = (char *) OICCalloc(queryLen + 1, 1);
4633 OICFree(*uriWithoutQuery);
4634 *uriWithoutQuery = NULL;
4637 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4643 return OC_STACK_NO_MEMORY;
4646 static const OicUuid_t* OCGetServerInstanceID(void)
4648 static bool generated = false;
4649 static OicUuid_t sid;
4655 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4657 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4664 const char* OCGetServerInstanceIDString(void)
4666 static bool generated = false;
4667 static char sidStr[UUID_STRING_SIZE];
4674 const OicUuid_t *sid = OCGetServerInstanceID();
4675 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4677 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4685 CAResult_t OCSelectNetwork()
4687 CAResult_t retResult = CA_STATUS_FAILED;
4688 CAResult_t caResult = CA_STATUS_OK;
4690 CATransportAdapter_t connTypes[] = {
4692 CA_ADAPTER_RFCOMM_BTEDR,
4693 CA_ADAPTER_GATT_BTLE,
4696 ,CA_ADAPTER_REMOTE_ACCESS
4703 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4705 for(int i = 0; i<numConnTypes; i++)
4707 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4708 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4710 caResult = CASelectNetwork(connTypes[i]);
4711 if(caResult == CA_STATUS_OK)
4713 retResult = CA_STATUS_OK;
4718 if(retResult != CA_STATUS_OK)
4720 return caResult; // Returns error of appropriate transport that failed fatally.
4726 OCStackResult CAResultToOCResult(CAResult_t caResult)
4732 case CA_STATUS_INVALID_PARAM:
4733 return OC_STACK_INVALID_PARAM;
4734 case CA_ADAPTER_NOT_ENABLED:
4735 return OC_STACK_ADAPTER_NOT_ENABLED;
4736 case CA_SERVER_STARTED_ALREADY:
4738 case CA_SERVER_NOT_STARTED:
4739 return OC_STACK_ERROR;
4740 case CA_DESTINATION_NOT_REACHABLE:
4741 return OC_STACK_COMM_ERROR;
4742 case CA_SOCKET_OPERATION_FAILED:
4743 return OC_STACK_COMM_ERROR;
4744 case CA_SEND_FAILED:
4745 return OC_STACK_COMM_ERROR;
4746 case CA_RECEIVE_FAILED:
4747 return OC_STACK_COMM_ERROR;
4748 case CA_MEMORY_ALLOC_FAILED:
4749 return OC_STACK_NO_MEMORY;
4750 case CA_REQUEST_TIMEOUT:
4751 return OC_STACK_TIMEOUT;
4752 case CA_DESTINATION_DISCONNECTED:
4753 return OC_STACK_COMM_ERROR;
4754 case CA_STATUS_FAILED:
4755 return OC_STACK_ERROR;
4756 case CA_NOT_SUPPORTED:
4757 return OC_STACK_NOTIMPL;
4759 return OC_STACK_ERROR;
4763 bool OCResultToSuccess(OCStackResult ocResult)
4768 case OC_STACK_RESOURCE_CREATED:
4769 case OC_STACK_RESOURCE_DELETED:
4770 case OC_STACK_CONTINUE:
4771 case OC_STACK_RESOURCE_CHANGED:
4772 case OC_STACK_SLOW_RESOURCE:
4779 #if defined(RD_CLIENT) || defined(RD_SERVER)
4780 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
4782 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4784 OCResource *resource = NULL;
4786 resource = findResource((OCResource *) handle);
4789 OIC_LOG(ERROR, TAG, "Resource not found");
4790 return OC_STACK_ERROR;
4793 resource->ins = ins;
4798 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
4802 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
4806 OCResource *pointer = headResource;
4810 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
4812 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
4815 pointer = pointer->next;
4820 OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
4822 OCResource *resource = NULL;
4824 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4825 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
4827 resource = findResource((OCResource *) handle);
4830 *ins = resource->ins;
4833 return OC_STACK_ERROR;