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
39 #include "iotivity_config.h"
45 #include "ocstackinternal.h"
46 #include "ocresourcehandler.h"
47 #include "occlientcb.h"
48 #include "ocobserve.h"
50 #include "oic_malloc.h"
51 #include "oic_string.h"
54 #include "ocserverrequest.h"
55 #include "secureresourcemanager.h"
56 #include "psinterface.h"
58 #include "doxmresource.h"
60 #include "cainterface.h"
61 #include "ocpayload.h"
62 #include "ocpayloadcbor.h"
63 #include "cautilinterface.h"
64 #include "camessagehandler.h"
66 #include "pstatresource.h"
68 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
69 #include "routingutility.h"
70 #ifdef ROUTING_GATEWAY
71 #include "routingmanager.h"
76 #include "oickeepaliveinternal.h"
79 //#ifdef DIRECT_PAIRING
80 #include "directpairing.h"
83 #ifdef HAVE_ARDUINO_TIME_H
86 #ifdef HAVE_SYS_TIME_H
89 #include <coap/coap.h>
91 #ifdef HAVE_ARPA_INET_H
92 #include <arpa/inet.h>
96 #define UINT32_MAX (0xFFFFFFFFUL)
99 //-----------------------------------------------------------------------------
101 //-----------------------------------------------------------------------------
104 OC_STACK_UNINITIALIZED = 0,
105 OC_STACK_INITIALIZED,
106 OC_STACK_UNINIT_IN_PROGRESS
112 OC_PRESENCE_UNINITIALIZED = 0,
113 OC_PRESENCE_INITIALIZED
117 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
120 OCOtmEventHandler cb;
122 } OCOtmEventHandler_t;
125 //-----------------------------------------------------------------------------
127 //-----------------------------------------------------------------------------
128 static OCStackState stackState = OC_STACK_UNINITIALIZED;
130 OCResource *headResource = NULL;
131 static OCResource *tailResource = NULL;
132 static OCResourceHandle platformResource = {0};
133 static OCResourceHandle deviceResource = {0};
135 static OCResourceHandle brokerResource = {0};
139 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
140 static PresenceResource presenceResource = {0};
141 static uint8_t PresenceTimeOutSize = 0;
142 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
145 static OCMode myStackMode;
147 //TODO: revisit this design
148 static bool gRASetInfo = false;
150 OCDeviceEntityHandler defaultDeviceHandler;
151 void* defaultDeviceHandlerCallbackParameter = NULL;
152 static const char COAP_TCP_SCHEME[] = "coap+tcp:";
153 static const char COAPS_TCP_SCHEME[] = "coaps+tcp:";
154 static const char CORESPEC[] = "core";
156 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
157 static OCOtmEventHandler_t g_otmEventHandler = {NULL, NULL};
160 #ifdef WITH_PROCESS_EVENT
161 static oc_event g_ocProcessEvent = NULL;
162 #endif // WITH_PROCESS_EVENT
164 //-----------------------------------------------------------------------------
166 //-----------------------------------------------------------------------------
167 #define TAG "OIC_RI_STACK"
168 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
169 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
170 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
171 TAG, #arg " is NULL"); return (retVal); } }
172 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
173 TAG, #arg " is NULL"); return; } }
174 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
177 //TODO: we should allow the server to define this
178 #define MAX_OBSERVE_AGE (0x2FFFFUL)
180 #define MILLISECONDS_PER_SECOND (1000)
182 //-----------------------------------------------------------------------------
183 // Private internal function prototypes
184 //-----------------------------------------------------------------------------
187 * Generate handle of OCDoResource invocation for callback management.
189 * @return Generated OCDoResource handle.
191 static OCDoHandle GenerateInvocationHandle();
194 * Initialize resource data structures, variables, etc.
196 * @return ::OC_STACK_OK on success, some other value upon failure.
198 static OCStackResult initResources();
201 * Add a resource to the end of the linked list of resources.
203 * @param resource Resource to be added
205 static void insertResource(OCResource *resource);
208 * Find a resource in the linked list of resources.
210 * @param resource Resource to be found.
211 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
214 static OCResource *findResource(OCResource *resource);
217 * Insert a resource type into a resource's resource type linked list.
218 * If resource type already exists, it will not be inserted and the
219 * resourceType will be free'd.
220 * resourceType->next should be null to avoid memory leaks.
221 * Function returns silently for null args.
223 * @param resource Resource where resource type is to be inserted.
224 * @param resourceType Resource type to be inserted.
226 static void insertResourceType(OCResource *resource,
227 OCResourceType *resourceType);
230 * Get a resource type at the specified index within a resource.
232 * @param handle Handle of resource.
233 * @param index Index of resource type.
235 * @return Pointer to resource type if found, NULL otherwise.
237 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
241 * Insert a resource interface into a resource's resource interface linked list.
242 * If resource interface already exists, it will not be inserted and the
243 * resourceInterface will be free'd.
244 * resourceInterface->next should be null to avoid memory leaks.
246 * @param resource Resource where resource interface is to be inserted.
247 * @param resourceInterface Resource interface to be inserted.
249 static void insertResourceInterface(OCResource *resource,
250 OCResourceInterface *resourceInterface);
253 * Get a resource interface at the specified index within a resource.
255 * @param handle Handle of resource.
256 * @param index Index of resource interface.
258 * @return Pointer to resource interface if found, NULL otherwise.
260 static OCResourceInterface *findResourceInterfaceAtIndex(
261 OCResourceHandle handle, uint8_t index);
264 * Delete all of the dynamically allocated elements that were created for the resource type.
266 * @param resourceType Specified resource type.
268 static void deleteResourceType(OCResourceType *resourceType);
271 * Delete all of the dynamically allocated elements that were created for the resource interface.
273 * @param resourceInterface Specified resource interface.
275 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
278 * Unbind all child resources.
280 * @param resourceChild Specified binded resource head is deleted from parent.
282 static void unbindChildResources(OCChildResource *resourceChild);
285 * Delete all of the dynamically allocated elements that were created for the resource.
287 * @param resource Specified resource.
289 static void deleteResourceElements(OCResource *resource);
292 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
295 * @param handle Handle of resource to be deleted.
297 * @return ::OC_STACK_OK on success, some other value upon failure.
299 static OCStackResult deleteResource(OCResource *resource);
302 * Delete all of the resources in the resource list.
304 static void deleteAllResources();
307 * Increment resource sequence number. Handles rollover.
309 * @param resPtr Pointer to resource.
311 static void incrementSequenceNumber(OCResource * resPtr);
314 * Attempts to initialize every network interface that the CA Layer might have compiled in.
316 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
317 * return something other than @ref CA_STATUS_OK, then this function fails.
318 * @param transportType OCTransportAdapter value to select.
319 * @return ::CA_STATUS_OK on success, some other value upon failure.
321 static CAResult_t OCSelectNetwork(OCTransportAdapter transportType);
324 * Convert CAResponseResult_t to OCStackResult.
326 * @param caCode CAResponseResult_t code.
327 * @return ::OC_STACK_OK on success, some other value upon failure.
329 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
332 * Convert OCTransportFlags_t to CATransportModifiers_t.
334 * @param ocConType OCTransportFlags_t input.
335 * @return CATransportFlags
337 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
340 * Convert CATransportFlags_t to OCTransportModifiers_t.
342 * @param caConType CATransportFlags_t input.
343 * @return OCTransportFlags
345 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
348 * Handle response from presence request.
350 * @param endPoint CA remote endpoint.
351 * @param responseInfo CA response info.
352 * @return ::OC_STACK_OK on success, some other value upon failure.
354 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
355 const CAResponseInfo_t *responseInfo);
358 * This function will be called back by CA layer when a response is received.
360 * @param endPoint CA remote endpoint.
361 * @param responseInfo CA response info.
363 static void HandleCAResponses(const CAEndpoint_t* endPoint,
364 const CAResponseInfo_t* responseInfo);
367 * This function will be called back by CA layer when a request is received.
369 * @param endPoint CA remote endpoint.
370 * @param requestInfo CA request info.
372 static void HandleCARequests(const CAEndpoint_t* endPoint,
373 const CARequestInfo_t* requestInfo);
376 * Extract query from a URI.
378 * @param uri Full URI with query.
379 * @param query Pointer to string that will contain query.
380 * @param newURI Pointer to string that will contain URI.
381 * @return ::OC_STACK_OK on success, some other value upon failure.
383 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
386 * Finds a resource type in an OCResourceType link-list.
388 * @param resourceTypeList The link-list to be searched through.
389 * @param resourceTypeName The key to search for.
391 * @return Resource type that matches the key (ie. resourceTypeName) or
392 * NULL if there is either an invalid parameter or this function was unable to find the key.
394 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
395 const char * resourceTypeName);
399 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
400 * TTL will be set to maxAge.
402 * @param cbNode Callback Node for which presence ttl is to be reset.
403 * @param maxAge New value of ttl in seconds.
405 * @return ::OC_STACK_OK on success, some other value upon failure.
407 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
411 * Ensure the accept header option is set appropriatly before sending the requests and routing
412 * header option is updated with destination.
414 * @param object CA remote endpoint.
415 * @param requestInfo CA request info.
417 * @return ::OC_STACK_OK on success, some other value upon failure.
419 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
422 * default adapter state change callback method
424 * @param adapter CA network adapter type.
425 * @param enabled current adapter state.
427 static void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled);
430 * default connection state change callback method
432 * @param info CAEndpoint which has address, port and etc.
433 * @param isConnected current connection state.
435 static void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected);
437 //-----------------------------------------------------------------------------
438 // Internal functions
439 //-----------------------------------------------------------------------------
441 bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
443 if (!options || 0 == numOptions)
445 OIC_LOG (INFO, TAG, "No options present");
449 for (uint8_t i = 0; i < numOptions; i++)
451 if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
453 OIC_LOG(DEBUG, TAG, "Proxy URI is present");
460 uint32_t GetTicks(uint32_t milliSeconds)
465 // Guard against overflow of uint32_t
466 if (milliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
467 COAP_TICKS_PER_SECOND)
469 return now + (milliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
477 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
479 VERIFY_NON_NULL_NR(in, FATAL);
480 VERIFY_NON_NULL_NR(out, FATAL);
482 out->adapter = (OCTransportAdapter)in->adapter;
483 out->flags = CAToOCTransportFlags(in->flags);
484 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
485 out->port = in->port;
486 out->ifindex = in->ifindex;
487 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
488 /* This assert is to prevent accidental mismatch between address size macros defined in
489 * RI and CA and cause crash here. */
490 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
491 "Address size mismatch between RI and CA");
492 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
496 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
498 VERIFY_NON_NULL_NR(in, FATAL);
499 VERIFY_NON_NULL_NR(out, FATAL);
501 out->adapter = (CATransportAdapter_t)in->adapter;
502 out->flags = OCToCATransportFlags(in->flags);
503 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
504 OICStrcpy(out->remoteId, sizeof(out->remoteId), in->remoteId);
505 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
506 /* This assert is to prevent accidental mismatch between address size macros defined in
507 * RI and CA and cause crash here. */
508 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
509 "Address size mismatch between RI and CA");
510 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
512 out->port = in->port;
513 out->ifindex = in->ifindex;
516 void FixUpClientResponse(OCClientResponse *cr)
518 VERIFY_NON_NULL_NR(cr, FATAL);
520 cr->addr = &cr->devAddr;
521 cr->connType = (OCConnectivityType)
522 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
525 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
527 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
528 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
529 OIC_TRACE_BEGIN(%s:OCSendRequest, TAG);
531 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
532 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
533 if (OC_STACK_OK != rmResult)
535 OIC_LOG(ERROR, TAG, "Add destination option failed");
541 // OC stack prefer CBOR encoded payloads.
542 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
543 CAResult_t result = CASendRequest(object, requestInfo);
544 if(CA_STATUS_OK != result)
546 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
548 return CAResultToOCResult(result);
554 //-----------------------------------------------------------------------------
555 // Internal API function
556 //-----------------------------------------------------------------------------
558 // This internal function is called to update the stack with the status of
559 // observers and communication failures
560 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
562 OCStackResult result = OC_STACK_ERROR;
563 ResourceObserver * observer = NULL;
564 OCEntityHandlerRequest ehRequest = {0};
568 case OC_OBSERVER_NOT_INTERESTED:
569 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
570 observer = GetObserverUsingToken(token, tokenLength);
573 result = FormOCEntityHandlerRequest(&ehRequest,
577 (OCResourceHandle)NULL,
578 NULL, PAYLOAD_TYPE_REPRESENTATION,
580 OC_OBSERVE_DEREGISTER,
583 if (result != OC_STACK_OK)
585 FreeObserver(observer);
589 if (observer->resource && observer->resource->entityHandler)
591 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
592 observer->resource->entityHandlerCallbackParam);
595 FreeObserver(observer);
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");
610 case OC_OBSERVER_STILL_INTERESTED:
611 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
612 observer = GetObserverUsingToken(token, tokenLength);
615 observer->forceHighQos = 0;
616 observer->failedCommCount = 0;
617 result = OC_STACK_OK;
618 FreeObserver(observer);
622 result = OC_STACK_OBSERVER_NOT_FOUND;
626 case OC_OBSERVER_FAILED_COMM:
627 OIC_LOG(DEBUG, TAG, "observer is unreachable");
628 observer = GetObserverUsingToken (token, tokenLength);
631 if (observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
633 result = FormOCEntityHandlerRequest(&ehRequest,
637 (OCResourceHandle)NULL,
638 NULL, PAYLOAD_TYPE_REPRESENTATION,
640 OC_OBSERVE_DEREGISTER,
643 if (result != OC_STACK_OK)
645 FreeObserver(observer);
646 return OC_STACK_ERROR;
649 if (observer->resource && observer->resource->entityHandler)
651 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
652 observer->resource->entityHandlerCallbackParam);
655 result = DeleteObserverUsingToken(token, tokenLength);
656 if (result == OC_STACK_OK)
658 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
662 result = OC_STACK_OK;
663 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
668 observer->failedCommCount++;
669 observer->forceHighQos = 1;
670 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",
671 observer->failedCommCount);
672 result = OC_STACK_CONTINUE;
675 FreeObserver(observer);
679 OIC_LOG(ERROR, TAG, "Unknown status");
680 result = OC_STACK_ERROR;
686 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
688 OCStackResult ret = OC_STACK_ERROR;
692 ret = OC_STACK_RESOURCE_CREATED;
695 ret = OC_STACK_RESOURCE_DELETED;
698 ret = OC_STACK_RESOURCE_CHANGED;
705 ret = OC_STACK_INVALID_QUERY;
707 case CA_UNAUTHORIZED_REQ:
708 ret = OC_STACK_UNAUTHORIZED_REQ;
711 ret = OC_STACK_INVALID_OPTION;
714 ret = OC_STACK_NO_RESOURCE;
716 case CA_REQUEST_ENTITY_TOO_LARGE:
717 ret = OC_STACK_TOO_LARGE_REQ;
719 case CA_METHOD_NOT_ALLOWED:
720 ret = OC_STACK_METHOD_NOT_ALLOWED;
722 case CA_NOT_ACCEPTABLE:
723 ret = OC_STACK_NOT_ACCEPTABLE;
725 case CA_FORBIDDEN_REQ:
726 ret = OC_STACK_FORBIDDEN_REQ;
728 case CA_TOO_MANY_REQUESTS:
729 ret = OC_STACK_TOO_MANY_REQUESTS;
731 case CA_INTERNAL_SERVER_ERROR:
732 ret = OC_STACK_INTERNAL_SERVER_ERROR;
734 case CA_NOT_IMPLEMENTED:
735 ret = OC_STACK_NOT_IMPLEMENTED;
738 ret = OC_STACK_BAD_GATEWAY;
740 case CA_SERVICE_UNAVAILABLE:
741 ret = OC_STACK_SERVICE_UNAVAILABLE;
743 case CA_RETRANSMIT_TIMEOUT:
744 ret = OC_STACK_GATEWAY_TIMEOUT;
746 case CA_PROXY_NOT_SUPPORTED:
747 ret = OC_STACK_PROXY_NOT_SUPPORTED;
755 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
757 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
766 // This Response Code is like HTTP 204 "No Content" but only used in
767 // response to POST and PUT requests.
771 // This Response Code is like HTTP 200 "OK" but only used in response to
776 // This should not happen but,
777 // give it a value just in case but output an error
779 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
783 case OC_STACK_RESOURCE_CREATED:
786 case OC_STACK_RESOURCE_DELETED:
789 case OC_STACK_RESOURCE_CHANGED:
792 case OC_STACK_INVALID_QUERY:
795 case OC_STACK_INVALID_OPTION:
798 case OC_STACK_NO_RESOURCE:
801 case OC_STACK_COMM_ERROR:
802 ret = CA_RETRANSMIT_TIMEOUT;
804 case OC_STACK_METHOD_NOT_ALLOWED:
805 ret = CA_METHOD_NOT_ALLOWED;
807 case OC_STACK_NOT_ACCEPTABLE:
808 ret = CA_NOT_ACCEPTABLE;
810 case OC_STACK_UNAUTHORIZED_REQ:
811 ret = CA_UNAUTHORIZED_REQ;
813 case OC_STACK_FORBIDDEN_REQ:
814 ret = CA_FORBIDDEN_REQ;
816 case OC_STACK_TOO_MANY_REQUESTS:
817 ret = CA_TOO_MANY_REQUESTS;
819 case OC_STACK_INTERNAL_SERVER_ERROR:
820 ret = CA_INTERNAL_SERVER_ERROR;
822 case OC_STACK_NOT_IMPLEMENTED:
823 ret = CA_NOT_IMPLEMENTED;
825 case OC_STACK_BAD_GATEWAY:
826 ret = CA_BAD_GATEWAY;
828 case OC_STACK_SERVICE_UNAVAILABLE:
829 ret = CA_SERVICE_UNAVAILABLE;
831 case OC_STACK_GATEWAY_TIMEOUT:
832 ret = CA_RETRANSMIT_TIMEOUT;
834 case OC_STACK_PROXY_NOT_SUPPORTED:
835 ret = CA_PROXY_NOT_SUPPORTED;
843 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
845 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
847 // supply default behavior.
848 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
850 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
852 if ((caFlags & OC_MASK_SCOPE) == 0)
854 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
859 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
861 return (OCTransportFlags)caFlags;
865 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
867 uint32_t lowerBound = 0;
868 uint32_t higherBound = 0;
870 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
872 return OC_STACK_INVALID_PARAM;
875 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
877 cbNode->presence->TTL = maxAgeSeconds;
879 for (int index = 0; index < PresenceTimeOutSize; index++)
881 // Guard against overflow
882 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
885 lowerBound = GetTicks((PresenceTimeOut[index] *
886 cbNode->presence->TTL *
887 MILLISECONDS_PER_SECOND)/100);
891 lowerBound = GetTicks(UINT32_MAX);
894 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
897 higherBound = GetTicks((PresenceTimeOut[index + 1] *
898 cbNode->presence->TTL *
899 MILLISECONDS_PER_SECOND)/100);
903 higherBound = GetTicks(UINT32_MAX);
906 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
908 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
909 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
910 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
913 cbNode->presence->TTLlevel = 0;
915 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
919 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
921 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
923 return OC_RSRVD_TRIGGER_CREATE;
925 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
927 return OC_RSRVD_TRIGGER_CHANGE;
931 return OC_RSRVD_TRIGGER_DELETE;
935 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
939 return OC_PRESENCE_TRIGGER_CREATE;
941 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
943 return OC_PRESENCE_TRIGGER_CREATE;
945 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
947 return OC_PRESENCE_TRIGGER_CHANGE;
951 return OC_PRESENCE_TRIGGER_DELETE;
954 #endif // WITH_PRESENCE
956 OCStackResult OCEncodeAddressForRFC6874(char *outputAddress,
958 const char *inputAddress)
960 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
961 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
963 size_t inputLength = strnlen(inputAddress, outputSize);
965 // inputSize includes the null terminator
966 size_t inputSize = inputLength + 1;
968 if (inputSize > outputSize)
970 OIC_LOG_V(ERROR, TAG,
971 "OCEncodeAddressForRFC6874 failed: "
972 "outputSize (%zu) < inputSize (%zu)",
973 outputSize, inputSize);
975 return OC_STACK_ERROR;
978 char* percentChar = strchr(inputAddress, '%');
980 // If there is no '%' character, then no change is required to the string.
981 if (NULL == percentChar)
983 OICStrcpy(outputAddress, outputSize, inputAddress);
987 const char* addressPart = &inputAddress[0];
988 const char* scopeIdPart = percentChar + 1;
990 // Sanity check to make sure this string doesn't have more '%' characters
991 if (NULL != strchr(scopeIdPart, '%'))
993 return OC_STACK_ERROR;
996 // If no string follows the first '%', then the input was invalid.
997 if (scopeIdPart[0] == '\0')
999 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
1000 return OC_STACK_ERROR;
1003 // Check to see if the string is already encoded
1004 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
1006 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Input string is already encoded");
1007 return OC_STACK_ERROR;
1010 // Fail if we don't have room for encoded string's two additional chars
1011 if (outputSize < (inputSize + 2))
1013 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: encoded output will not fit!");
1014 return OC_STACK_ERROR;
1017 // Restore the null terminator with an escaped '%' character, per RFC 6874
1018 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
1019 OICStrcat(outputAddress, outputSize, "%25");
1020 OICStrcat(outputAddress, outputSize, scopeIdPart);
1025 OCStackResult OCDecodeAddressForRFC6874(char *outputAddress,
1027 const char *inputAddress,
1030 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
1031 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
1035 end = inputAddress + strlen(inputAddress);
1037 size_t inputLength = end - inputAddress;
1039 const char *percent = strchr(inputAddress, '%');
1040 if (!percent || (percent > end))
1042 OICStrcpyPartial(outputAddress, outputSize, inputAddress, inputLength);
1046 if (percent[1] != '2' || percent[2] != '5')
1048 return OC_STACK_INVALID_URI;
1051 int addrlen = percent - inputAddress + 1;
1052 OICStrcpyPartial(outputAddress, outputSize, inputAddress, addrlen);
1053 OICStrcpyPartial(outputAddress + addrlen, outputSize - addrlen,
1054 percent + 3, end - percent - 3);
1060 #ifdef WITH_PRESENCE
1062 * The cononical presence allows constructed URIs to be string compared.
1064 * requestUri must be a char array of size CA_MAX_URI_LENGTH
1066 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
1067 char *presenceUri, bool isMulticast)
1069 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
1070 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1074 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1075 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1078 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1079 if (ep->adapter == CA_ADAPTER_IP)
1081 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1083 if ('\0' == ep->addr[0]) // multicast
1085 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1089 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1091 OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1092 sizeof(addressEncoded),
1095 if (OC_STACK_OK != result)
1100 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1101 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1106 if ('\0' == ep->addr[0]) // multicast
1108 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1109 ep->port = OC_MULTICAST_PORT;
1111 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1112 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1116 // might work for other adapters (untested, but better than nothing)
1117 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1118 OC_RSRVD_PRESENCE_URI);
1122 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1123 const CAResponseInfo_t *responseInfo)
1125 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1126 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1128 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1129 ClientCB * cbNode = NULL;
1130 char *resourceTypeName = NULL;
1131 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1132 OCStackResult result = OC_STACK_ERROR;
1133 uint32_t maxAge = 0;
1135 char presenceUri[CA_MAX_URI_LENGTH];
1137 int presenceSubscribe = 0;
1138 int multicastPresenceSubscribe = 0;
1140 if (responseInfo->result != CA_CONTENT)
1142 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1143 return OC_STACK_ERROR;
1146 response.payload = NULL;
1147 response.result = OC_STACK_OK;
1149 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1150 FixUpClientResponse(&response);
1152 if (responseInfo->info.payload)
1154 result = OCParsePayload(&response.payload,
1155 PAYLOAD_TYPE_PRESENCE,
1156 responseInfo->info.payload,
1157 responseInfo->info.payloadSize);
1159 if(result != OC_STACK_OK)
1161 OIC_LOG(ERROR, TAG, "Presence parse failed");
1164 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1166 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1167 result = OC_STACK_ERROR;
1170 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1171 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1172 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1175 // check for unicast presence
1176 uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1177 responseInfo->isMulticast);
1178 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1180 return OC_STACK_INVALID_URI;
1182 OIC_LOG(INFO, TAG, "check for unicast presence");
1183 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1186 presenceSubscribe = 1;
1190 // check for multicast presence
1191 OIC_LOG(INFO, TAG, "check for multicast presence");
1192 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1195 multicastPresenceSubscribe = 1;
1199 if (!presenceSubscribe && !multicastPresenceSubscribe)
1201 OIC_LOG(INFO, TAG, "Received a presence notification, "
1202 "but need to register presence callback, ignoring");
1206 if (presenceSubscribe)
1208 if(cbNode->sequenceNumber == response.sequenceNumber)
1210 OIC_LOG(INFO, TAG, "No presence change");
1211 ResetPresenceTTL(cbNode, maxAge);
1212 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1218 OIC_LOG(INFO, TAG, "Stopping presence");
1219 response.result = OC_STACK_PRESENCE_STOPPED;
1220 if(cbNode->presence)
1222 OICFree(cbNode->presence->timeOut);
1223 OICFree(cbNode->presence);
1224 cbNode->presence = NULL;
1229 if(!cbNode->presence)
1231 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1233 if(!(cbNode->presence))
1235 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1236 result = OC_STACK_NO_MEMORY;
1240 VERIFY_NON_NULL_V(cbNode->presence);
1241 cbNode->presence->timeOut = NULL;
1242 cbNode->presence->timeOut = (uint32_t *)
1243 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1244 if(!(cbNode->presence->timeOut)){
1246 "Could not allocate memory for cbNode->presence->timeOut");
1247 OICFree(cbNode->presence);
1248 cbNode->presence = NULL;
1249 result = OC_STACK_NO_MEMORY;
1254 ResetPresenceTTL(cbNode, maxAge);
1256 cbNode->sequenceNumber = response.sequenceNumber;
1261 // This is the multicast case
1262 OIC_LOG(INFO, TAG, "this is the multicast presence");
1265 OIC_LOG(INFO, TAG, "Stopping presence");
1266 response.result = OC_STACK_PRESENCE_STOPPED;
1270 // Ensure that a filter is actually applied.
1271 if (resourceTypeName && cbNode->filterResourceType)
1273 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1274 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1280 OIC_LOG(INFO, TAG, "Before calling into application address space for presence");
1281 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1282 OIC_LOG(INFO, TAG, "After calling into application address space for presence");
1284 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1286 FindAndDeleteClientCB(cbNode);
1290 OCPayloadDestroy(response.payload);
1293 #endif // WITH_PRESENCE
1295 OCStackResult HandleBatchResponse(char *requestUri, OCRepPayload **payload)
1297 if (requestUri && *payload)
1299 char *interfaceName = NULL;
1300 char *rtTypeName = NULL;
1301 char *uriQuery = NULL;
1302 char *uriWithoutQuery = NULL;
1303 if (OC_STACK_OK == getQueryFromUri(requestUri, &uriQuery, &uriWithoutQuery))
1305 if (OC_STACK_OK == ExtractFiltersFromQuery(uriQuery, &interfaceName, &rtTypeName))
1307 if (interfaceName && (0 == strcmp(OC_RSRVD_INTERFACE_BATCH, interfaceName)))
1309 char *uri = (*payload)->uri;
1310 if (uri && 0 != strcmp(uriWithoutQuery, uri))
1312 OCRepPayload *newPayload = OCRepPayloadCreate();
1315 OCRepPayloadSetUri(newPayload, uri);
1316 newPayload->next = *payload;
1317 *payload = newPayload;
1324 OICFree(interfaceName);
1325 OICFree(rtTypeName);
1327 OICFree(uriWithoutQuery);
1330 return OC_STACK_INVALID_PARAM;
1333 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1335 OIC_TRACE_MARK(%s:OCHandleResponse:%s, TAG, responseInfo->info.resourceUri);
1336 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1338 #ifdef WITH_PRESENCE
1339 if(responseInfo->info.resourceUri &&
1340 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1342 HandlePresenceResponse(endPoint, responseInfo);
1347 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1348 responseInfo->info.tokenLength, NULL, NULL);
1352 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1354 // check obs header option
1355 bool obsHeaderOpt = false;
1356 CAHeaderOption_t *options = responseInfo->info.options;
1357 for (uint8_t i = 0; i< responseInfo->info.numOptions; i++)
1359 if (options && options[i].protocolID == CA_COAP_ID &&
1360 options[i].optionID == COAP_OPTION_OBSERVE)
1362 obsHeaderOpt = true;
1367 if(responseInfo->result == CA_EMPTY)
1369 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1370 // We do not have a case for the client to receive a RESET
1371 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1373 //This is the case of receiving an ACK on a request to a slow resource!
1374 OIC_LOG(INFO, TAG, "This is a pure ACK");
1375 //TODO: should we inform the client
1376 // app that at least the request was received at the server?
1379 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1381 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1383 OCClientResponse response =
1384 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1385 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1386 FixUpClientResponse(&response);
1387 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1388 memcpy(response.identity.id, responseInfo->info.identity.id,
1389 sizeof (response.identity.id));
1390 response.identity.id_length = responseInfo->info.identity.id_length;
1392 response.result = CAResponseToOCStackResult(responseInfo->result);
1393 OIC_LOG(INFO, TAG, "Before calling into application address space for reTrans timeout");
1394 cbNode->callBack(cbNode->context,
1395 cbNode->handle, &response);
1396 OIC_LOG(INFO, TAG, "After calling into application address space for reTrans timeout");
1397 FindAndDeleteClientCB(cbNode);
1398 OICFree((void *)response.resourceUri);
1401 else if ((cbNode->method == OC_REST_OBSERVE || cbNode->method == OC_REST_OBSERVE_ALL)
1402 && (responseInfo->result == CA_CONTENT) && !obsHeaderOpt)
1404 OCClientResponse response =
1405 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1406 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1407 FixUpClientResponse(&response);
1408 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1409 memcpy(response.identity.id, responseInfo->info.identity.id,
1410 sizeof (response.identity.id));
1411 response.identity.id_length = responseInfo->info.identity.id_length;
1412 response.result = OC_STACK_UNAUTHORIZED_REQ;
1414 OIC_LOG(INFO, TAG, "Before calling into application address space for observe resp");
1415 cbNode->callBack(cbNode->context,
1418 OIC_LOG(INFO, TAG, "After calling into application address space for observe resp");
1420 FindAndDeleteClientCB(cbNode);
1421 OICFree(response.resourceUri);
1426 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1428 OCClientResponse response;
1429 memset(&response, 0, sizeof(OCClientResponse));
1430 response.devAddr.adapter = OC_DEFAULT_ADAPTER;
1432 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1433 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1434 FixUpClientResponse(&response);
1435 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1436 memcpy(response.identity.id, responseInfo->info.identity.id,
1437 sizeof (response.identity.id));
1438 response.identity.id_length = responseInfo->info.identity.id_length;
1440 response.result = CAResponseToOCStackResult(responseInfo->result);
1442 if(responseInfo->info.payload &&
1443 responseInfo->info.payloadSize)
1445 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1446 // check the security resource
1447 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1449 type = PAYLOAD_TYPE_SECURITY;
1451 else if (cbNode->method == OC_REST_DISCOVER)
1453 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1454 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1456 type = PAYLOAD_TYPE_DISCOVERY;
1459 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1461 type = PAYLOAD_TYPE_DISCOVERY;
1464 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1466 type = PAYLOAD_TYPE_REPRESENTATION;
1468 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1470 type = PAYLOAD_TYPE_REPRESENTATION;
1473 #ifdef ROUTING_GATEWAY
1474 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1476 type = PAYLOAD_TYPE_REPRESENTATION;
1479 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1481 type = PAYLOAD_TYPE_REPRESENTATION;
1484 else if (strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1486 type = PAYLOAD_TYPE_REPRESENTATION;
1491 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1492 cbNode->method, cbNode->requestUri);
1493 OICFree((void *)response.resourceUri);
1497 else if (cbNode->method == OC_REST_GET ||
1498 cbNode->method == OC_REST_PUT ||
1499 cbNode->method == OC_REST_POST ||
1500 cbNode->method == OC_REST_OBSERVE ||
1501 cbNode->method == OC_REST_OBSERVE_ALL ||
1502 cbNode->method == OC_REST_DELETE)
1504 if (cbNode->requestUri)
1506 if (0 == strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri))
1508 type = PAYLOAD_TYPE_REPRESENTATION;
1510 else if (0 == strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri))
1512 type = PAYLOAD_TYPE_REPRESENTATION;
1514 if (type == PAYLOAD_TYPE_INVALID)
1516 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1517 cbNode->method, cbNode->requestUri);
1518 type = PAYLOAD_TYPE_REPRESENTATION;
1523 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1524 type = PAYLOAD_TYPE_REPRESENTATION;
1529 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1530 cbNode->method, cbNode->requestUri);
1531 OICFree((void *)response.resourceUri);
1535 // In case of error, still want application to receive the error message.
1536 if (OCResultToSuccess(response.result) || PAYLOAD_TYPE_REPRESENTATION == type)
1538 if(OC_STACK_OK != OCParsePayload(&response.payload,
1540 responseInfo->info.payload,
1541 responseInfo->info.payloadSize))
1543 OIC_LOG(ERROR, TAG, "Error converting payload");
1544 OCPayloadDestroy(response.payload);
1545 OICFree((void *)response.resourceUri);
1551 OICFree((void *)response.resourceUri);
1552 response.resourceUri = OICStrdup(cbNode->requestUri);
1556 response.numRcvdVendorSpecificHeaderOptions = 0;
1557 if(responseInfo->info.numOptions > 0)
1560 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1561 if(responseInfo->info.options
1562 && responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1565 uint32_t observationOption;
1566 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1567 for (observationOption=0, i=0;
1568 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1572 (observationOption << 8) | optionData[i];
1574 response.sequenceNumber = observationOption;
1575 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1580 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1583 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1585 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1586 OCPayloadDestroy(response.payload);
1587 OICFree((void *)response.resourceUri);
1591 if (response.numRcvdVendorSpecificHeaderOptions > 0)
1593 response.rcvdVendorSpecificHeaderOptions =
1594 (OCHeaderOption *) OICCalloc(response.numRcvdVendorSpecificHeaderOptions, sizeof(OCHeaderOption));
1595 if (NULL == response.rcvdVendorSpecificHeaderOptions)
1597 OIC_LOG(ERROR, TAG, "Failed to allocate memory for vendor header options");
1598 OCPayloadDestroy(response.payload);
1599 OICFree((void *)response.resourceUri);
1603 memcpy(response.rcvdVendorSpecificHeaderOptions, responseInfo->info.options + start,
1604 response.numRcvdVendorSpecificHeaderOptions*sizeof(OCHeaderOption));
1608 if (cbNode->method == OC_REST_OBSERVE &&
1609 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1610 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1611 response.sequenceNumber <= cbNode->sequenceNumber)
1613 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1614 response.sequenceNumber);
1619 if (cbNode->requestUri)
1621 // if request uri is '/oic/rd', update ins value of resource.
1622 char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
1625 OCUpdateResourceInsWithResponse(cbNode->requestUri, &response);
1629 // set remoteID(device ID) into OCClientResponse callback parameter
1630 if (OC_REST_DISCOVER == cbNode->method)
1632 OIC_LOG(INFO, TAG, "cbNode method is OC_REST_DISCOVER");
1633 OCDiscoveryPayload *payload = (OCDiscoveryPayload*) response.payload;
1634 // Payload can be empty in case of error message.
1635 if (payload && payload->sid)
1637 OICStrcpy(response.devAddr.remoteId, sizeof(response.devAddr.remoteId),
1639 OIC_LOG_V(INFO_PRIVATE, TAG, "Device ID of response : %s",
1640 response.devAddr.remoteId);
1643 if(NULL == response.resourceUri)
1645 response.resourceUri = OICStrdup(cbNode->requestUri);
1649 if (cbNode->requestUri)
1651 OIC_LOG_V(INFO, TAG, "cbNode requestUri is %s", cbNode->requestUri);
1652 if (cbNode->method == OC_REST_POST &&
1653 strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1655 OCHandleKeepAliveResponse(endPoint, response.payload);
1659 if (response.payload && response.payload->type == PAYLOAD_TYPE_REPRESENTATION)
1661 OIC_LOG(INFO, TAG, "Handle batch response");
1662 HandleBatchResponse(cbNode->requestUri, (OCRepPayload **)&response.payload);
1665 OIC_LOG(INFO, TAG, "Before calling into application address space for handleResponse");
1666 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1669 OIC_LOG(INFO, TAG, "After calling into application address space for handleResponse");
1671 cbNode->sequenceNumber = response.sequenceNumber;
1673 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1675 FindAndDeleteClientCB(cbNode);
1679 // To keep discovery callbacks active.
1680 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1681 MILLISECONDS_PER_SECOND);
1685 //Need to send ACK when the response is CON
1686 if(responseInfo->info.type == CA_MSG_CONFIRM)
1688 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1690 OIC_LOG(INFO, TAG, "Received a confirmable message. Sending EMPTY");
1691 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1692 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1696 OICFree((void *)response.resourceUri);
1697 OCPayloadDestroy(response.payload);
1698 OICFree(response.rcvdVendorSpecificHeaderOptions);
1703 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1704 responseInfo->info.tokenLength);
1708 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1709 if(responseInfo->result == CA_EMPTY)
1711 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1712 if(responseInfo->info.type == CA_MSG_RESET)
1714 OIC_LOG(INFO, TAG, "This is a RESET");
1715 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1716 OC_OBSERVER_NOT_INTERESTED);
1718 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1720 OIC_LOG(INFO, TAG, "This is a pure ACK");
1721 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1722 OC_OBSERVER_STILL_INTERESTED);
1725 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1727 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1728 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1729 OC_OBSERVER_FAILED_COMM);
1732 FreeObserver(observer);
1736 if(!cbNode && !observer)
1738 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1739 || myStackMode == OC_GATEWAY)
1741 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1742 if(responseInfo->result == CA_EMPTY)
1744 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1748 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1750 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1751 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1752 CA_MSG_RESET, 0, NULL, NULL, 0, NULL,
1753 CA_RESPONSE_FOR_RES);
1758 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1759 || myStackMode == OC_GATEWAY)
1761 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1762 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1764 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1765 responseInfo->info.messageId);
1767 if (responseInfo->info.type == CA_MSG_RESET)
1769 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1770 responseInfo->info.messageId);
1778 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1780 VERIFY_NON_NULL_NR(endPoint, FATAL);
1781 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1783 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1784 OIC_TRACE_BEGIN(%s:HandleCAResponses, TAG);
1786 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1787 #ifdef ROUTING_GATEWAY
1788 bool needRIHandling = false;
1790 * Routing manager is going to update either of endpoint or response or both.
1791 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1792 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1795 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1797 if(ret != OC_STACK_OK || !needRIHandling)
1799 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1806 * Put source in sender endpoint so that the next packet from application can be routed to
1807 * proper destination and remove "RM" coap header option before passing request / response to
1808 * RI as this option will make no sense to either RI or application.
1810 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1811 (uint8_t *) &(responseInfo->info.numOptions),
1812 (CAEndpoint_t *) endPoint);
1815 OCHandleResponse(endPoint, responseInfo);
1817 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1821 * This function handles error response from CA
1822 * code shall be added to handle the errors
1824 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1826 VERIFY_NON_NULL_NR(endPoint, FATAL);
1827 VERIFY_NON_NULL_NR(errorInfo, FATAL);
1829 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1830 OIC_TRACE_BEGIN(%s:HandleCAErrorResponse, TAG);
1832 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1833 errorInfo->info.tokenLength, NULL, NULL);
1836 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1837 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1838 FixUpClientResponse(&response);
1839 response.resourceUri = errorInfo->info.resourceUri;
1840 memcpy(response.identity.id, errorInfo->info.identity.id,
1841 sizeof (response.identity.id));
1842 response.identity.id_length = errorInfo->info.identity.id_length;
1843 response.result = CAResultToOCResult(errorInfo->result);
1845 OIC_LOG(INFO, TAG, "Before calling into application address space for error response");
1846 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1847 OIC_LOG(INFO, TAG, "After calling into application address space for error response");
1849 FindAndDeleteClientCB(cbNode);
1852 ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1853 errorInfo->info.tokenLength);
1856 OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1857 OCStackResult result = CAResultToOCResult(errorInfo->result);
1858 if (OC_STACK_COMM_ERROR == result)
1860 OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1861 OC_OBSERVER_FAILED_COMM);
1865 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1867 if(NULL != observer)
1875 * This function sends out Direct Stack Responses. These are responses that are not coming
1876 * from the application entity handler. These responses have no payload and are usually ACKs,
1877 * RESETs or some error conditions that were caught by the stack.
1879 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1880 const CAResponseResult_t responseResult, const CAMessageType_t type,
1881 const uint8_t numOptions, const CAHeaderOption_t *options,
1882 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1883 CADataType_t dataType)
1885 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1887 if (endPoint->flags & CA_MULTICAST)
1889 OIC_LOG(ERROR, TAG, "It is unnecessary to respond to a multicast request");
1893 CAResponseInfo_t respInfo = { .result = responseResult };
1894 respInfo.info.messageId = coapID;
1895 respInfo.info.numOptions = numOptions;
1897 if (respInfo.info.numOptions)
1899 respInfo.info.options =
1900 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1901 memcpy (respInfo.info.options, options,
1902 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1906 respInfo.info.payload = NULL;
1907 respInfo.info.token = token;
1908 respInfo.info.tokenLength = tokenLength;
1909 respInfo.info.type = type;
1910 respInfo.info.resourceUri = OICStrdup (resourceUri);
1911 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1912 respInfo.info.dataType = dataType;
1914 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1915 // Add the destination to route option from the endpoint->routeData.
1916 bool doPost = false;
1917 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1918 if(OC_STACK_OK != result)
1920 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1921 OICFree (respInfo.info.resourceUri);
1922 OICFree (respInfo.info.options);
1927 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1928 CARequestInfo_t reqInfo = {.method = CA_POST };
1929 /* The following initialization is not done in a single initializer block as in
1930 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1931 * does not have designated initalizers. This is a work-around for now.
1933 reqInfo.info.type = CA_MSG_NONCONFIRM;
1934 reqInfo.info.messageId = coapID;
1935 reqInfo.info.tokenLength = tokenLength;
1936 reqInfo.info.token = token;
1937 reqInfo.info.numOptions = respInfo.info.numOptions;
1938 reqInfo.info.payload = NULL;
1939 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1940 if (reqInfo.info.numOptions)
1942 reqInfo.info.options =
1943 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1944 if (NULL == reqInfo.info.options)
1946 OIC_LOG(ERROR, TAG, "Calloc failed");
1947 OICFree (reqInfo.info.resourceUri);
1948 OICFree (respInfo.info.resourceUri);
1949 OICFree (respInfo.info.options);
1950 return OC_STACK_NO_MEMORY;
1952 memcpy (reqInfo.info.options, respInfo.info.options,
1953 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1956 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1957 OICFree (reqInfo.info.resourceUri);
1958 OICFree (reqInfo.info.options);
1959 OICFree (respInfo.info.resourceUri);
1960 OICFree (respInfo.info.options);
1961 if (CA_STATUS_OK != caResult)
1963 OIC_LOG(ERROR, TAG, "CASendRequest error");
1964 return CAResultToOCResult(caResult);
1970 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1972 // resourceUri in the info field is cloned in the CA layer and
1973 // thus ownership is still here.
1974 OICFree (respInfo.info.resourceUri);
1975 OICFree (respInfo.info.options);
1976 if(CA_STATUS_OK != caResult)
1978 OIC_LOG(ERROR, TAG, "CASendResponse error");
1979 return CAResultToOCResult(caResult);
1982 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1986 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1988 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1989 OCStackResult result = OC_STACK_ERROR;
1990 if(!protocolRequest)
1992 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1993 return OC_STACK_INVALID_PARAM;
1996 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1997 protocolRequest->tokenLength);
2000 OIC_LOG(INFO, TAG, "This is a new Server Request");
2001 result = AddServerRequest(&request, protocolRequest->coapID,
2002 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
2003 protocolRequest->numRcvdVendorSpecificHeaderOptions,
2004 protocolRequest->observationOption, protocolRequest->qos,
2005 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
2006 protocolRequest->payload, protocolRequest->requestToken,
2007 protocolRequest->tokenLength, protocolRequest->resourceUrl,
2008 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
2009 &protocolRequest->devAddr);
2010 if (OC_STACK_OK != result)
2012 OIC_LOG(ERROR, TAG, "Error adding server request");
2018 OIC_LOG(ERROR, TAG, "Out of Memory");
2019 return OC_STACK_NO_MEMORY;
2022 if(!protocolRequest->reqMorePacket)
2024 request->requestComplete = 1;
2027 OIC_LOG_V(WARNING, TAG, "Server request ID = [%u]", request->requestId);
2031 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
2032 return OC_STACK_DUPLICATE_REQUEST;
2035 if(request->requestComplete)
2037 OIC_LOG(INFO, TAG, "This Server Request is complete");
2038 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2039 OCResource *resource = NULL;
2040 result = DetermineResourceHandling (request, &resHandling, &resource);
2041 if (result == OC_STACK_OK)
2043 result = ProcessRequest(resHandling, resource, request);
2048 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2049 result = OC_STACK_CONTINUE;
2054 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2056 OIC_TRACE_MARK(%s:OCHandleRequests:%s, TAG, requestInfo->info.resourceUri);
2057 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2059 OCStackResult requestResult = OC_STACK_ERROR;
2061 if(myStackMode == OC_CLIENT)
2063 //TODO: should the client be responding to requests?
2067 OCServerProtocolRequest serverRequest = {0};
2069 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2071 char * uriWithoutQuery = NULL;
2072 char * query = NULL;
2074 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2076 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2078 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2081 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2082 OIC_LOG_V(INFO, TAG, "Query : %s", query);
2084 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2086 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2087 OICFree(uriWithoutQuery);
2091 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2092 OICFree(uriWithoutQuery);
2099 if(strlen(query) < MAX_QUERY_LENGTH)
2101 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2106 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2112 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2114 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2115 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2116 if (!serverRequest.payload)
2118 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2121 memcpy (serverRequest.payload, requestInfo->info.payload,
2122 requestInfo->info.payloadSize);
2126 serverRequest.reqTotalSize = 0;
2129 switch (requestInfo->method)
2132 serverRequest.method = OC_REST_GET;
2135 serverRequest.method = OC_REST_PUT;
2138 serverRequest.method = OC_REST_POST;
2141 serverRequest.method = OC_REST_DELETE;
2144 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2145 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2146 requestInfo->info.type, requestInfo->info.numOptions,
2147 requestInfo->info.options, requestInfo->info.token,
2148 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2150 OICFree(serverRequest.payload);
2154 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2155 requestInfo->info.tokenLength);
2157 serverRequest.tokenLength = requestInfo->info.tokenLength;
2158 if (serverRequest.tokenLength) {
2160 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2162 if (!serverRequest.requestToken)
2164 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2165 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2166 requestInfo->info.type, requestInfo->info.numOptions,
2167 requestInfo->info.options, requestInfo->info.token,
2168 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2170 OICFree(serverRequest.payload);
2173 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2176 switch (requestInfo->info.acceptFormat)
2178 case CA_FORMAT_APPLICATION_CBOR:
2179 serverRequest.acceptFormat = OC_FORMAT_CBOR;
2181 case CA_FORMAT_UNDEFINED:
2182 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2185 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2188 if (requestInfo->info.type == CA_MSG_CONFIRM)
2190 serverRequest.qos = OC_HIGH_QOS;
2194 serverRequest.qos = OC_LOW_QOS;
2196 // CA does not need the following field
2197 // Are we sure CA does not need them? how is it responding to multicast
2198 serverRequest.delayedResNeeded = 0;
2200 serverRequest.coapID = requestInfo->info.messageId;
2202 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2204 // copy vendor specific header options
2205 uint8_t tempNum = (requestInfo->info.numOptions);
2207 // Assume no observation requested and it is a pure GET.
2208 // If obs registration/de-registration requested it'll be fetched from the
2209 // options in GetObserveHeaderOption()
2210 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2212 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2213 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2216 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2217 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2218 requestInfo->info.type, requestInfo->info.numOptions,
2219 requestInfo->info.options, requestInfo->info.token,
2220 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2222 OICFree(serverRequest.payload);
2223 OICFree(serverRequest.requestToken);
2227 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2228 if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2230 serverRequest.rcvdVendorSpecificHeaderOptions = (OCHeaderOption*) OICCalloc(tempNum, sizeof(OCHeaderOption));
2231 if (NULL == serverRequest.rcvdVendorSpecificHeaderOptions)
2233 OIC_LOG(ERROR, TAG, "Failed to allocated memory to vnd header options!");
2234 OICFree(serverRequest.payload);
2235 OICFree(serverRequest.requestToken);
2239 memcpy (serverRequest.rcvdVendorSpecificHeaderOptions, requestInfo->info.options,
2240 sizeof(CAHeaderOption_t)*tempNum);
2243 requestResult = HandleStackRequests (&serverRequest);
2245 // Send ACK to client as precursor to slow response
2246 if (requestResult == OC_STACK_SLOW_RESOURCE)
2248 if (requestInfo->info.type == CA_MSG_CONFIRM)
2250 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2251 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2256 if (requestResult == OC_STACK_RESOURCE_ERROR
2257 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2259 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2262 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2264 if (requestResult == OC_STACK_RESOURCE_ERROR)
2266 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2268 else if (!OCResultToSuccess(requestResult))
2270 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2274 else if(!OCResultToSuccess(requestResult))
2276 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2278 // Delete observer node if it is OBSERVE failure from app
2279 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2281 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2284 CAResponseResult_t stackResponse =
2285 OCToCAStackResult(requestResult, serverRequest.method);
2287 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2288 requestInfo->info.type, requestInfo->info.numOptions,
2289 requestInfo->info.options, requestInfo->info.token,
2290 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2293 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2294 // The token is copied in there, and is thus still owned by this function.
2295 OICFree(serverRequest.payload);
2296 OICFree(serverRequest.requestToken);
2297 OICFree(serverRequest.rcvdVendorSpecificHeaderOptions);
2298 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2301 //This function will be called back by CA layer when a request is received
2302 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2304 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2305 OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2308 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2315 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2320 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2321 #ifdef ROUTING_GATEWAY
2322 bool needRIHandling = false;
2323 bool isEmptyMsg = false;
2325 * Routing manager is going to update either of endpoint or request or both.
2326 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2327 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2328 * destination. It can also remove "RM" coap header option before passing request / response to
2329 * RI as this option will make no sense to either RI or application.
2331 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2332 &needRIHandling, &isEmptyMsg);
2333 if(OC_STACK_OK != ret || !needRIHandling)
2335 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2342 * Put source in sender endpoint so that the next packet from application can be routed to
2343 * proper destination and remove RM header option.
2345 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2346 (uint8_t *) &(requestInfo->info.numOptions),
2347 (CAEndpoint_t *) endPoint);
2349 #ifdef ROUTING_GATEWAY
2353 * In Gateways, the MSGType in route option is used to check if the actual
2354 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2355 * EMPTY response is sent in the form of POST request which need to be changed
2356 * to a EMPTY response by RM. This translation is done in this part of the code.
2358 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2359 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2360 .info.messageId = requestInfo->info.messageId,
2361 .info.type = CA_MSG_ACKNOWLEDGE};
2362 OCHandleResponse(endPoint, &respInfo);
2368 // Normal handling of the packet
2369 OCHandleRequests(endPoint, requestInfo);
2371 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2375 //-----------------------------------------------------------------------------
2377 //-----------------------------------------------------------------------------
2379 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2382 !raInfo->username ||
2383 !raInfo->hostname ||
2384 !raInfo->xmpp_domain)
2387 return OC_STACK_INVALID_PARAM;
2389 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2390 gRASetInfo = (result == OC_STACK_OK)? true : false;
2396 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2400 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2403 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2405 OC_UNUSED(serverFlags);
2406 OC_UNUSED(clientFlags);
2408 OIC_LOG(DEBUG, TAG, "call OCInit1");
2409 return OCInit2(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS, OC_DEFAULT_ADAPTER);
2412 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2413 OCTransportAdapter transportType)
2415 if(stackState == OC_STACK_INITIALIZED)
2417 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2418 OCStop() between them are ignored.");
2422 #ifndef ROUTING_GATEWAY
2423 if (OC_GATEWAY == mode)
2425 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2426 return OC_STACK_INVALID_PARAM;
2433 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2434 return OC_STACK_ERROR;
2438 OCStackResult result = OC_STACK_ERROR;
2439 OIC_LOG(INFO, TAG, "Entering OCInit");
2442 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2443 || (mode == OC_GATEWAY)))
2445 OIC_LOG(ERROR, TAG, "Invalid mode");
2446 return OC_STACK_ERROR;
2450 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2452 caglobals.client = true;
2454 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2456 caglobals.server = true;
2459 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2460 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2462 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2464 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2465 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2467 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2470 defaultDeviceHandler = NULL;
2471 defaultDeviceHandlerCallbackParameter = NULL;
2473 result = InitializeScheduleResourceList();
2474 VERIFY_SUCCESS(result, OC_STACK_OK);
2476 result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2477 VERIFY_SUCCESS(result, OC_STACK_OK);
2479 result = CAResultToOCResult(OCSelectNetwork(transportType));
2480 VERIFY_SUCCESS(result, OC_STACK_OK);
2482 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2483 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2484 VERIFY_SUCCESS(result, OC_STACK_OK);
2486 switch (myStackMode)
2489 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2490 result = CAResultToOCResult(CAStartDiscoveryServer());
2491 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2494 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2495 result = CAResultToOCResult(CAStartListeningServer());
2496 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2498 case OC_CLIENT_SERVER:
2500 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2501 result = CAResultToOCResult(CAStartListeningServer());
2502 if(result == OC_STACK_OK)
2504 result = CAResultToOCResult(CAStartDiscoveryServer());
2508 VERIFY_SUCCESS(result, OC_STACK_OK);
2511 CARegisterKeepAliveHandler(OCHandleKeepAliveConnCB);
2514 #ifdef WITH_PRESENCE
2515 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2516 #endif // WITH_PRESENCE
2518 //Update Stack state to initialized
2519 stackState = OC_STACK_INITIALIZED;
2521 // Initialize resource
2522 if(myStackMode != OC_CLIENT)
2524 result = initResources();
2527 // Initialize the SRM Policy Engine
2528 if(result == OC_STACK_OK)
2530 result = SRMInitPolicyEngine();
2531 // TODO after BeachHead delivery: consolidate into single SRMInit()
2533 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2534 RMSetStackMode(mode);
2535 #ifdef ROUTING_GATEWAY
2536 if (OC_GATEWAY == myStackMode)
2538 result = RMInitialize();
2544 if (result == OC_STACK_OK)
2546 result = OCInitializeKeepAlive(myStackMode);
2550 InitializeObserverList();
2553 if(result != OC_STACK_OK)
2555 OIC_LOG(ERROR, TAG, "Stack initialization error");
2556 TerminateScheduleResourceList();
2557 deleteAllResources();
2559 stackState = OC_STACK_UNINITIALIZED;
2564 OCStackResult OCStop()
2566 OIC_LOG(INFO, TAG, "Entering OCStop");
2568 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2570 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2573 else if (stackState != OC_STACK_INITIALIZED)
2575 OIC_LOG(INFO, TAG, "Stack not initialized");
2576 return OC_STACK_ERROR;
2579 // unset cautil config
2580 CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2581 CAUtilSetBTConfigure(configs);
2583 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2585 CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2586 OCDefaultConnectionStateChangedHandler);
2588 #ifdef WITH_PRESENCE
2589 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2590 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2591 presenceResource.presenceTTL = 0;
2592 presenceState = OC_PRESENCE_UNINITIALIZED;
2593 #endif // WITH_PRESENCE
2595 #ifdef ROUTING_GATEWAY
2596 if (OC_GATEWAY == myStackMode)
2603 OCTerminateKeepAlive(myStackMode);
2606 TerminateScheduleResourceList();
2607 // Remove all observers
2608 DeleteObserverList();
2609 // Free memory dynamically allocated for resources
2610 deleteAllResources();
2611 // Remove all the client callbacks
2612 DeleteClientCBList();
2613 // Terminate connectivity-abstraction layer.
2616 // De-init the SRM Policy Engine
2617 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2618 SRMDeInitPolicyEngine();
2620 // Destroy Observer List Mutex
2621 TerminateObserverList();
2623 stackState = OC_STACK_UNINITIALIZED;
2627 OCStackResult OCStartMulticastServer()
2629 if(stackState != OC_STACK_INITIALIZED)
2631 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2632 return OC_STACK_ERROR;
2634 CAResult_t ret = CAStartListeningServer();
2635 if (CA_STATUS_OK != ret)
2637 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2638 return OC_STACK_ERROR;
2643 OCStackResult OCStopMulticastServer()
2645 CAResult_t ret = CAStopListeningServer();
2646 if (CA_STATUS_OK != ret)
2648 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2649 return OC_STACK_ERROR;
2654 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2659 return CA_MSG_CONFIRM;
2664 return CA_MSG_NONCONFIRM;
2668 OCStackResult ParseRequestUri(const char *fullUri,
2669 OCTransportAdapter adapter,
2670 OCTransportFlags flags,
2671 OCDevAddr **devAddr,
2673 char **resourceType)
2675 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2677 OCStackResult result = OC_STACK_OK;
2678 OCDevAddr *da = NULL;
2682 // provide defaults for all returned values
2689 *resourceUri = NULL;
2693 *resourceType = NULL;
2696 // delimit url prefix, if any
2697 const char *start = fullUri;
2698 char *slash2 = strstr(start, "//");
2703 char *slash = strchr(start, '/');
2706 return OC_STACK_INVALID_URI;
2709 // process url scheme
2710 size_t prefixLen = slash2 - fullUri;
2714 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2715 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2721 // TODO: this logic should come in with unit tests exercising the various strings
2722 // processs url prefix, if any
2723 size_t urlLen = slash - start;
2727 if (urlLen && devAddr)
2728 { // construct OCDevAddr
2729 if (start[0] == '[')
2731 char *close = strchr(++start, ']');
2732 if (!close || close > slash)
2734 return OC_STACK_INVALID_URI;
2737 if (close[1] == ':')
2744 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2748 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2750 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2754 char *dot = strchr(start, '.');
2755 if (dot && dot < slash)
2757 colon = strchr(start, ':');
2758 end = (colon && colon < slash) ? colon : slash;
2763 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2767 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2769 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2777 if (len >= sizeof(da->addr))
2779 return OC_STACK_INVALID_URI;
2781 // collect port, if any
2782 if (colon && colon < slash)
2784 for (colon++; colon < slash; colon++)
2787 if (c < '0' || c > '9')
2789 return OC_STACK_INVALID_URI;
2791 port = 10 * port + c - '0';
2796 if (len >= sizeof(da->addr))
2798 return OC_STACK_INVALID_URI;
2801 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2804 return OC_STACK_NO_MEMORY;
2807 // Decode address per RFC 6874.
2808 result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2809 if (result != OC_STACK_OK)
2816 da->adapter = adapter;
2818 if (!strncmp(fullUri, "coaps", 5))
2820 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2825 // process resource uri, if any
2827 { // request uri and query
2828 size_t ulen = strlen(slash); // resource uri length
2829 size_t tlen = 0; // resource type length
2832 static const char strPresence[] = "/oic/ad?rt=";
2833 static const size_t lenPresence = sizeof(strPresence) - 1;
2834 if (!strncmp(slash, strPresence, lenPresence))
2836 type = slash + lenPresence;
2837 tlen = ulen - lenPresence;
2842 *resourceUri = (char *)OICMalloc(ulen + 1);
2845 result = OC_STACK_NO_MEMORY;
2848 OICStrcpy(*resourceUri, (ulen + 1), slash);
2851 if (type && resourceType)
2853 *resourceType = (char *)OICMalloc(tlen + 1);
2856 result = OC_STACK_NO_MEMORY;
2860 OICStrcpy(*resourceType, (tlen+1), type);
2867 // free all returned values
2874 OICFree(*resourceUri);
2878 OICFree(*resourceType);
2883 #ifdef WITH_PRESENCE
2884 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2888 char uri[CA_MAX_URI_LENGTH];
2890 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2892 *requestUri = OICStrdup(uri);
2895 return OC_STACK_NO_MEMORY;
2900 #endif // WITH_PRESENCE
2903 * Discover or Perform requests on a specified resource
2905 OCStackResult OCDoResource(OCDoHandle *handle,
2907 const char *requestUri,
2908 const OCDevAddr *destination,
2910 OCConnectivityType connectivityType,
2911 OCQualityOfService qos,
2912 OCCallbackData *cbData,
2913 OCHeaderOption *options,
2916 OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
2917 connectivityType, qos, cbData, options, numOptions);
2919 // This is the owner of the payload object, so we free it
2920 OCPayloadDestroy(payload);
2925 * Discover or Perform requests on a specified resource
2927 OCStackResult OCDoRequest(OCDoHandle *handle,
2929 const char *requestUri,
2930 const OCDevAddr *destination,
2932 OCConnectivityType connectivityType,
2933 OCQualityOfService qos,
2934 OCCallbackData *cbData,
2935 OCHeaderOption *options,
2938 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2939 OIC_TRACE_BEGIN(%s:OCDoRequest, TAG);
2941 // Validate input parameters
2942 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2943 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2945 OCStackResult result = OC_STACK_ERROR;
2946 CAResult_t caResult;
2947 CAToken_t token = NULL;
2948 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2949 ClientCB *clientCB = NULL;
2950 OCDoHandle resHandle = NULL;
2951 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2952 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2954 OCTransportAdapter adapter;
2955 OCTransportFlags flags;
2956 // the request contents are put here
2957 CARequestInfo_t requestInfo = {.method = CA_GET};
2958 // requestUri will be parsed into the following three variables
2959 OCDevAddr *devAddr = NULL;
2960 char *resourceUri = NULL;
2961 char *resourceType = NULL;
2964 * Support original behavior with address on resourceUri argument.
2966 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2967 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2971 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2972 if (result != OC_STACK_OK)
2974 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2978 else if (!checkProxyUri(options, numOptions))
2980 result = OC_STACK_INVALID_URI;
2981 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2988 case OC_REST_OBSERVE:
2989 case OC_REST_OBSERVE_ALL:
2990 requestInfo.method = CA_GET;
2993 requestInfo.method = CA_PUT;
2996 requestInfo.method = CA_POST;
2998 case OC_REST_DELETE:
2999 requestInfo.method = CA_DELETE;
3001 case OC_REST_DISCOVER:
3002 #ifdef WITH_PRESENCE
3003 case OC_REST_PRESENCE:
3005 if (destination || devAddr)
3007 requestInfo.isMulticast = false;
3011 tmpDevAddr.adapter = adapter;
3012 tmpDevAddr.flags = flags;
3013 destination = &tmpDevAddr;
3014 requestInfo.isMulticast = true;
3017 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
3018 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
3019 // replacing method type with GET.
3020 requestInfo.method = CA_GET;
3023 result = OC_STACK_INVALID_METHOD;
3027 if (!devAddr && !destination)
3029 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
3030 result = OC_STACK_INVALID_PARAM;
3034 /* If not original behavior, use destination argument */
3035 if (destination && !devAddr)
3037 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
3040 result = OC_STACK_NO_MEMORY;
3043 OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
3044 *devAddr = *destination;
3049 OIC_LOG_V(INFO_PRIVATE, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
3050 if (!requestInfo.isMulticast)
3052 OIC_LOG_V(DEBUG, TAG, "remoteAddr of devAddr : [%s]:[%d]",
3053 devAddr->addr, devAddr->port);
3057 resHandle = GenerateInvocationHandle();
3060 result = OC_STACK_NO_MEMORY;
3064 caResult = CAGenerateToken(&token, tokenLength);
3065 if (caResult != CA_STATUS_OK)
3067 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3068 result = CAResultToOCResult(caResult);
3072 // fill in request data
3073 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3074 requestInfo.info.token = token;
3075 requestInfo.info.tokenLength = tokenLength;
3077 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3079 result = CreateObserveHeaderOption (&(requestInfo.info.options),
3080 options, numOptions, OC_OBSERVE_REGISTER);
3081 if (result != OC_STACK_OK)
3085 requestInfo.info.numOptions = numOptions + 1;
3089 requestInfo.info.numOptions = numOptions;
3090 requestInfo.info.options =
3091 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3092 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3093 numOptions * sizeof(CAHeaderOption_t));
3096 CopyDevAddrToEndpoint(devAddr, &endpoint);
3101 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3104 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3107 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3111 requestInfo.info.payload = NULL;
3112 requestInfo.info.payloadSize = 0;
3113 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3116 // prepare for response
3117 #ifdef WITH_PRESENCE
3118 if (method == OC_REST_PRESENCE)
3120 char *presenceUri = NULL;
3121 result = OCPreparePresence(&endpoint, &presenceUri,
3122 requestInfo.isMulticast);
3123 if (OC_STACK_OK != result)
3128 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3129 // Presence notification will form a canonical uri to
3130 // look for callbacks into the application.
3133 OICFree(resourceUri);
3135 resourceUri = presenceUri;
3139 // update resourceUri onto requestInfo after check presence uri
3140 requestInfo.info.resourceUri = resourceUri;
3142 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3143 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3144 method, devAddr, resourceUri, resourceType, ttl);
3145 if (OC_STACK_OK != result)
3150 cbData = NULL; // Client CB list entry now owns it
3151 token = NULL; // Client CB list entry now owns it
3152 devAddr = NULL; // Client CB list entry now owns it
3153 resourceUri = NULL; // Client CB list entry now owns it
3154 resourceType = NULL; // Client CB list entry now owns it
3156 #ifdef WITH_PRESENCE
3157 if (method == OC_REST_PRESENCE)
3159 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3163 *handle = resHandle;
3165 #ifdef WITH_PROCESS_EVENT
3166 OCSendProcessEventSignal();
3167 #endif // WITH_PROCESS_EVENT
3174 result = OCSendRequest(&endpoint, &requestInfo);
3175 if (OC_STACK_OK != result)
3182 *handle = resHandle;
3186 if (result != OC_STACK_OK)
3188 OIC_LOG(ERROR, TAG, "OCDoResource error");
3189 if (NULL != cbData && NULL != cbData->cd)
3191 cbData->cd(cbData->context);
3193 if (!clientCB) // token and resHandle associated with clientCB
3195 CADestroyToken(token);
3200 FindAndDeleteClientCB(clientCB);
3208 OICFree(requestInfo.info.payload);
3210 OICFree(resourceUri);
3211 OICFree(resourceType);
3212 OICFree(requestInfo.info.options);
3217 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3221 * This ftn is implemented one of two ways in the case of observation:
3223 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3224 * Remove the callback associated on client side.
3225 * When the next notification comes in from server,
3226 * reply with RESET message to server.
3227 * Keep in mind that the server will react to RESET only
3228 * if the last notification was sent as CON
3230 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3231 * and it is associated with an observe request
3232 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3233 * Send CON Observe request to server with
3234 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3235 * Remove the callback associated on client side.
3237 OCStackResult ret = OC_STACK_OK;
3238 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3239 CARequestInfo_t requestInfo = {.method = CA_GET};
3243 return OC_STACK_INVALID_PARAM;
3246 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3249 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3250 return OC_STACK_ERROR;
3253 switch (clientCB->method)
3255 case OC_REST_OBSERVE:
3256 case OC_REST_OBSERVE_ALL:
3258 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3260 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3262 if (((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS) ||
3263 ((endpoint.adapter & CA_ADAPTER_TCP) && OC_LOW_QOS_WITH_TCP == qos))
3265 OIC_LOG_V(INFO, TAG, "the %s observe callback is removed", clientCB->requestUri);
3266 FindAndDeleteClientCB(clientCB);
3270 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3272 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3273 requestInfo.info.token = clientCB->token;
3274 requestInfo.info.tokenLength = clientCB->tokenLength;
3276 if (CreateObserveHeaderOption (&(requestInfo.info.options),
3277 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3279 return OC_STACK_ERROR;
3281 requestInfo.info.numOptions = numOptions + 1;
3282 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3285 ret = OCSendRequest(&endpoint, &requestInfo);
3287 if (requestInfo.info.options)
3289 OICFree (requestInfo.info.options);
3291 if (requestInfo.info.resourceUri)
3293 OICFree (requestInfo.info.resourceUri);
3298 case OC_REST_DISCOVER:
3299 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3300 clientCB->requestUri);
3301 FindAndDeleteClientCB(clientCB);
3304 #ifdef WITH_PRESENCE
3305 case OC_REST_PRESENCE:
3306 FindAndDeleteClientCB(clientCB);
3312 case OC_REST_DELETE:
3313 OIC_LOG_V(INFO, TAG, "Cancelling request callback for resource %s",
3314 clientCB->requestUri);
3315 FindAndDeleteClientCB(clientCB);
3319 ret = OC_STACK_INVALID_METHOD;
3327 * @brief Register Persistent storage callback.
3328 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3330 * OC_STACK_OK - No errors; Success
3331 * OC_STACK_INVALID_PARAM - Invalid parameter
3333 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3335 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3336 if(!persistentStorageHandler)
3338 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3339 return OC_STACK_INVALID_PARAM;
3343 if( !persistentStorageHandler->open ||
3344 !persistentStorageHandler->close ||
3345 !persistentStorageHandler->read ||
3346 !persistentStorageHandler->unlink ||
3347 !persistentStorageHandler->write)
3349 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3350 return OC_STACK_INVALID_PARAM;
3353 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3356 #ifdef WITH_PRESENCE
3358 #ifdef WITH_PROCESS_EVENT
3359 OCStackResult OCProcessPresence(uint32_t *nextEventTime)
3360 #else // WITH_PROCESS_EVENT
3361 OCStackResult OCProcessPresence(void)
3362 #endif // !WITH_PROCESS_EVENT
3364 OCStackResult result = OC_STACK_OK;
3366 // the following line floods the log with messages that are irrelevant
3367 // to most purposes. Uncomment as needed.
3368 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3369 ClientCB* cbNode = NULL;
3370 ClientCB* tempcbNode = NULL;
3371 OCClientResponse clientResponse;
3372 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3374 LL_FOREACH_SAFE(cbList, cbNode, tempcbNode)
3376 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3381 uint32_t now = GetTicks(0);
3382 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3383 cbNode->presence->TTLlevel);
3384 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3386 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3391 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3393 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3394 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3396 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3398 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3400 clientResponse.sequenceNumber = 0;
3401 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3402 clientResponse.devAddr = *cbNode->devAddr;
3403 FixUpClientResponse(&clientResponse);
3404 clientResponse.payload = NULL;
3406 // Increment the TTLLevel (going to a next state), so we don't keep
3407 // sending presence notification to client.
3408 cbNode->presence->TTLlevel++;
3409 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3410 cbNode->presence->TTLlevel);
3412 OIC_LOG(INFO, TAG, "Before calling into application address space for presence timeout");
3413 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3414 OIC_LOG(INFO, TAG, "After calling into application address space for presence timeout");
3416 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3418 FindAndDeleteClientCB(cbNode);
3423 uint32_t timeout = cbNode->presence->timeOut[cbNode->presence->TTLlevel];
3426 #ifdef WITH_PROCESS_EVENT
3427 if (nextEventTime && (timeout - now) < *nextEventTime)
3429 *nextEventTime = timeout - now;
3431 #endif // WITH_PROCESS_EVENT
3435 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3436 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3437 CARequestInfo_t requestInfo = {.method = CA_GET};
3439 OIC_LOG(DEBUG, TAG, "time to test server presence");
3441 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3443 requestData.type = CA_MSG_NONCONFIRM;
3444 requestData.token = cbNode->token;
3445 requestData.tokenLength = cbNode->tokenLength;
3446 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3447 requestInfo.method = CA_GET;
3448 requestInfo.info = requestData;
3450 result = OCSendRequest(&endpoint, &requestInfo);
3451 if (OC_STACK_OK != result)
3456 cbNode->presence->TTLlevel++;
3457 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3460 if (result != OC_STACK_OK)
3462 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3467 #endif // WITH_PRESENCE
3469 #ifdef WITH_PROCESS_EVENT
3470 OCStackResult OCProcess(void)
3472 uint32_t nextEventTime;
3473 return OCProcessEvent(&nextEventTime);
3476 OCStackResult OCProcessEvent(uint32_t *nextEventTime)
3478 if (stackState == OC_STACK_UNINITIALIZED)
3480 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3481 return OC_STACK_ERROR;
3484 *nextEventTime = UINT32_MAX;
3486 #ifdef WITH_PRESENCE
3487 OCProcessPresence(nextEventTime);
3488 OIC_LOG_V(INFO, TAG, "OCProcessPresence next event time : %u", *nextEventTime);
3490 CAHandleRequestResponse();
3493 #ifdef ROUTING_GATEWAY
3494 RMProcess(nextEventTime);
3498 OCProcessKeepAlive(nextEventTime);
3499 OIC_LOG_V(INFO, TAG, "OCProcessKeepAlive next event time : %u", *nextEventTime);
3504 void OCRegisterProcessEvent(oc_event event)
3506 g_ocProcessEvent = event;
3507 CARegisterProcessEvent(event);
3510 void OCSendProcessEventSignal(void)
3512 if (g_ocProcessEvent)
3514 oc_event_signal(g_ocProcessEvent);
3517 #else // WITH_PROCESS_EVENT
3519 OCStackResult OCProcess()
3521 if (stackState == OC_STACK_UNINITIALIZED)
3523 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3524 return OC_STACK_ERROR;
3526 #ifdef WITH_PRESENCE
3527 OCProcessPresence();
3529 CAHandleRequestResponse();
3531 #ifdef ROUTING_GATEWAY
3536 OCProcessKeepAlive();
3540 #endif // !WITH_PROCESS_EVENT
3542 #ifdef WITH_PRESENCE
3543 OCStackResult OCStartPresence(const uint32_t ttl)
3545 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3546 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3547 OCChangeResourceProperty(
3548 &(((OCResource *)presenceResource.handle)->resourceProperties),
3551 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3553 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3554 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3558 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3559 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3563 presenceResource.presenceTTL = ttl;
3566 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3569 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3571 presenceState = OC_PRESENCE_INITIALIZED;
3573 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3575 CAToken_t caToken = NULL;
3576 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3577 if (caResult != CA_STATUS_OK)
3579 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3580 CADestroyToken(caToken);
3581 return OC_STACK_ERROR;
3584 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3585 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3586 CADestroyToken(caToken);
3589 // Each time OCStartPresence is called
3590 // a different random 32-bit integer number is used
3591 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3593 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3594 OC_PRESENCE_TRIGGER_CREATE);
3597 OCStackResult OCStopPresence()
3599 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3600 OCStackResult result = OC_STACK_ERROR;
3602 if(presenceResource.handle)
3604 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3606 // make resource inactive
3607 result = OCChangeResourceProperty(
3608 &(((OCResource *) presenceResource.handle)->resourceProperties),
3612 if(result != OC_STACK_OK)
3615 "Changing the presence resource properties to ACTIVE not successful");
3619 return SendStopNotification();
3623 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3624 void* callbackParameter)
3626 defaultDeviceHandler = entityHandler;
3627 defaultDeviceHandlerCallbackParameter = callbackParameter;
3632 OCStackResult OCCreateResource(OCResourceHandle *handle,
3633 const char *resourceTypeName,
3634 const char *resourceInterfaceName,
3635 const char *uri, OCEntityHandler entityHandler,
3636 void* callbackParam,
3637 uint8_t resourceProperties)
3640 OCResource *pointer = NULL;
3641 OCStackResult result = OC_STACK_ERROR;
3643 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3645 if(myStackMode == OC_CLIENT)
3647 return OC_STACK_INVALID_PARAM;
3649 // Validate parameters
3650 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3652 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3653 return OC_STACK_INVALID_URI;
3655 // Is it presented during resource discovery?
3656 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3658 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3659 return OC_STACK_INVALID_PARAM;
3662 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3664 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3668 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3670 // Make sure resourceProperties bitmask has allowed properties specified
3671 if (resourceProperties
3672 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3673 OC_EXPLICIT_DISCOVERABLE
3682 OIC_LOG(ERROR, TAG, "Invalid property");
3683 return OC_STACK_INVALID_PARAM;
3686 // If the headResource is NULL, then no resources have been created...
3687 pointer = headResource;
3690 // At least one resources is in the resource list, so we need to search for
3691 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3694 if (pointer->uri && strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3696 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3697 return OC_STACK_INVALID_PARAM;
3699 pointer = pointer->next;
3702 // Create the pointer and insert it into the resource list
3703 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3706 result = OC_STACK_NO_MEMORY;
3709 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3711 insertResource(pointer);
3714 pointer->uri = OICStrdup(uri);
3717 result = OC_STACK_NO_MEMORY;
3721 // Set properties. Set OC_ACTIVE
3722 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3725 // Add the resourcetype to the resource
3726 result = BindResourceTypeToResource(pointer, resourceTypeName);
3727 if (result != OC_STACK_OK)
3729 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3733 // Add the resourceinterface to the resource
3734 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3735 if (result != OC_STACK_OK)
3737 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3741 // If an entity handler has been passed, attach it to the newly created
3742 // resource. Otherwise, set the default entity handler.
3745 pointer->entityHandler = entityHandler;
3746 pointer->entityHandlerCallbackParam = callbackParam;
3750 pointer->entityHandler = defaultResourceEHandler;
3751 pointer->entityHandlerCallbackParam = NULL;
3754 // Initialize a pointer indicating child resources in case of collection
3755 pointer->rsrcChildResourcesHead = NULL;
3758 result = OC_STACK_OK;
3760 #ifdef WITH_PRESENCE
3761 if (presenceResource.handle)
3763 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3764 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3768 if (result != OC_STACK_OK)
3770 // Deep delete of resource and other dynamic elements that it contains
3771 deleteResource(pointer);
3776 OCStackResult OCBindResource(
3777 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3779 OCResource *resource = NULL;
3780 OCChildResource *tempChildResource = NULL;
3781 OCChildResource *newChildResource = NULL;
3783 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3785 // Validate parameters
3786 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3787 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3788 // Container cannot contain itself
3789 if (collectionHandle == resourceHandle)
3791 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3792 return OC_STACK_INVALID_PARAM;
3795 // Use the handle to find the resource in the resource linked list
3796 resource = findResource((OCResource *) collectionHandle);
3799 OIC_LOG(ERROR, TAG, "Collection handle not found");
3800 return OC_STACK_INVALID_PARAM;
3803 // Look for an open slot to add add the child resource.
3804 // If found, add it and return success
3806 tempChildResource = resource->rsrcChildResourcesHead;
3808 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3810 // TODO: what if one of child resource was deregistered without unbinding?
3811 tempChildResource = tempChildResource->next;
3814 // Do memory allocation for child resource
3815 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3816 if(!newChildResource)
3818 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3819 return OC_STACK_ERROR;
3822 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3823 newChildResource->next = NULL;
3825 if(!resource->rsrcChildResourcesHead)
3827 resource->rsrcChildResourcesHead = newChildResource;
3830 tempChildResource->next = newChildResource;
3833 OIC_LOG(INFO, TAG, "resource bound");
3835 #ifdef WITH_PRESENCE
3836 if (presenceResource.handle)
3838 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3839 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3840 OC_PRESENCE_TRIGGER_CHANGE);
3847 OCStackResult OCUnBindResource(
3848 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3850 OCResource *resource = NULL;
3851 OCChildResource *tempChildResource = NULL;
3852 OCChildResource *tempLastChildResource = NULL;
3854 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3856 // Validate parameters
3857 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3858 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3859 // Container cannot contain itself
3860 if (collectionHandle == resourceHandle)
3862 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3863 return OC_STACK_INVALID_PARAM;
3866 // Use the handle to find the resource in the resource linked list
3867 resource = findResource((OCResource *) collectionHandle);
3870 OIC_LOG(ERROR, TAG, "Collection handle not found");
3871 return OC_STACK_INVALID_PARAM;
3874 // Look for an open slot to add add the child resource.
3875 // If found, add it and return success
3876 if(!resource->rsrcChildResourcesHead)
3878 OIC_LOG(INFO, TAG, "resource not found in collection");
3880 // Unable to add resourceHandle, so return error
3881 return OC_STACK_ERROR;
3885 tempChildResource = resource->rsrcChildResourcesHead;
3887 while (tempChildResource)
3889 if(tempChildResource->rsrcResource == resourceHandle)
3891 // if resource going to be unbinded is the head one.
3892 if( tempChildResource == resource->rsrcChildResourcesHead )
3894 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3895 OICFree(resource->rsrcChildResourcesHead);
3896 resource->rsrcChildResourcesHead = temp;
3901 OCChildResource *temp = tempChildResource->next;
3902 OICFree(tempChildResource);
3903 if (tempLastChildResource)
3905 tempLastChildResource->next = temp;
3910 OIC_LOG(INFO, TAG, "resource unbound");
3912 // Send notification when resource is unbounded successfully.
3913 #ifdef WITH_PRESENCE
3914 if (presenceResource.handle)
3916 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3917 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3918 OC_PRESENCE_TRIGGER_CHANGE);
3921 tempChildResource = NULL;
3922 tempLastChildResource = NULL;
3928 tempLastChildResource = tempChildResource;
3929 tempChildResource = tempChildResource->next;
3932 OIC_LOG(INFO, TAG, "resource not found in collection");
3934 tempChildResource = NULL;
3935 tempLastChildResource = NULL;
3937 // Unable to add resourceHandle, so return error
3938 return OC_STACK_ERROR;
3941 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3943 if (!resourceItemName)
3947 // Per RFC 6690 only registered values must follow the first rule below.
3948 // At this point in time the only values registered begin with "core", and
3949 // all other values are specified as opaque strings where multiple values
3950 // are separated by a space.
3951 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3953 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3955 if (resourceItemName[index] != '.'
3956 && resourceItemName[index] != '-'
3957 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3958 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3966 for (size_t index = 0; resourceItemName[index]; ++index)
3968 if (resourceItemName[index] == ' '
3969 || resourceItemName[index] == '\t'
3970 || resourceItemName[index] == '\r'
3971 || resourceItemName[index] == '\n')
3981 OCStackResult BindResourceTypeToResource(OCResource* resource,
3982 const char *resourceTypeName)
3984 OCResourceType *pointer = NULL;
3986 OCStackResult result = OC_STACK_ERROR;
3988 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3990 if (!ValidateResourceTypeInterface(resourceTypeName))
3992 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3993 return OC_STACK_INVALID_PARAM;
3996 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3999 result = OC_STACK_NO_MEMORY;
4003 str = OICStrdup(resourceTypeName);
4006 result = OC_STACK_NO_MEMORY;
4009 pointer->resourcetypename = str;
4010 pointer->next = NULL;
4012 insertResourceType(resource, pointer);
4013 result = OC_STACK_OK;
4016 if (result != OC_STACK_OK)
4025 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
4026 const char *resourceInterfaceName)
4028 OCResourceInterface *pointer = NULL;
4030 OCStackResult result = OC_STACK_ERROR;
4032 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
4034 if (!ValidateResourceTypeInterface(resourceInterfaceName))
4036 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
4037 return OC_STACK_INVALID_PARAM;
4040 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
4042 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
4045 result = OC_STACK_NO_MEMORY;
4049 str = OICStrdup(resourceInterfaceName);
4052 result = OC_STACK_NO_MEMORY;
4055 pointer->name = str;
4057 // Bind the resourceinterface to the resource
4058 insertResourceInterface(resource, pointer);
4060 result = OC_STACK_OK;
4063 if (result != OC_STACK_OK)
4072 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
4073 const char *resourceTypeName)
4076 OCStackResult result = OC_STACK_ERROR;
4077 OCResource *resource = NULL;
4079 resource = findResource((OCResource *) handle);
4082 OIC_LOG(ERROR, TAG, "Resource not found");
4083 return OC_STACK_ERROR;
4086 result = BindResourceTypeToResource(resource, resourceTypeName);
4088 #ifdef WITH_PRESENCE
4089 if(presenceResource.handle)
4091 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4092 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4099 OCStackResult OCResetResourceTypes(OCResourceHandle handle,
4100 const char *newResourceType)
4102 OCStackResult result = OC_STACK_ERROR;
4103 OCResource *resource = NULL;
4105 resource = findResource((OCResource *) handle);
4108 OIC_LOG(ERROR, TAG, "Resource not found");
4109 return OC_STACK_ERROR;
4112 // Clear all bound resource types
4113 deleteResourceType(resource->rsrcType);
4114 resource->rsrcType = NULL;
4116 // Bind new resource type to resource
4117 result = BindResourceTypeToResource(resource, newResourceType);
4119 #ifdef WITH_PRESENCE
4120 if(presenceResource.handle)
4122 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4123 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4130 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
4131 const char *resourceInterfaceName)
4134 OCStackResult result = OC_STACK_ERROR;
4135 OCResource *resource = NULL;
4137 resource = findResource((OCResource *) handle);
4140 OIC_LOG(ERROR, TAG, "Resource not found");
4141 return OC_STACK_ERROR;
4144 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
4146 #ifdef WITH_PRESENCE
4147 if (presenceResource.handle)
4149 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4150 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4157 OCStackResult OCResetResourceInterfaces(OCResourceHandle handle,
4158 const char *newResourceInterface)
4160 OCStackResult result = OC_STACK_ERROR;
4161 OCResource *resource = NULL;
4163 resource = findResource((OCResource *) handle);
4166 OIC_LOG(ERROR, TAG, "Resource not found");
4167 return OC_STACK_ERROR;
4170 // Clear all bound interface
4171 deleteResourceInterface(resource->rsrcInterface);
4172 resource->rsrcInterface = NULL;
4174 // Bind new interface to resource
4175 result = BindResourceInterfaceToResource(resource, newResourceInterface);
4177 #ifdef WITH_PRESENCE
4178 if (presenceResource.handle)
4180 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4181 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4188 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
4190 OCResource *pointer = headResource;
4192 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
4196 *numResources = *numResources + 1;
4197 pointer = pointer->next;
4202 OCResourceHandle OCGetResourceHandle(uint8_t index)
4204 OCResource *pointer = headResource;
4206 for( uint8_t i = 0; i < index && pointer; ++i)
4208 pointer = pointer->next;
4210 return (OCResourceHandle) pointer;
4213 OCStackResult OCDeleteResource(OCResourceHandle handle)
4217 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4218 return OC_STACK_INVALID_PARAM;
4221 OCResource *resource = findResource((OCResource *) handle);
4222 if (resource == NULL)
4224 OIC_LOG(ERROR, TAG, "Resource not found");
4225 return OC_STACK_NO_RESOURCE;
4228 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4230 OIC_LOG(ERROR, TAG, "Error deleting resource");
4231 return OC_STACK_ERROR;
4237 const char *OCGetResourceUri(OCResourceHandle handle)
4239 OCResource *resource = NULL;
4241 resource = findResource((OCResource *) handle);
4244 return resource->uri;
4246 return (const char *) NULL;
4249 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4251 OCResource *resource = NULL;
4253 resource = findResource((OCResource *) handle);
4256 return resource->resourceProperties;
4258 return (OCResourceProperty)-1;
4261 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4262 uint8_t *numResourceTypes)
4264 OCResource *resource = NULL;
4265 OCResourceType *pointer = NULL;
4267 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4268 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4270 *numResourceTypes = 0;
4272 resource = findResource((OCResource *) handle);
4275 pointer = resource->rsrcType;
4278 *numResourceTypes = *numResourceTypes + 1;
4279 pointer = pointer->next;
4285 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4287 OCResourceType *resourceType = NULL;
4289 resourceType = findResourceTypeAtIndex(handle, index);
4292 return resourceType->resourcetypename;
4294 return (const char *) NULL;
4297 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4298 uint8_t *numResourceInterfaces)
4300 OCResourceInterface *pointer = NULL;
4301 OCResource *resource = NULL;
4303 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4304 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4306 *numResourceInterfaces = 0;
4307 resource = findResource((OCResource *) handle);
4310 pointer = resource->rsrcInterface;
4313 *numResourceInterfaces = *numResourceInterfaces + 1;
4314 pointer = pointer->next;
4320 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4322 OCResourceInterface *resourceInterface = NULL;
4324 resourceInterface = findResourceInterfaceAtIndex(handle, index);
4325 if (resourceInterface)
4327 return resourceInterface->name;
4329 return (const char *) NULL;
4332 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4335 OCResource *resource = NULL;
4336 OCChildResource *tempChildResource = NULL;
4339 resource = findResource((OCResource *) collectionHandle);
4345 tempChildResource = resource->rsrcChildResourcesHead;
4347 while(tempChildResource)
4351 return tempChildResource->rsrcResource;
4354 tempChildResource = tempChildResource->next;
4357 // In this case, the number of resource handles in the collection exceeds the index
4358 tempChildResource = NULL;
4362 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4363 OCEntityHandler entityHandler,
4364 void* callbackParam)
4366 OCResource *resource = NULL;
4368 // Validate parameters
4369 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4371 // Use the handle to find the resource in the resource linked list
4372 resource = findResource((OCResource *)handle);
4375 OIC_LOG(ERROR, TAG, "Resource not found");
4376 return OC_STACK_ERROR;
4380 resource->entityHandler = entityHandler;
4381 resource->entityHandlerCallbackParam = callbackParam;
4383 #ifdef WITH_PRESENCE
4384 if (presenceResource.handle)
4386 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4387 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4394 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4396 OCResource *resource = NULL;
4398 resource = findResource((OCResource *)handle);
4401 OIC_LOG(ERROR, TAG, "Resource not found");
4406 return resource->entityHandler;
4409 void incrementSequenceNumber(OCResource * resPtr)
4411 // Increment the sequence number
4412 resPtr->sequenceNum += 1;
4413 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4415 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4420 #ifdef WITH_PRESENCE
4421 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4422 OCPresenceTrigger trigger)
4424 OIC_LOG(INFO, TAG, "SendPresenceNotification");
4425 OCResource *resPtr = NULL;
4426 OCStackResult result = OC_STACK_ERROR;
4427 OCMethod method = OC_REST_PRESENCE;
4428 uint32_t maxAge = 0;
4429 resPtr = findResource((OCResource *) presenceResource.handle);
4432 return OC_STACK_NO_RESOURCE;
4435 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4437 maxAge = presenceResource.presenceTTL;
4439 result = SendAllObserverNotification(method, resPtr, maxAge,
4440 trigger, resourceType, OC_LOW_QOS);
4446 OCStackResult SendStopNotification()
4448 OIC_LOG(INFO, TAG, "SendStopNotification");
4449 OCResource *resPtr = NULL;
4450 OCStackResult result = OC_STACK_ERROR;
4451 OCMethod method = OC_REST_PRESENCE;
4452 resPtr = findResource((OCResource *) presenceResource.handle);
4455 return OC_STACK_NO_RESOURCE;
4458 // maxAge is 0. ResourceType is NULL.
4459 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4465 #endif // WITH_PRESENCE
4466 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4468 OCResource *resPtr = NULL;
4469 OCStackResult result = OC_STACK_ERROR;
4470 OCMethod method = OC_REST_NOMETHOD;
4471 uint32_t maxAge = 0;
4473 OIC_LOG(INFO, TAG, "Notifying all observers");
4474 #ifdef WITH_PRESENCE
4475 if(handle == presenceResource.handle)
4479 #endif // WITH_PRESENCE
4480 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4482 // Verify that the resource exists
4483 resPtr = findResource ((OCResource *) handle);
4486 return OC_STACK_NO_RESOURCE;
4490 //only increment in the case of regular observing (not presence)
4491 incrementSequenceNumber(resPtr);
4492 method = OC_REST_OBSERVE;
4493 maxAge = MAX_OBSERVE_AGE;
4494 #ifdef WITH_PRESENCE
4495 result = SendAllObserverNotification (method, resPtr, maxAge,
4496 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4498 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4505 OCNotifyListOfObservers (OCResourceHandle handle,
4506 OCObservationId *obsIdList,
4507 uint8_t numberOfIds,
4508 const OCRepPayload *payload,
4509 OCQualityOfService qos)
4511 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4513 OCResource *resPtr = NULL;
4514 //TODO: we should allow the server to define this
4515 uint32_t maxAge = MAX_OBSERVE_AGE;
4517 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4518 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4519 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4521 resPtr = findResource ((OCResource *) handle);
4522 if (NULL == resPtr || myStackMode == OC_CLIENT)
4524 return OC_STACK_NO_RESOURCE;
4528 incrementSequenceNumber(resPtr);
4530 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4531 payload, maxAge, qos));
4534 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4536 OIC_TRACE_BEGIN(%s:OCDoResponse, TAG);
4537 OCStackResult result = OC_STACK_ERROR;
4538 OCServerRequest *serverRequest = NULL;
4540 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4542 // Validate input parameters
4543 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4544 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4547 // Get pointer to request info
4548 serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
4551 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4552 result = serverRequest->ehResponseHandler(ehResponse);
4559 //#ifdef DIRECT_PAIRING
4560 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4562 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4563 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4565 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4569 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4572 const OCDPDev_t* OCGetDirectPairedDevices()
4574 return (const OCDPDev_t*)DPGetPairedDevices();
4577 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4578 OCDirectPairingCB resultCallback)
4580 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4581 if(NULL == peer || NULL == pinNumber)
4583 OIC_LOG(ERROR, TAG, "Invalid parameters");
4584 return OC_STACK_INVALID_PARAM;
4586 if (NULL == resultCallback)
4588 OIC_LOG(ERROR, TAG, "Invalid callback");
4589 return OC_STACK_INVALID_CALLBACK;
4592 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4593 pinNumber, (OCDirectPairingResultCB)resultCallback);
4595 //#endif // DIRECT_PAIRING
4597 //-----------------------------------------------------------------------------
4598 // Private internal function definitions
4599 //-----------------------------------------------------------------------------
4600 static OCDoHandle GenerateInvocationHandle()
4602 OCDoHandle handle = NULL;
4603 // Generate token here, it will be deleted when the transaction is deleted
4604 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4607 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4613 #ifdef WITH_PRESENCE
4614 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4615 OCResourceProperty resourceProperties, uint8_t enable)
4619 return OC_STACK_INVALID_PARAM;
4621 if (resourceProperties
4622 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4624 OIC_LOG(ERROR, TAG, "Invalid property");
4625 return OC_STACK_INVALID_PARAM;
4629 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4633 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4639 OCStackResult initResources()
4641 OCStackResult result = OC_STACK_OK;
4643 headResource = NULL;
4644 tailResource = NULL;
4645 // Init Virtual Resources
4646 #ifdef WITH_PRESENCE
4647 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4649 result = OCCreateResource(&presenceResource.handle,
4650 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4652 OC_RSRVD_PRESENCE_URI,
4656 //make resource inactive
4657 result = OCChangeResourceProperty(
4658 &(((OCResource *) presenceResource.handle)->resourceProperties),
4661 #ifndef WITH_ARDUINO
4662 if (result == OC_STACK_OK)
4664 result = SRMInitSecureResources();
4668 if(result == OC_STACK_OK)
4670 CreateResetProfile();
4671 result = OCCreateResource(&deviceResource,
4672 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4673 OC_RSRVD_INTERFACE_DEFAULT,
4674 OC_RSRVD_DEVICE_URI,
4678 if(result == OC_STACK_OK)
4680 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4681 OC_RSRVD_INTERFACE_READ);
4685 if(result == OC_STACK_OK)
4687 result = OCCreateResource(&platformResource,
4688 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4689 OC_RSRVD_INTERFACE_DEFAULT,
4690 OC_RSRVD_PLATFORM_URI,
4694 if(result == OC_STACK_OK)
4696 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4697 OC_RSRVD_INTERFACE_READ);
4704 void insertResource(OCResource *resource)
4708 headResource = resource;
4709 tailResource = resource;
4713 tailResource->next = resource;
4714 tailResource = resource;
4716 resource->next = NULL;
4719 OCResource *findResource(OCResource *resource)
4721 OCResource *pointer = headResource;
4725 if (pointer == resource)
4729 pointer = pointer->next;
4734 void deleteAllResources()
4736 OCResource *pointer = headResource;
4737 OCResource *temp = NULL;
4741 temp = pointer->next;
4742 #ifdef WITH_PRESENCE
4743 if (pointer != (OCResource *) presenceResource.handle)
4745 #endif // WITH_PRESENCE
4746 deleteResource(pointer);
4747 #ifdef WITH_PRESENCE
4749 #endif // WITH_PRESENCE
4752 memset(&platformResource, 0, sizeof(platformResource));
4753 memset(&deviceResource, 0, sizeof(deviceResource));
4755 memset(&brokerResource, 0, sizeof(brokerResource));
4758 SRMDeInitSecureResources();
4760 #ifdef WITH_PRESENCE
4761 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4762 // presence notification attributed to their deletion to be processed.
4763 deleteResource((OCResource *) presenceResource.handle);
4764 memset(&presenceResource, 0, sizeof(presenceResource));
4765 #endif // WITH_PRESENCE
4768 OCStackResult deleteResource(OCResource *resource)
4770 OCResource *prev = NULL;
4771 OCResource *temp = NULL;
4774 OIC_LOG(DEBUG,TAG,"resource is NULL");
4775 return OC_STACK_INVALID_PARAM;
4778 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4780 temp = headResource;
4783 if (temp == resource)
4785 // Invalidate all Resource Properties.
4786 resource->resourceProperties = (OCResourceProperty) 0;
4787 #ifdef WITH_PRESENCE
4788 if(resource != (OCResource *) presenceResource.handle)
4790 #endif // WITH_PRESENCE
4791 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4792 #ifdef WITH_PRESENCE
4795 if(presenceResource.handle)
4797 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4798 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4801 // Delete resource's all observers
4802 DeleteObserverUsingResource(resource);
4804 // Only resource in list.
4805 if (temp == headResource && temp == tailResource)
4807 headResource = NULL;
4808 tailResource = NULL;
4811 else if (temp == headResource)
4813 headResource = temp->next;
4816 else if (temp == tailResource && prev)
4818 tailResource = prev;
4819 tailResource->next = NULL;
4823 prev->next = temp->next;
4826 deleteResourceElements(temp);
4837 return OC_STACK_ERROR;
4840 void deleteResourceElements(OCResource *resource)
4849 OICFree(resource->uri);
4850 resource->uri = NULL;
4852 if (resource->rsrcType)
4854 deleteResourceType(resource->rsrcType);
4855 resource->rsrcType = NULL;
4857 if (resource->rsrcInterface)
4859 deleteResourceInterface(resource->rsrcInterface);
4860 resource->rsrcInterface = NULL;
4862 if (resource->rsrcChildResourcesHead)
4864 unbindChildResources(resource->rsrcChildResourcesHead);
4865 resource->rsrcChildResourcesHead = NULL;
4867 if (resource->rsrcAttributes)
4869 OCDeleteResourceAttributes(resource->rsrcAttributes);
4870 resource->rsrcAttributes = NULL;
4873 resource->entityHandler = NULL;
4877 void deleteResourceType(OCResourceType *resourceType)
4879 OCResourceType *next = NULL;
4881 for (OCResourceType *pointer = resourceType; pointer; pointer = next)
4883 next = pointer->next ? pointer->next : NULL;
4884 if (pointer->resourcetypename)
4886 OICFree(pointer->resourcetypename);
4887 pointer->resourcetypename = NULL;
4893 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4895 OCResourceInterface *next = NULL;
4896 for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
4898 next = pointer->next ? pointer->next : NULL;
4901 OICFree(pointer->name);
4902 pointer->name = NULL;
4908 void unbindChildResources(OCChildResource *head)
4910 OCChildResource *next = NULL;
4911 for (OCChildResource *current = head; current; current = next)
4913 next = current->next;
4918 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
4920 OCAttribute *next = NULL;
4921 for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
4923 next = pointer->next ? pointer->next : NULL;
4924 if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
4926 OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
4927 pointer->attrValue = NULL;
4929 else if (pointer->attrValue)
4931 OICFree(pointer->attrValue);
4932 pointer->attrValue = NULL;
4934 if (pointer->attrName)
4936 OICFree(pointer->attrName);
4937 pointer->attrName = NULL;
4943 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4945 OCResourceType *pointer = NULL;
4946 OCResourceType *previous = NULL;
4947 if (!resource || !resourceType)
4951 // resource type list is empty.
4952 else if (!resource->rsrcType)
4954 resource->rsrcType = resourceType;
4958 pointer = resource->rsrcType;
4962 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4964 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4965 OICFree(resourceType->resourcetypename);
4966 OICFree(resourceType);
4970 pointer = pointer->next;
4975 previous->next = resourceType;
4978 resourceType->next = NULL;
4980 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4983 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4985 OCResource *resource = NULL;
4986 OCResourceType *pointer = NULL;
4988 // Find the specified resource
4989 resource = findResource((OCResource *) handle);
4995 // Make sure a resource has a resourcetype
4996 if (!resource->rsrcType)
5001 // Iterate through the list
5002 pointer = resource->rsrcType;
5003 for(uint8_t i = 0; i< index && pointer; ++i)
5005 pointer = pointer->next;
5010 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
5012 if(resourceTypeList && resourceTypeName)
5014 OCResourceType * rtPointer = resourceTypeList;
5015 while(resourceTypeName && rtPointer)
5017 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
5018 if(rtPointer->resourcetypename &&
5019 strcmp(resourceTypeName, (const char *)
5020 (rtPointer->resourcetypename)) == 0)
5024 rtPointer = rtPointer->next;
5032 * Insert a new interface into interface linked list only if not already present.
5033 * If alredy present, 2nd arg is free'd.
5034 * Default interface will always be first if present.
5036 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
5038 OCResourceInterface *pointer = NULL;
5039 OCResourceInterface *previous = NULL;
5041 newInterface->next = NULL;
5043 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
5045 if (!*firstInterface)
5047 // If first interface is not oic.if.baseline, by default add it as first interface type.
5048 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
5050 *firstInterface = newInterface;
5054 OCStackResult result = BindResourceInterfaceToResource(resource,
5055 OC_RSRVD_INTERFACE_DEFAULT);
5056 if (result != OC_STACK_OK)
5058 OICFree(newInterface->name);
5059 OICFree(newInterface);
5062 if (*firstInterface)
5064 (*firstInterface)->next = newInterface;
5068 // If once add oic.if.baseline, later too below code take care of freeing memory.
5069 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5071 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5073 OICFree(newInterface->name);
5074 OICFree(newInterface);
5077 // This code will not hit anymore, keeping
5080 newInterface->next = *firstInterface;
5081 *firstInterface = newInterface;
5086 pointer = *firstInterface;
5089 if (strcmp(newInterface->name, pointer->name) == 0)
5091 OICFree(newInterface->name);
5092 OICFree(newInterface);
5096 pointer = pointer->next;
5101 previous->next = newInterface;
5106 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
5109 OCResource *resource = NULL;
5110 OCResourceInterface *pointer = NULL;
5112 // Find the specified resource
5113 resource = findResource((OCResource *) handle);
5119 // Make sure a resource has a resourceinterface
5120 if (!resource->rsrcInterface)
5125 // Iterate through the list
5126 pointer = resource->rsrcInterface;
5128 for (uint8_t i = 0; i < index && pointer; ++i)
5130 pointer = pointer->next;
5136 * This function splits the uri using the '?' delimiter.
5137 * "uriWithoutQuery" is the block of characters between the beginning
5138 * till the delimiter or '\0' which ever comes first.
5139 * "query" is whatever is to the right of the delimiter if present.
5140 * No delimiter sets the query to NULL.
5141 * If either are present, they will be malloc'ed into the params 2, 3.
5142 * The first param, *uri is left untouched.
5144 * NOTE: This function does not account for whitespace at the end of the uri NOR
5145 * malformed uri's with '??'. Whitespace at the end will be assumed to be
5146 * part of the query.
5148 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
5152 return OC_STACK_INVALID_URI;
5154 if(!query || !uriWithoutQuery)
5156 return OC_STACK_INVALID_PARAM;
5160 *uriWithoutQuery = NULL;
5162 size_t uriWithoutQueryLen = 0;
5163 size_t queryLen = 0;
5164 size_t uriLen = strlen(uri);
5166 char *pointerToDelimiter = strstr(uri, "?");
5168 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
5169 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
5171 if (uriWithoutQueryLen)
5173 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
5174 if (!*uriWithoutQuery)
5178 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
5182 *query = (char *) OICCalloc(queryLen + 1, 1);
5185 OICFree(*uriWithoutQuery);
5186 *uriWithoutQuery = NULL;
5189 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5195 return OC_STACK_NO_MEMORY;
5198 const char* OCGetServerInstanceIDString(void)
5200 static char sidStr[UUID_STRING_SIZE];
5202 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5204 OIC_LOG(FATAL, TAG, "GetDoxmDeviceID failed!");
5208 if (OCConvertUuidToString(sid.id, sidStr) != RAND_UUID_OK)
5210 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5217 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5219 OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5220 CAResult_t retResult = CA_STATUS_FAILED;
5221 CAResult_t caResult = CA_STATUS_OK;
5223 CATransportAdapter_t connTypes[] = {
5225 CA_ADAPTER_RFCOMM_BTEDR,
5226 CA_ADAPTER_GATT_BTLE,
5229 ,CA_ADAPTER_REMOTE_ACCESS
5236 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5238 for(int i = 0; i < numConnTypes; i++)
5240 // If CA status is not initialized, CASelectNetwork() will not be called.
5241 if (caResult != CA_STATUS_NOT_INITIALIZED)
5243 if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5245 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5246 caResult = CASelectNetwork(connTypes[i]);
5247 if (caResult == CA_STATUS_OK)
5249 retResult = CA_STATUS_OK;
5254 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5259 if (retResult != CA_STATUS_OK)
5261 return caResult; // Returns error of appropriate transport that failed fatally.
5267 OCStackResult CAResultToOCResult(CAResult_t caResult)
5273 case CA_STATUS_INVALID_PARAM:
5274 return OC_STACK_INVALID_PARAM;
5275 case CA_ADAPTER_NOT_ENABLED:
5276 return OC_STACK_ADAPTER_NOT_ENABLED;
5277 case CA_SERVER_STARTED_ALREADY:
5279 case CA_SERVER_NOT_STARTED:
5280 return OC_STACK_ERROR;
5281 case CA_DESTINATION_NOT_REACHABLE:
5282 return OC_STACK_COMM_ERROR;
5283 case CA_SOCKET_OPERATION_FAILED:
5284 return OC_STACK_COMM_ERROR;
5285 case CA_SEND_FAILED:
5286 return OC_STACK_COMM_ERROR;
5287 case CA_RECEIVE_FAILED:
5288 return OC_STACK_COMM_ERROR;
5289 case CA_MEMORY_ALLOC_FAILED:
5290 return OC_STACK_NO_MEMORY;
5291 case CA_REQUEST_TIMEOUT:
5292 return OC_STACK_TIMEOUT;
5293 case CA_DESTINATION_DISCONNECTED:
5294 return OC_STACK_COMM_ERROR;
5295 case CA_STATUS_FAILED:
5296 return OC_STACK_ERROR;
5297 case CA_NOT_SUPPORTED:
5298 return OC_STACK_NOTIMPL;
5300 return OC_STACK_ERROR;
5304 bool OCResultToSuccess(OCStackResult ocResult)
5309 case OC_STACK_RESOURCE_CREATED:
5310 case OC_STACK_RESOURCE_DELETED:
5311 case OC_STACK_CONTINUE:
5312 case OC_STACK_RESOURCE_CHANGED:
5313 case OC_STACK_SLOW_RESOURCE:
5321 OCStackResult OCSetProxyURI(const char *uri)
5323 return CAResultToOCResult(CASetProxyUri(uri));
5327 #if defined(RD_CLIENT) || defined(RD_SERVER)
5328 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5330 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5332 OCResource *resource = NULL;
5334 resource = findResource((OCResource *) handle);
5337 OIC_LOG(ERROR, TAG, "Resource not found");
5338 return OC_STACK_ERROR;
5341 resource->ins = ins;
5347 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5348 const OCClientResponse *response)
5350 // Validate input parameters
5351 VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5352 VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5354 char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5357 return OC_STACK_NO_MEMORY;
5359 strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5361 if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5363 OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5365 char rdPubUri[MAX_URI_LENGTH] = { 0 };
5366 snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5367 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5369 if (strcmp(rdPubUri, targetUri) == 0)
5371 // Update resource unique id in stack.
5374 if (response->payload)
5376 OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5377 OCRepPayload **links = NULL;
5378 size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5379 if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5380 &links, dimensions))
5383 for (; i < dimensions[0]; i++)
5386 if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5388 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5390 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5392 OCBindResourceInsToResource(handle, ins);
5401 size_t count = calcDimTotal(dimensions);
5402 for (size_t k = 0; k < count; k++)
5404 OCRepPayloadDestroy(links[k]);
5412 else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5414 OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5416 uint8_t numResources = 0;
5417 OCGetNumberOfResources(&numResources);
5419 char *ins = strstr(targetUri, OC_RSRVD_INS);
5422 for (uint8_t i = 0; i < numResources; i++)
5424 OCResourceHandle resHandle = OCGetResourceHandle(i);
5427 OCBindResourceInsToResource(resHandle, 0);
5433 const char *token = "&";
5434 char *iterTokenPtr = NULL;
5435 char *start = strtok_r(targetUri, token, &iterTokenPtr);
5437 while (start != NULL)
5439 char *query = start;
5440 query = strstr(query, OC_RSRVD_INS);
5443 int64_t queryIns = atoi(query + 4);
5444 for (uint8_t i = 0; i < numResources; i++)
5446 OCResourceHandle resHandle = OCGetResourceHandle(i);
5450 OCGetResourceIns(resHandle, &resIns);
5451 if (queryIns && queryIns == resIns)
5453 OCBindResourceInsToResource(resHandle, 0);
5459 start = strtok_r(NULL, token, &iterTokenPtr);
5468 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5472 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5476 OCResource *pointer = headResource;
5480 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5482 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5485 pointer = pointer->next;
5490 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t *ins)
5492 OCResource *resource = NULL;
5494 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5495 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5497 resource = findResource((OCResource *) handle);
5500 *ins = resource->ins;
5503 return OC_STACK_ERROR;
5507 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5508 const void* optionData, size_t optionDataLength)
5512 OIC_LOG (INFO, TAG, "Header options are NULL");
5513 return OC_STACK_INVALID_PARAM;
5518 OIC_LOG (INFO, TAG, "optionData are NULL");
5519 return OC_STACK_INVALID_PARAM;
5524 OIC_LOG (INFO, TAG, "numOptions is NULL");
5525 return OC_STACK_INVALID_PARAM;
5528 if (*numOptions >= MAX_HEADER_OPTIONS)
5530 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5531 return OC_STACK_NO_MEMORY;
5534 ocHdrOpt += *numOptions;
5535 ocHdrOpt->protocolID = OC_COAP_ID;
5536 ocHdrOpt->optionID = optionID;
5537 ocHdrOpt->optionLength =
5538 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
5539 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5540 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5546 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5547 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5549 if (!ocHdrOpt || !numOptions)
5551 OIC_LOG (INFO, TAG, "No options present");
5557 OIC_LOG (INFO, TAG, "optionData are NULL");
5558 return OC_STACK_INVALID_PARAM;
5561 if (!receivedDataLength)
5563 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5564 return OC_STACK_INVALID_PARAM;
5567 for (uint8_t i = 0; i < numOptions; i++)
5569 if (ocHdrOpt[i].optionID == optionID)
5571 if (optionDataLength >= ocHdrOpt->optionLength)
5573 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5574 *receivedDataLength = ocHdrOpt->optionLength;
5579 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5580 return OC_STACK_ERROR;
5587 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5589 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5595 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5597 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5600 * If the client observes one or more resources over a reliable connection,
5601 * then the CoAP server (or intermediary in the role of the CoAP server)
5602 * MUST remove all entries associated with the client endpoint from the lists
5603 * of observers when the connection is either closed or times out.
5607 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5608 CopyEndpointToDevAddr(info, &devAddr);
5610 // remove observer list with remote device address.
5611 DeleteObserverUsingDevAddr(&devAddr);
5615 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5618 OCStackResult ret = OC_STACK_ERROR;
5620 ret = GetDoxmDeviceID(&oicUuid);
5621 if (OC_STACK_OK == ret)
5623 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5627 OIC_LOG(ERROR, TAG, "Device ID Get error");
5632 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5635 OCStackResult ret = OC_STACK_ERROR;
5637 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5638 for (int i = 0; i < UUID_LENGTH; i++)
5640 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5642 ret = SetDoxmDeviceID(&oicUuid);
5646 OCStackResult OCSetDeviceIdResetPF(const OCUUIdentity *deviceId)
5649 OCStackResult ret = OC_STACK_ERROR;
5651 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5652 char *strUuid = NULL;
5653 if (OC_STACK_OK == ConvertUuidToStr(&oicUuid, &strUuid))
5655 OIC_LOG_V(INFO, TAG, "%s: deviceId : %s" ,__func__, strUuid);
5660 OIC_LOG(DEBUG, TAG, "Can't convert deviceId to string");
5662 ret = SetDoxmDeviceIDResetPF(&oicUuid);
5666 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5668 bool isDeviceOwned = true;
5669 OCStackResult ret = OC_STACK_ERROR;
5671 ret = GetDoxmIsOwned(&isDeviceOwned);
5672 if (OC_STACK_OK == ret)
5674 *isOwned = isDeviceOwned;
5678 OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5683 OCStackResult OCGetDeviceOperationalState(bool* isOp)
5687 *isOp = GetPstatIsop();
5691 return OC_STACK_ERROR;
5694 void OCClearCallBackList()
5696 DeleteClientCBList();
5699 void OCClearObserverlist()
5701 DeleteObserverList();
5704 int OCEncrypt(const unsigned char *pt, size_t pt_len,
5705 unsigned char **ct, size_t *ct_len)
5707 #ifndef __SECURE_PSI__
5708 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5711 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5713 return psiEncrypt(pt, pt_len, ct, ct_len);
5714 #endif // __SECURE_PSI__
5717 int OCDecrypt(const unsigned char *ct, size_t ct_len,
5718 unsigned char **pt, size_t *pt_len)
5720 #ifndef __SECURE_PSI__
5721 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5724 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5726 return psiDecrypt(ct, ct_len, pt, pt_len);
5727 #endif // __SECURE_PSI__
5730 OCStackResult OCSetKey(const unsigned char* key)
5732 #ifndef __SECURE_PSI__
5733 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5736 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5738 return psiSetKey(key);
5739 #endif // __SECURE_PSI__
5742 OCStackResult OCGetKey(unsigned char* key)
5744 #ifndef __SECURE_PSI__
5745 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5748 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5750 return psiGetKey(key);
5751 #endif // __SECURE_PSI__
5754 OCStackResult OCSetSecurePSI(const unsigned char *key, const OCPersistentStorage *psPlain,
5755 const OCPersistentStorage *psEnc, const OCPersistentStorage *psRescue)
5757 #ifndef __SECURE_PSI__
5758 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5761 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5763 return setSecurePSI(key, psPlain, psEnc, psRescue);
5764 #endif // __SECURE_PSI__
5767 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5768 static void OtmEventHandler(const char *addr, uint16_t port, const char *uuid, int event)
5770 if (g_otmEventHandler.cb)
5772 g_otmEventHandler.cb(g_otmEventHandler.ctx, addr, port, uuid, event);
5777 * It is already declared in srmutility.h.
5778 * We can't include the header file, because of "redefined VERIFY_NON_NULL"
5780 typedef void (*OicSecOtmEventHandler_t)(const char* addr, uint16_t port,
5781 const char* uuid, int event);
5782 void SetOtmEventHandler(OicSecOtmEventHandler_t otmEventHandler);
5785 OCStackResult OCSetOtmEventHandler(void *ctx, OCOtmEventHandler cb)
5787 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5788 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5790 g_otmEventHandler.cb = cb;
5791 g_otmEventHandler.ctx = ctx;
5793 if (g_otmEventHandler.cb)
5795 OIC_LOG(DEBUG, TAG, "SET OCOtmEventHandler");
5796 SetOtmEventHandler(OtmEventHandler);
5800 OIC_LOG(DEBUG, TAG, "UNSET OCOtmEventHandler");
5801 SetOtmEventHandler(NULL);
5804 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);