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");
1850 ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1851 errorInfo->info.tokenLength);
1854 OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1855 OCStackResult result = CAResultToOCResult(errorInfo->result);
1856 if (OC_STACK_COMM_ERROR == result)
1858 OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1859 OC_OBSERVER_FAILED_COMM);
1863 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1868 * This function sends out Direct Stack Responses. These are responses that are not coming
1869 * from the application entity handler. These responses have no payload and are usually ACKs,
1870 * RESETs or some error conditions that were caught by the stack.
1872 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1873 const CAResponseResult_t responseResult, const CAMessageType_t type,
1874 const uint8_t numOptions, const CAHeaderOption_t *options,
1875 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1876 CADataType_t dataType)
1878 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1880 if (endPoint->flags & CA_MULTICAST)
1882 OIC_LOG(ERROR, TAG, "It is unnecessary to respond to a multicast request");
1886 CAResponseInfo_t respInfo = { .result = responseResult };
1887 respInfo.info.messageId = coapID;
1888 respInfo.info.numOptions = numOptions;
1890 if (respInfo.info.numOptions)
1892 respInfo.info.options =
1893 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1894 memcpy (respInfo.info.options, options,
1895 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1899 respInfo.info.payload = NULL;
1900 respInfo.info.token = token;
1901 respInfo.info.tokenLength = tokenLength;
1902 respInfo.info.type = type;
1903 respInfo.info.resourceUri = OICStrdup (resourceUri);
1904 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1905 respInfo.info.dataType = dataType;
1907 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1908 // Add the destination to route option from the endpoint->routeData.
1909 bool doPost = false;
1910 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1911 if(OC_STACK_OK != result)
1913 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1914 OICFree (respInfo.info.resourceUri);
1915 OICFree (respInfo.info.options);
1920 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1921 CARequestInfo_t reqInfo = {.method = CA_POST };
1922 /* The following initialization is not done in a single initializer block as in
1923 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1924 * does not have designated initalizers. This is a work-around for now.
1926 reqInfo.info.type = CA_MSG_NONCONFIRM;
1927 reqInfo.info.messageId = coapID;
1928 reqInfo.info.tokenLength = tokenLength;
1929 reqInfo.info.token = token;
1930 reqInfo.info.numOptions = respInfo.info.numOptions;
1931 reqInfo.info.payload = NULL;
1932 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1933 if (reqInfo.info.numOptions)
1935 reqInfo.info.options =
1936 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1937 if (NULL == reqInfo.info.options)
1939 OIC_LOG(ERROR, TAG, "Calloc failed");
1940 OICFree (reqInfo.info.resourceUri);
1941 OICFree (respInfo.info.resourceUri);
1942 OICFree (respInfo.info.options);
1943 return OC_STACK_NO_MEMORY;
1945 memcpy (reqInfo.info.options, respInfo.info.options,
1946 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1949 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1950 OICFree (reqInfo.info.resourceUri);
1951 OICFree (reqInfo.info.options);
1952 OICFree (respInfo.info.resourceUri);
1953 OICFree (respInfo.info.options);
1954 if (CA_STATUS_OK != caResult)
1956 OIC_LOG(ERROR, TAG, "CASendRequest error");
1957 return CAResultToOCResult(caResult);
1963 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1965 // resourceUri in the info field is cloned in the CA layer and
1966 // thus ownership is still here.
1967 OICFree (respInfo.info.resourceUri);
1968 OICFree (respInfo.info.options);
1969 if(CA_STATUS_OK != caResult)
1971 OIC_LOG(ERROR, TAG, "CASendResponse error");
1972 return CAResultToOCResult(caResult);
1975 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1979 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1981 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1982 OCStackResult result = OC_STACK_ERROR;
1983 if(!protocolRequest)
1985 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1986 return OC_STACK_INVALID_PARAM;
1989 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1990 protocolRequest->tokenLength);
1993 OIC_LOG(INFO, TAG, "This is a new Server Request");
1994 result = AddServerRequest(&request, protocolRequest->coapID,
1995 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1996 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1997 protocolRequest->observationOption, protocolRequest->qos,
1998 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1999 protocolRequest->payload, protocolRequest->requestToken,
2000 protocolRequest->tokenLength, protocolRequest->resourceUrl,
2001 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
2002 &protocolRequest->devAddr);
2003 if (OC_STACK_OK != result)
2005 OIC_LOG(ERROR, TAG, "Error adding server request");
2011 OIC_LOG(ERROR, TAG, "Out of Memory");
2012 return OC_STACK_NO_MEMORY;
2015 if(!protocolRequest->reqMorePacket)
2017 request->requestComplete = 1;
2020 OIC_LOG_V(WARNING, TAG, "Server request ID = [%u]", request->requestId);
2024 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
2025 return OC_STACK_DUPLICATE_REQUEST;
2028 if(request->requestComplete)
2030 OIC_LOG(INFO, TAG, "This Server Request is complete");
2031 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2032 OCResource *resource = NULL;
2033 result = DetermineResourceHandling (request, &resHandling, &resource);
2034 if (result == OC_STACK_OK)
2036 result = ProcessRequest(resHandling, resource, request);
2041 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2042 result = OC_STACK_CONTINUE;
2047 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2049 OIC_TRACE_MARK(%s:OCHandleRequests:%s, TAG, requestInfo->info.resourceUri);
2050 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2052 OCStackResult requestResult = OC_STACK_ERROR;
2054 if(myStackMode == OC_CLIENT)
2056 //TODO: should the client be responding to requests?
2060 OCServerProtocolRequest serverRequest = {0};
2062 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2064 char * uriWithoutQuery = NULL;
2065 char * query = NULL;
2067 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2069 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2071 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2074 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2075 OIC_LOG_V(INFO, TAG, "Query : %s", query);
2077 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2079 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2080 OICFree(uriWithoutQuery);
2084 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2085 OICFree(uriWithoutQuery);
2092 if(strlen(query) < MAX_QUERY_LENGTH)
2094 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2099 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2105 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2107 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2108 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2109 if (!serverRequest.payload)
2111 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2114 memcpy (serverRequest.payload, requestInfo->info.payload,
2115 requestInfo->info.payloadSize);
2119 serverRequest.reqTotalSize = 0;
2122 switch (requestInfo->method)
2125 serverRequest.method = OC_REST_GET;
2128 serverRequest.method = OC_REST_PUT;
2131 serverRequest.method = OC_REST_POST;
2134 serverRequest.method = OC_REST_DELETE;
2137 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2138 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2139 requestInfo->info.type, requestInfo->info.numOptions,
2140 requestInfo->info.options, requestInfo->info.token,
2141 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2143 OICFree(serverRequest.payload);
2147 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2148 requestInfo->info.tokenLength);
2150 serverRequest.tokenLength = requestInfo->info.tokenLength;
2151 if (serverRequest.tokenLength) {
2153 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2155 if (!serverRequest.requestToken)
2157 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2158 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2159 requestInfo->info.type, requestInfo->info.numOptions,
2160 requestInfo->info.options, requestInfo->info.token,
2161 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2163 OICFree(serverRequest.payload);
2166 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2169 switch (requestInfo->info.acceptFormat)
2171 case CA_FORMAT_APPLICATION_CBOR:
2172 serverRequest.acceptFormat = OC_FORMAT_CBOR;
2174 case CA_FORMAT_UNDEFINED:
2175 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2178 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2181 if (requestInfo->info.type == CA_MSG_CONFIRM)
2183 serverRequest.qos = OC_HIGH_QOS;
2187 serverRequest.qos = OC_LOW_QOS;
2189 // CA does not need the following field
2190 // Are we sure CA does not need them? how is it responding to multicast
2191 serverRequest.delayedResNeeded = 0;
2193 serverRequest.coapID = requestInfo->info.messageId;
2195 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2197 // copy vendor specific header options
2198 uint8_t tempNum = (requestInfo->info.numOptions);
2200 // Assume no observation requested and it is a pure GET.
2201 // If obs registration/de-registration requested it'll be fetched from the
2202 // options in GetObserveHeaderOption()
2203 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2205 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2206 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2209 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2210 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2211 requestInfo->info.type, requestInfo->info.numOptions,
2212 requestInfo->info.options, requestInfo->info.token,
2213 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2215 OICFree(serverRequest.payload);
2216 OICFree(serverRequest.requestToken);
2220 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2221 if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2223 serverRequest.rcvdVendorSpecificHeaderOptions = (OCHeaderOption*) OICCalloc(tempNum, sizeof(OCHeaderOption));
2224 if (NULL == serverRequest.rcvdVendorSpecificHeaderOptions)
2226 OIC_LOG(ERROR, TAG, "Failed to allocated memory to vnd header options!");
2227 OICFree(serverRequest.payload);
2228 OICFree(serverRequest.requestToken);
2232 memcpy (serverRequest.rcvdVendorSpecificHeaderOptions, requestInfo->info.options,
2233 sizeof(CAHeaderOption_t)*tempNum);
2236 requestResult = HandleStackRequests (&serverRequest);
2238 // Send ACK to client as precursor to slow response
2239 if (requestResult == OC_STACK_SLOW_RESOURCE)
2241 if (requestInfo->info.type == CA_MSG_CONFIRM)
2243 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2244 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2249 if (requestResult == OC_STACK_RESOURCE_ERROR
2250 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2252 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2255 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2257 if (requestResult == OC_STACK_RESOURCE_ERROR)
2259 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2261 else if (!OCResultToSuccess(requestResult))
2263 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2267 else if(!OCResultToSuccess(requestResult))
2269 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2271 // Delete observer node if it is OBSERVE failure from app
2272 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2274 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2277 CAResponseResult_t stackResponse =
2278 OCToCAStackResult(requestResult, serverRequest.method);
2280 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2281 requestInfo->info.type, requestInfo->info.numOptions,
2282 requestInfo->info.options, requestInfo->info.token,
2283 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2286 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2287 // The token is copied in there, and is thus still owned by this function.
2288 OICFree(serverRequest.payload);
2289 OICFree(serverRequest.requestToken);
2290 OICFree(serverRequest.rcvdVendorSpecificHeaderOptions);
2291 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2294 //This function will be called back by CA layer when a request is received
2295 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2297 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2298 OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2301 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2308 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2313 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2314 #ifdef ROUTING_GATEWAY
2315 bool needRIHandling = false;
2316 bool isEmptyMsg = false;
2318 * Routing manager is going to update either of endpoint or request or both.
2319 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2320 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2321 * destination. It can also remove "RM" coap header option before passing request / response to
2322 * RI as this option will make no sense to either RI or application.
2324 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2325 &needRIHandling, &isEmptyMsg);
2326 if(OC_STACK_OK != ret || !needRIHandling)
2328 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2335 * Put source in sender endpoint so that the next packet from application can be routed to
2336 * proper destination and remove RM header option.
2338 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2339 (uint8_t *) &(requestInfo->info.numOptions),
2340 (CAEndpoint_t *) endPoint);
2342 #ifdef ROUTING_GATEWAY
2346 * In Gateways, the MSGType in route option is used to check if the actual
2347 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2348 * EMPTY response is sent in the form of POST request which need to be changed
2349 * to a EMPTY response by RM. This translation is done in this part of the code.
2351 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2352 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2353 .info.messageId = requestInfo->info.messageId,
2354 .info.type = CA_MSG_ACKNOWLEDGE};
2355 OCHandleResponse(endPoint, &respInfo);
2361 // Normal handling of the packet
2362 OCHandleRequests(endPoint, requestInfo);
2364 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2368 //-----------------------------------------------------------------------------
2370 //-----------------------------------------------------------------------------
2372 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2375 !raInfo->username ||
2376 !raInfo->hostname ||
2377 !raInfo->xmpp_domain)
2380 return OC_STACK_INVALID_PARAM;
2382 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2383 gRASetInfo = (result == OC_STACK_OK)? true : false;
2389 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2393 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2396 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2398 OC_UNUSED(serverFlags);
2399 OC_UNUSED(clientFlags);
2401 OIC_LOG(DEBUG, TAG, "call OCInit1");
2402 return OCInit2(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS, OC_DEFAULT_ADAPTER);
2405 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2406 OCTransportAdapter transportType)
2408 if(stackState == OC_STACK_INITIALIZED)
2410 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2411 OCStop() between them are ignored.");
2415 #ifndef ROUTING_GATEWAY
2416 if (OC_GATEWAY == mode)
2418 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2419 return OC_STACK_INVALID_PARAM;
2426 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2427 return OC_STACK_ERROR;
2431 OCStackResult result = OC_STACK_ERROR;
2432 OIC_LOG(INFO, TAG, "Entering OCInit");
2435 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2436 || (mode == OC_GATEWAY)))
2438 OIC_LOG(ERROR, TAG, "Invalid mode");
2439 return OC_STACK_ERROR;
2443 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2445 caglobals.client = true;
2447 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2449 caglobals.server = true;
2452 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2453 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2455 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2457 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2458 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2460 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2463 defaultDeviceHandler = NULL;
2464 defaultDeviceHandlerCallbackParameter = NULL;
2466 result = InitializeScheduleResourceList();
2467 VERIFY_SUCCESS(result, OC_STACK_OK);
2469 result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2470 VERIFY_SUCCESS(result, OC_STACK_OK);
2472 result = CAResultToOCResult(OCSelectNetwork(transportType));
2473 VERIFY_SUCCESS(result, OC_STACK_OK);
2475 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2476 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2477 VERIFY_SUCCESS(result, OC_STACK_OK);
2479 switch (myStackMode)
2482 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2483 result = CAResultToOCResult(CAStartDiscoveryServer());
2484 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2487 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2488 result = CAResultToOCResult(CAStartListeningServer());
2489 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2491 case OC_CLIENT_SERVER:
2493 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2494 result = CAResultToOCResult(CAStartListeningServer());
2495 if(result == OC_STACK_OK)
2497 result = CAResultToOCResult(CAStartDiscoveryServer());
2501 VERIFY_SUCCESS(result, OC_STACK_OK);
2504 CARegisterKeepAliveHandler(OCHandleKeepAliveConnCB);
2507 #ifdef WITH_PRESENCE
2508 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2509 #endif // WITH_PRESENCE
2511 //Update Stack state to initialized
2512 stackState = OC_STACK_INITIALIZED;
2514 // Initialize resource
2515 if(myStackMode != OC_CLIENT)
2517 result = initResources();
2520 // Initialize the SRM Policy Engine
2521 if(result == OC_STACK_OK)
2523 result = SRMInitPolicyEngine();
2524 // TODO after BeachHead delivery: consolidate into single SRMInit()
2526 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2527 RMSetStackMode(mode);
2528 #ifdef ROUTING_GATEWAY
2529 if (OC_GATEWAY == myStackMode)
2531 result = RMInitialize();
2537 if (result == OC_STACK_OK)
2539 result = OCInitializeKeepAlive(myStackMode);
2543 InitializeObserverList();
2546 if(result != OC_STACK_OK)
2548 OIC_LOG(ERROR, TAG, "Stack initialization error");
2549 TerminateScheduleResourceList();
2550 deleteAllResources();
2552 stackState = OC_STACK_UNINITIALIZED;
2557 OCStackResult OCStop()
2559 OIC_LOG(INFO, TAG, "Entering OCStop");
2561 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2563 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2566 else if (stackState != OC_STACK_INITIALIZED)
2568 OIC_LOG(INFO, TAG, "Stack not initialized");
2569 return OC_STACK_ERROR;
2572 // unset cautil config
2573 CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2574 CAUtilSetBTConfigure(configs);
2576 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2578 CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2579 OCDefaultConnectionStateChangedHandler);
2581 #ifdef WITH_PRESENCE
2582 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2583 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2584 presenceResource.presenceTTL = 0;
2585 presenceState = OC_PRESENCE_UNINITIALIZED;
2586 #endif // WITH_PRESENCE
2588 #ifdef ROUTING_GATEWAY
2589 if (OC_GATEWAY == myStackMode)
2596 OCTerminateKeepAlive(myStackMode);
2599 TerminateScheduleResourceList();
2600 // Remove all observers
2601 DeleteObserverList();
2602 // Free memory dynamically allocated for resources
2603 deleteAllResources();
2604 // Remove all the client callbacks
2605 DeleteClientCBList();
2606 // Terminate connectivity-abstraction layer.
2609 // De-init the SRM Policy Engine
2610 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2611 SRMDeInitPolicyEngine();
2613 // Destroy Observer List Mutex
2614 TerminateObserverList();
2616 stackState = OC_STACK_UNINITIALIZED;
2620 OCStackResult OCStartMulticastServer()
2622 if(stackState != OC_STACK_INITIALIZED)
2624 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2625 return OC_STACK_ERROR;
2627 CAResult_t ret = CAStartListeningServer();
2628 if (CA_STATUS_OK != ret)
2630 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2631 return OC_STACK_ERROR;
2636 OCStackResult OCStopMulticastServer()
2638 CAResult_t ret = CAStopListeningServer();
2639 if (CA_STATUS_OK != ret)
2641 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2642 return OC_STACK_ERROR;
2647 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2652 return CA_MSG_CONFIRM;
2657 return CA_MSG_NONCONFIRM;
2661 OCStackResult ParseRequestUri(const char *fullUri,
2662 OCTransportAdapter adapter,
2663 OCTransportFlags flags,
2664 OCDevAddr **devAddr,
2666 char **resourceType)
2668 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2670 OCStackResult result = OC_STACK_OK;
2671 OCDevAddr *da = NULL;
2675 // provide defaults for all returned values
2682 *resourceUri = NULL;
2686 *resourceType = NULL;
2689 // delimit url prefix, if any
2690 const char *start = fullUri;
2691 char *slash2 = strstr(start, "//");
2696 char *slash = strchr(start, '/');
2699 return OC_STACK_INVALID_URI;
2702 // process url scheme
2703 size_t prefixLen = slash2 - fullUri;
2707 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2708 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2714 // TODO: this logic should come in with unit tests exercising the various strings
2715 // processs url prefix, if any
2716 size_t urlLen = slash - start;
2720 if (urlLen && devAddr)
2721 { // construct OCDevAddr
2722 if (start[0] == '[')
2724 char *close = strchr(++start, ']');
2725 if (!close || close > slash)
2727 return OC_STACK_INVALID_URI;
2730 if (close[1] == ':')
2737 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2741 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2743 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2747 char *dot = strchr(start, '.');
2748 if (dot && dot < slash)
2750 colon = strchr(start, ':');
2751 end = (colon && colon < slash) ? colon : slash;
2756 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2760 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2762 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2770 if (len >= sizeof(da->addr))
2772 return OC_STACK_INVALID_URI;
2774 // collect port, if any
2775 if (colon && colon < slash)
2777 for (colon++; colon < slash; colon++)
2780 if (c < '0' || c > '9')
2782 return OC_STACK_INVALID_URI;
2784 port = 10 * port + c - '0';
2789 if (len >= sizeof(da->addr))
2791 return OC_STACK_INVALID_URI;
2794 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2797 return OC_STACK_NO_MEMORY;
2800 // Decode address per RFC 6874.
2801 result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2802 if (result != OC_STACK_OK)
2809 da->adapter = adapter;
2811 if (!strncmp(fullUri, "coaps", 5))
2813 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2818 // process resource uri, if any
2820 { // request uri and query
2821 size_t ulen = strlen(slash); // resource uri length
2822 size_t tlen = 0; // resource type length
2825 static const char strPresence[] = "/oic/ad?rt=";
2826 static const size_t lenPresence = sizeof(strPresence) - 1;
2827 if (!strncmp(slash, strPresence, lenPresence))
2829 type = slash + lenPresence;
2830 tlen = ulen - lenPresence;
2835 *resourceUri = (char *)OICMalloc(ulen + 1);
2838 result = OC_STACK_NO_MEMORY;
2841 OICStrcpy(*resourceUri, (ulen + 1), slash);
2844 if (type && resourceType)
2846 *resourceType = (char *)OICMalloc(tlen + 1);
2849 result = OC_STACK_NO_MEMORY;
2853 OICStrcpy(*resourceType, (tlen+1), type);
2860 // free all returned values
2867 OICFree(*resourceUri);
2871 OICFree(*resourceType);
2876 #ifdef WITH_PRESENCE
2877 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2881 char uri[CA_MAX_URI_LENGTH];
2883 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2885 *requestUri = OICStrdup(uri);
2888 return OC_STACK_NO_MEMORY;
2893 #endif // WITH_PRESENCE
2896 * Discover or Perform requests on a specified resource
2898 OCStackResult OCDoResource(OCDoHandle *handle,
2900 const char *requestUri,
2901 const OCDevAddr *destination,
2903 OCConnectivityType connectivityType,
2904 OCQualityOfService qos,
2905 OCCallbackData *cbData,
2906 OCHeaderOption *options,
2909 OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
2910 connectivityType, qos, cbData, options, numOptions);
2912 // This is the owner of the payload object, so we free it
2913 OCPayloadDestroy(payload);
2918 * Discover or Perform requests on a specified resource
2920 OCStackResult OCDoRequest(OCDoHandle *handle,
2922 const char *requestUri,
2923 const OCDevAddr *destination,
2925 OCConnectivityType connectivityType,
2926 OCQualityOfService qos,
2927 OCCallbackData *cbData,
2928 OCHeaderOption *options,
2931 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2932 OIC_TRACE_BEGIN(%s:OCDoRequest, TAG);
2934 // Validate input parameters
2935 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2936 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2938 OCStackResult result = OC_STACK_ERROR;
2939 CAResult_t caResult;
2940 CAToken_t token = NULL;
2941 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2942 ClientCB *clientCB = NULL;
2943 OCDoHandle resHandle = NULL;
2944 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2945 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2947 OCTransportAdapter adapter;
2948 OCTransportFlags flags;
2949 // the request contents are put here
2950 CARequestInfo_t requestInfo = {.method = CA_GET};
2951 // requestUri will be parsed into the following three variables
2952 OCDevAddr *devAddr = NULL;
2953 char *resourceUri = NULL;
2954 char *resourceType = NULL;
2957 * Support original behavior with address on resourceUri argument.
2959 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2960 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2964 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2965 if (result != OC_STACK_OK)
2967 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2971 else if (!checkProxyUri(options, numOptions))
2973 result = OC_STACK_INVALID_URI;
2974 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2981 case OC_REST_OBSERVE:
2982 case OC_REST_OBSERVE_ALL:
2983 requestInfo.method = CA_GET;
2986 requestInfo.method = CA_PUT;
2989 requestInfo.method = CA_POST;
2991 case OC_REST_DELETE:
2992 requestInfo.method = CA_DELETE;
2994 case OC_REST_DISCOVER:
2995 #ifdef WITH_PRESENCE
2996 case OC_REST_PRESENCE:
2998 if (destination || devAddr)
3000 requestInfo.isMulticast = false;
3004 tmpDevAddr.adapter = adapter;
3005 tmpDevAddr.flags = flags;
3006 destination = &tmpDevAddr;
3007 requestInfo.isMulticast = true;
3010 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
3011 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
3012 // replacing method type with GET.
3013 requestInfo.method = CA_GET;
3016 result = OC_STACK_INVALID_METHOD;
3020 if (!devAddr && !destination)
3022 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
3023 result = OC_STACK_INVALID_PARAM;
3027 /* If not original behavior, use destination argument */
3028 if (destination && !devAddr)
3030 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
3033 result = OC_STACK_NO_MEMORY;
3036 OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
3037 *devAddr = *destination;
3042 OIC_LOG_V(INFO_PRIVATE, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
3043 if (!requestInfo.isMulticast)
3045 OIC_LOG_V(DEBUG, TAG, "remoteAddr of devAddr : [%s]:[%d]",
3046 devAddr->addr, devAddr->port);
3050 resHandle = GenerateInvocationHandle();
3053 result = OC_STACK_NO_MEMORY;
3057 caResult = CAGenerateToken(&token, tokenLength);
3058 if (caResult != CA_STATUS_OK)
3060 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3061 result = CAResultToOCResult(caResult);
3065 // fill in request data
3066 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3067 requestInfo.info.token = token;
3068 requestInfo.info.tokenLength = tokenLength;
3070 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3072 result = CreateObserveHeaderOption (&(requestInfo.info.options),
3073 options, numOptions, OC_OBSERVE_REGISTER);
3074 if (result != OC_STACK_OK)
3078 requestInfo.info.numOptions = numOptions + 1;
3082 requestInfo.info.numOptions = numOptions;
3083 requestInfo.info.options =
3084 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3085 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3086 numOptions * sizeof(CAHeaderOption_t));
3089 CopyDevAddrToEndpoint(devAddr, &endpoint);
3094 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3097 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3100 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3104 requestInfo.info.payload = NULL;
3105 requestInfo.info.payloadSize = 0;
3106 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3109 // prepare for response
3110 #ifdef WITH_PRESENCE
3111 if (method == OC_REST_PRESENCE)
3113 char *presenceUri = NULL;
3114 result = OCPreparePresence(&endpoint, &presenceUri,
3115 requestInfo.isMulticast);
3116 if (OC_STACK_OK != result)
3121 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3122 // Presence notification will form a canonical uri to
3123 // look for callbacks into the application.
3126 OICFree(resourceUri);
3128 resourceUri = presenceUri;
3132 // update resourceUri onto requestInfo after check presence uri
3133 requestInfo.info.resourceUri = resourceUri;
3135 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3136 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3137 method, devAddr, resourceUri, resourceType, ttl);
3138 if (OC_STACK_OK != result)
3143 cbData = NULL; // Client CB list entry now owns it
3144 token = NULL; // Client CB list entry now owns it
3145 devAddr = NULL; // Client CB list entry now owns it
3146 resourceUri = NULL; // Client CB list entry now owns it
3147 resourceType = NULL; // Client CB list entry now owns it
3149 #ifdef WITH_PRESENCE
3150 if (method == OC_REST_PRESENCE)
3152 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3156 *handle = resHandle;
3158 #ifdef WITH_PROCESS_EVENT
3159 OCSendProcessEventSignal();
3160 #endif // WITH_PROCESS_EVENT
3167 result = OCSendRequest(&endpoint, &requestInfo);
3168 if (OC_STACK_OK != result)
3175 *handle = resHandle;
3179 if (result != OC_STACK_OK)
3181 OIC_LOG(ERROR, TAG, "OCDoResource error");
3182 if (NULL != cbData && NULL != cbData->cd)
3184 cbData->cd(cbData->context);
3186 if (!clientCB) // token and resHandle associated with clientCB
3188 CADestroyToken(token);
3193 FindAndDeleteClientCB(clientCB);
3201 OICFree(requestInfo.info.payload);
3203 OICFree(resourceUri);
3204 OICFree(resourceType);
3205 OICFree(requestInfo.info.options);
3210 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3214 * This ftn is implemented one of two ways in the case of observation:
3216 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3217 * Remove the callback associated on client side.
3218 * When the next notification comes in from server,
3219 * reply with RESET message to server.
3220 * Keep in mind that the server will react to RESET only
3221 * if the last notification was sent as CON
3223 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3224 * and it is associated with an observe request
3225 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3226 * Send CON Observe request to server with
3227 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3228 * Remove the callback associated on client side.
3230 OCStackResult ret = OC_STACK_OK;
3231 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3232 CARequestInfo_t requestInfo = {.method = CA_GET};
3236 return OC_STACK_INVALID_PARAM;
3239 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3242 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3243 return OC_STACK_ERROR;
3246 switch (clientCB->method)
3248 case OC_REST_OBSERVE:
3249 case OC_REST_OBSERVE_ALL:
3251 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3253 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3255 if (((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS) ||
3256 ((endpoint.adapter & CA_ADAPTER_TCP) && OC_LOW_QOS_WITH_TCP == qos))
3258 OIC_LOG_V(INFO, TAG, "the %s observe callback is removed", clientCB->requestUri);
3259 FindAndDeleteClientCB(clientCB);
3263 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3265 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3266 requestInfo.info.token = clientCB->token;
3267 requestInfo.info.tokenLength = clientCB->tokenLength;
3269 if (CreateObserveHeaderOption (&(requestInfo.info.options),
3270 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3272 return OC_STACK_ERROR;
3274 requestInfo.info.numOptions = numOptions + 1;
3275 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3278 ret = OCSendRequest(&endpoint, &requestInfo);
3280 if (requestInfo.info.options)
3282 OICFree (requestInfo.info.options);
3284 if (requestInfo.info.resourceUri)
3286 OICFree (requestInfo.info.resourceUri);
3291 case OC_REST_DISCOVER:
3292 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3293 clientCB->requestUri);
3294 FindAndDeleteClientCB(clientCB);
3297 #ifdef WITH_PRESENCE
3298 case OC_REST_PRESENCE:
3299 FindAndDeleteClientCB(clientCB);
3305 case OC_REST_DELETE:
3306 OIC_LOG_V(INFO, TAG, "Cancelling request callback for resource %s",
3307 clientCB->requestUri);
3308 FindAndDeleteClientCB(clientCB);
3312 ret = OC_STACK_INVALID_METHOD;
3320 * @brief Register Persistent storage callback.
3321 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3323 * OC_STACK_OK - No errors; Success
3324 * OC_STACK_INVALID_PARAM - Invalid parameter
3326 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3328 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3329 if(!persistentStorageHandler)
3331 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3332 return OC_STACK_INVALID_PARAM;
3336 if( !persistentStorageHandler->open ||
3337 !persistentStorageHandler->close ||
3338 !persistentStorageHandler->read ||
3339 !persistentStorageHandler->unlink ||
3340 !persistentStorageHandler->write)
3342 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3343 return OC_STACK_INVALID_PARAM;
3346 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3349 #ifdef WITH_PRESENCE
3351 #ifdef WITH_PROCESS_EVENT
3352 OCStackResult OCProcessPresence(uint32_t *nextEventTime)
3353 #else // WITH_PROCESS_EVENT
3354 OCStackResult OCProcessPresence(void)
3355 #endif // !WITH_PROCESS_EVENT
3357 OCStackResult result = OC_STACK_OK;
3359 // the following line floods the log with messages that are irrelevant
3360 // to most purposes. Uncomment as needed.
3361 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3362 ClientCB* cbNode = NULL;
3363 ClientCB* tempcbNode = NULL;
3364 OCClientResponse clientResponse;
3365 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3367 LL_FOREACH_SAFE(cbList, cbNode, tempcbNode)
3369 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3374 uint32_t now = GetTicks(0);
3375 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3376 cbNode->presence->TTLlevel);
3377 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3379 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3384 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3386 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3387 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3389 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3391 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3393 clientResponse.sequenceNumber = 0;
3394 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3395 clientResponse.devAddr = *cbNode->devAddr;
3396 FixUpClientResponse(&clientResponse);
3397 clientResponse.payload = NULL;
3399 // Increment the TTLLevel (going to a next state), so we don't keep
3400 // sending presence notification to client.
3401 cbNode->presence->TTLlevel++;
3402 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3403 cbNode->presence->TTLlevel);
3405 OIC_LOG(INFO, TAG, "Before calling into application address space for presence timeout");
3406 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3407 OIC_LOG(INFO, TAG, "After calling into application address space for presence timeout");
3409 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3411 FindAndDeleteClientCB(cbNode);
3416 uint32_t timeout = cbNode->presence->timeOut[cbNode->presence->TTLlevel];
3419 #ifdef WITH_PROCESS_EVENT
3420 if (nextEventTime && (timeout - now) < *nextEventTime)
3422 *nextEventTime = timeout - now;
3424 #endif // WITH_PROCESS_EVENT
3428 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3429 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3430 CARequestInfo_t requestInfo = {.method = CA_GET};
3432 OIC_LOG(DEBUG, TAG, "time to test server presence");
3434 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3436 requestData.type = CA_MSG_NONCONFIRM;
3437 requestData.token = cbNode->token;
3438 requestData.tokenLength = cbNode->tokenLength;
3439 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3440 requestInfo.method = CA_GET;
3441 requestInfo.info = requestData;
3443 result = OCSendRequest(&endpoint, &requestInfo);
3444 if (OC_STACK_OK != result)
3449 cbNode->presence->TTLlevel++;
3450 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3453 if (result != OC_STACK_OK)
3455 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3460 #endif // WITH_PRESENCE
3462 #ifdef WITH_PROCESS_EVENT
3463 OCStackResult OCProcess(void)
3465 uint32_t nextEventTime;
3466 return OCProcessEvent(&nextEventTime);
3469 OCStackResult OCProcessEvent(uint32_t *nextEventTime)
3471 if (stackState == OC_STACK_UNINITIALIZED)
3473 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3474 return OC_STACK_ERROR;
3477 *nextEventTime = UINT32_MAX;
3479 #ifdef WITH_PRESENCE
3480 OCProcessPresence(nextEventTime);
3481 OIC_LOG_V(INFO, TAG, "OCProcessPresence next event time : %u", *nextEventTime);
3483 CAHandleRequestResponse();
3486 #ifdef ROUTING_GATEWAY
3487 RMProcess(nextEventTime);
3491 OCProcessKeepAlive(nextEventTime);
3492 OIC_LOG_V(INFO, TAG, "OCProcessKeepAlive next event time : %u", *nextEventTime);
3497 void OCRegisterProcessEvent(oc_event event)
3499 g_ocProcessEvent = event;
3500 CARegisterProcessEvent(event);
3503 void OCSendProcessEventSignal(void)
3505 if (g_ocProcessEvent)
3507 oc_event_signal(g_ocProcessEvent);
3510 #else // WITH_PROCESS_EVENT
3512 OCStackResult OCProcess()
3514 if (stackState == OC_STACK_UNINITIALIZED)
3516 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3517 return OC_STACK_ERROR;
3519 #ifdef WITH_PRESENCE
3520 OCProcessPresence();
3522 CAHandleRequestResponse();
3524 #ifdef ROUTING_GATEWAY
3529 OCProcessKeepAlive();
3533 #endif // !WITH_PROCESS_EVENT
3535 #ifdef WITH_PRESENCE
3536 OCStackResult OCStartPresence(const uint32_t ttl)
3538 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3539 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3540 OCChangeResourceProperty(
3541 &(((OCResource *)presenceResource.handle)->resourceProperties),
3544 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3546 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3547 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3551 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3552 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3556 presenceResource.presenceTTL = ttl;
3559 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3562 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3564 presenceState = OC_PRESENCE_INITIALIZED;
3566 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3568 CAToken_t caToken = NULL;
3569 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3570 if (caResult != CA_STATUS_OK)
3572 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3573 CADestroyToken(caToken);
3574 return OC_STACK_ERROR;
3577 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3578 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3579 CADestroyToken(caToken);
3582 // Each time OCStartPresence is called
3583 // a different random 32-bit integer number is used
3584 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3586 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3587 OC_PRESENCE_TRIGGER_CREATE);
3590 OCStackResult OCStopPresence()
3592 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3593 OCStackResult result = OC_STACK_ERROR;
3595 if(presenceResource.handle)
3597 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3599 // make resource inactive
3600 result = OCChangeResourceProperty(
3601 &(((OCResource *) presenceResource.handle)->resourceProperties),
3605 if(result != OC_STACK_OK)
3608 "Changing the presence resource properties to ACTIVE not successful");
3612 return SendStopNotification();
3616 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3617 void* callbackParameter)
3619 defaultDeviceHandler = entityHandler;
3620 defaultDeviceHandlerCallbackParameter = callbackParameter;
3625 OCStackResult OCCreateResource(OCResourceHandle *handle,
3626 const char *resourceTypeName,
3627 const char *resourceInterfaceName,
3628 const char *uri, OCEntityHandler entityHandler,
3629 void* callbackParam,
3630 uint8_t resourceProperties)
3633 OCResource *pointer = NULL;
3634 OCStackResult result = OC_STACK_ERROR;
3636 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3638 if(myStackMode == OC_CLIENT)
3640 return OC_STACK_INVALID_PARAM;
3642 // Validate parameters
3643 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3645 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3646 return OC_STACK_INVALID_URI;
3648 // Is it presented during resource discovery?
3649 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3651 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3652 return OC_STACK_INVALID_PARAM;
3655 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3657 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3661 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3663 // Make sure resourceProperties bitmask has allowed properties specified
3664 if (resourceProperties
3665 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3666 OC_EXPLICIT_DISCOVERABLE
3675 OIC_LOG(ERROR, TAG, "Invalid property");
3676 return OC_STACK_INVALID_PARAM;
3679 // If the headResource is NULL, then no resources have been created...
3680 pointer = headResource;
3683 // At least one resources is in the resource list, so we need to search for
3684 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3687 if (pointer->uri && strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3689 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3690 return OC_STACK_INVALID_PARAM;
3692 pointer = pointer->next;
3695 // Create the pointer and insert it into the resource list
3696 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3699 result = OC_STACK_NO_MEMORY;
3702 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3704 insertResource(pointer);
3707 pointer->uri = OICStrdup(uri);
3710 result = OC_STACK_NO_MEMORY;
3714 // Set properties. Set OC_ACTIVE
3715 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3718 // Add the resourcetype to the resource
3719 result = BindResourceTypeToResource(pointer, resourceTypeName);
3720 if (result != OC_STACK_OK)
3722 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3726 // Add the resourceinterface to the resource
3727 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3728 if (result != OC_STACK_OK)
3730 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3734 // If an entity handler has been passed, attach it to the newly created
3735 // resource. Otherwise, set the default entity handler.
3738 pointer->entityHandler = entityHandler;
3739 pointer->entityHandlerCallbackParam = callbackParam;
3743 pointer->entityHandler = defaultResourceEHandler;
3744 pointer->entityHandlerCallbackParam = NULL;
3747 // Initialize a pointer indicating child resources in case of collection
3748 pointer->rsrcChildResourcesHead = NULL;
3751 result = OC_STACK_OK;
3753 #ifdef WITH_PRESENCE
3754 if (presenceResource.handle)
3756 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3757 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3761 if (result != OC_STACK_OK)
3763 // Deep delete of resource and other dynamic elements that it contains
3764 deleteResource(pointer);
3769 OCStackResult OCBindResource(
3770 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3772 OCResource *resource = NULL;
3773 OCChildResource *tempChildResource = NULL;
3774 OCChildResource *newChildResource = NULL;
3776 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3778 // Validate parameters
3779 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3780 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3781 // Container cannot contain itself
3782 if (collectionHandle == resourceHandle)
3784 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3785 return OC_STACK_INVALID_PARAM;
3788 // Use the handle to find the resource in the resource linked list
3789 resource = findResource((OCResource *) collectionHandle);
3792 OIC_LOG(ERROR, TAG, "Collection handle not found");
3793 return OC_STACK_INVALID_PARAM;
3796 // Look for an open slot to add add the child resource.
3797 // If found, add it and return success
3799 tempChildResource = resource->rsrcChildResourcesHead;
3801 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3803 // TODO: what if one of child resource was deregistered without unbinding?
3804 tempChildResource = tempChildResource->next;
3807 // Do memory allocation for child resource
3808 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3809 if(!newChildResource)
3811 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3812 return OC_STACK_ERROR;
3815 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3816 newChildResource->next = NULL;
3818 if(!resource->rsrcChildResourcesHead)
3820 resource->rsrcChildResourcesHead = newChildResource;
3823 tempChildResource->next = newChildResource;
3826 OIC_LOG(INFO, TAG, "resource bound");
3828 #ifdef WITH_PRESENCE
3829 if (presenceResource.handle)
3831 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3832 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3833 OC_PRESENCE_TRIGGER_CHANGE);
3840 OCStackResult OCUnBindResource(
3841 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3843 OCResource *resource = NULL;
3844 OCChildResource *tempChildResource = NULL;
3845 OCChildResource *tempLastChildResource = NULL;
3847 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3849 // Validate parameters
3850 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3851 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3852 // Container cannot contain itself
3853 if (collectionHandle == resourceHandle)
3855 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3856 return OC_STACK_INVALID_PARAM;
3859 // Use the handle to find the resource in the resource linked list
3860 resource = findResource((OCResource *) collectionHandle);
3863 OIC_LOG(ERROR, TAG, "Collection handle not found");
3864 return OC_STACK_INVALID_PARAM;
3867 // Look for an open slot to add add the child resource.
3868 // If found, add it and return success
3869 if(!resource->rsrcChildResourcesHead)
3871 OIC_LOG(INFO, TAG, "resource not found in collection");
3873 // Unable to add resourceHandle, so return error
3874 return OC_STACK_ERROR;
3878 tempChildResource = resource->rsrcChildResourcesHead;
3880 while (tempChildResource)
3882 if(tempChildResource->rsrcResource == resourceHandle)
3884 // if resource going to be unbinded is the head one.
3885 if( tempChildResource == resource->rsrcChildResourcesHead )
3887 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3888 OICFree(resource->rsrcChildResourcesHead);
3889 resource->rsrcChildResourcesHead = temp;
3894 OCChildResource *temp = tempChildResource->next;
3895 OICFree(tempChildResource);
3896 if (tempLastChildResource)
3898 tempLastChildResource->next = temp;
3903 OIC_LOG(INFO, TAG, "resource unbound");
3905 // Send notification when resource is unbounded successfully.
3906 #ifdef WITH_PRESENCE
3907 if (presenceResource.handle)
3909 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3910 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3911 OC_PRESENCE_TRIGGER_CHANGE);
3914 tempChildResource = NULL;
3915 tempLastChildResource = NULL;
3921 tempLastChildResource = tempChildResource;
3922 tempChildResource = tempChildResource->next;
3925 OIC_LOG(INFO, TAG, "resource not found in collection");
3927 tempChildResource = NULL;
3928 tempLastChildResource = NULL;
3930 // Unable to add resourceHandle, so return error
3931 return OC_STACK_ERROR;
3934 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3936 if (!resourceItemName)
3940 // Per RFC 6690 only registered values must follow the first rule below.
3941 // At this point in time the only values registered begin with "core", and
3942 // all other values are specified as opaque strings where multiple values
3943 // are separated by a space.
3944 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3946 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3948 if (resourceItemName[index] != '.'
3949 && resourceItemName[index] != '-'
3950 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3951 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3959 for (size_t index = 0; resourceItemName[index]; ++index)
3961 if (resourceItemName[index] == ' '
3962 || resourceItemName[index] == '\t'
3963 || resourceItemName[index] == '\r'
3964 || resourceItemName[index] == '\n')
3974 OCStackResult BindResourceTypeToResource(OCResource* resource,
3975 const char *resourceTypeName)
3977 OCResourceType *pointer = NULL;
3979 OCStackResult result = OC_STACK_ERROR;
3981 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3983 if (!ValidateResourceTypeInterface(resourceTypeName))
3985 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3986 return OC_STACK_INVALID_PARAM;
3989 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3992 result = OC_STACK_NO_MEMORY;
3996 str = OICStrdup(resourceTypeName);
3999 result = OC_STACK_NO_MEMORY;
4002 pointer->resourcetypename = str;
4003 pointer->next = NULL;
4005 insertResourceType(resource, pointer);
4006 result = OC_STACK_OK;
4009 if (result != OC_STACK_OK)
4018 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
4019 const char *resourceInterfaceName)
4021 OCResourceInterface *pointer = NULL;
4023 OCStackResult result = OC_STACK_ERROR;
4025 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
4027 if (!ValidateResourceTypeInterface(resourceInterfaceName))
4029 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
4030 return OC_STACK_INVALID_PARAM;
4033 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
4035 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
4038 result = OC_STACK_NO_MEMORY;
4042 str = OICStrdup(resourceInterfaceName);
4045 result = OC_STACK_NO_MEMORY;
4048 pointer->name = str;
4050 // Bind the resourceinterface to the resource
4051 insertResourceInterface(resource, pointer);
4053 result = OC_STACK_OK;
4056 if (result != OC_STACK_OK)
4065 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
4066 const char *resourceTypeName)
4069 OCStackResult result = OC_STACK_ERROR;
4070 OCResource *resource = NULL;
4072 resource = findResource((OCResource *) handle);
4075 OIC_LOG(ERROR, TAG, "Resource not found");
4076 return OC_STACK_ERROR;
4079 result = BindResourceTypeToResource(resource, resourceTypeName);
4081 #ifdef WITH_PRESENCE
4082 if(presenceResource.handle)
4084 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4085 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4092 OCStackResult OCResetResourceTypes(OCResourceHandle handle,
4093 const char *newResourceType)
4095 OCStackResult result = OC_STACK_ERROR;
4096 OCResource *resource = NULL;
4098 resource = findResource((OCResource *) handle);
4101 OIC_LOG(ERROR, TAG, "Resource not found");
4102 return OC_STACK_ERROR;
4105 // Clear all bound resource types
4106 deleteResourceType(resource->rsrcType);
4107 resource->rsrcType = NULL;
4109 // Bind new resource type to resource
4110 result = BindResourceTypeToResource(resource, newResourceType);
4112 #ifdef WITH_PRESENCE
4113 if(presenceResource.handle)
4115 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4116 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4123 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
4124 const char *resourceInterfaceName)
4127 OCStackResult result = OC_STACK_ERROR;
4128 OCResource *resource = NULL;
4130 resource = findResource((OCResource *) handle);
4133 OIC_LOG(ERROR, TAG, "Resource not found");
4134 return OC_STACK_ERROR;
4137 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
4139 #ifdef WITH_PRESENCE
4140 if (presenceResource.handle)
4142 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4143 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4150 OCStackResult OCResetResourceInterfaces(OCResourceHandle handle,
4151 const char *newResourceInterface)
4153 OCStackResult result = OC_STACK_ERROR;
4154 OCResource *resource = NULL;
4156 resource = findResource((OCResource *) handle);
4159 OIC_LOG(ERROR, TAG, "Resource not found");
4160 return OC_STACK_ERROR;
4163 // Clear all bound interface
4164 deleteResourceInterface(resource->rsrcInterface);
4165 resource->rsrcInterface = NULL;
4167 // Bind new interface to resource
4168 result = BindResourceInterfaceToResource(resource, newResourceInterface);
4170 #ifdef WITH_PRESENCE
4171 if (presenceResource.handle)
4173 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4174 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4181 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
4183 OCResource *pointer = headResource;
4185 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
4189 *numResources = *numResources + 1;
4190 pointer = pointer->next;
4195 OCResourceHandle OCGetResourceHandle(uint8_t index)
4197 OCResource *pointer = headResource;
4199 for( uint8_t i = 0; i < index && pointer; ++i)
4201 pointer = pointer->next;
4203 return (OCResourceHandle) pointer;
4206 OCStackResult OCDeleteResource(OCResourceHandle handle)
4210 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4211 return OC_STACK_INVALID_PARAM;
4214 OCResource *resource = findResource((OCResource *) handle);
4215 if (resource == NULL)
4217 OIC_LOG(ERROR, TAG, "Resource not found");
4218 return OC_STACK_NO_RESOURCE;
4221 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4223 OIC_LOG(ERROR, TAG, "Error deleting resource");
4224 return OC_STACK_ERROR;
4230 const char *OCGetResourceUri(OCResourceHandle handle)
4232 OCResource *resource = NULL;
4234 resource = findResource((OCResource *) handle);
4237 return resource->uri;
4239 return (const char *) NULL;
4242 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4244 OCResource *resource = NULL;
4246 resource = findResource((OCResource *) handle);
4249 return resource->resourceProperties;
4251 return (OCResourceProperty)-1;
4254 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4255 uint8_t *numResourceTypes)
4257 OCResource *resource = NULL;
4258 OCResourceType *pointer = NULL;
4260 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4261 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4263 *numResourceTypes = 0;
4265 resource = findResource((OCResource *) handle);
4268 pointer = resource->rsrcType;
4271 *numResourceTypes = *numResourceTypes + 1;
4272 pointer = pointer->next;
4278 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4280 OCResourceType *resourceType = NULL;
4282 resourceType = findResourceTypeAtIndex(handle, index);
4285 return resourceType->resourcetypename;
4287 return (const char *) NULL;
4290 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4291 uint8_t *numResourceInterfaces)
4293 OCResourceInterface *pointer = NULL;
4294 OCResource *resource = NULL;
4296 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4297 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4299 *numResourceInterfaces = 0;
4300 resource = findResource((OCResource *) handle);
4303 pointer = resource->rsrcInterface;
4306 *numResourceInterfaces = *numResourceInterfaces + 1;
4307 pointer = pointer->next;
4313 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4315 OCResourceInterface *resourceInterface = NULL;
4317 resourceInterface = findResourceInterfaceAtIndex(handle, index);
4318 if (resourceInterface)
4320 return resourceInterface->name;
4322 return (const char *) NULL;
4325 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4328 OCResource *resource = NULL;
4329 OCChildResource *tempChildResource = NULL;
4332 resource = findResource((OCResource *) collectionHandle);
4338 tempChildResource = resource->rsrcChildResourcesHead;
4340 while(tempChildResource)
4344 return tempChildResource->rsrcResource;
4347 tempChildResource = tempChildResource->next;
4350 // In this case, the number of resource handles in the collection exceeds the index
4351 tempChildResource = NULL;
4355 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4356 OCEntityHandler entityHandler,
4357 void* callbackParam)
4359 OCResource *resource = NULL;
4361 // Validate parameters
4362 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4364 // Use the handle to find the resource in the resource linked list
4365 resource = findResource((OCResource *)handle);
4368 OIC_LOG(ERROR, TAG, "Resource not found");
4369 return OC_STACK_ERROR;
4373 resource->entityHandler = entityHandler;
4374 resource->entityHandlerCallbackParam = callbackParam;
4376 #ifdef WITH_PRESENCE
4377 if (presenceResource.handle)
4379 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4380 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4387 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4389 OCResource *resource = NULL;
4391 resource = findResource((OCResource *)handle);
4394 OIC_LOG(ERROR, TAG, "Resource not found");
4399 return resource->entityHandler;
4402 void incrementSequenceNumber(OCResource * resPtr)
4404 // Increment the sequence number
4405 resPtr->sequenceNum += 1;
4406 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4408 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4413 #ifdef WITH_PRESENCE
4414 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4415 OCPresenceTrigger trigger)
4417 OIC_LOG(INFO, TAG, "SendPresenceNotification");
4418 OCResource *resPtr = NULL;
4419 OCStackResult result = OC_STACK_ERROR;
4420 OCMethod method = OC_REST_PRESENCE;
4421 uint32_t maxAge = 0;
4422 resPtr = findResource((OCResource *) presenceResource.handle);
4425 return OC_STACK_NO_RESOURCE;
4428 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4430 maxAge = presenceResource.presenceTTL;
4432 result = SendAllObserverNotification(method, resPtr, maxAge,
4433 trigger, resourceType, OC_LOW_QOS);
4439 OCStackResult SendStopNotification()
4441 OIC_LOG(INFO, TAG, "SendStopNotification");
4442 OCResource *resPtr = NULL;
4443 OCStackResult result = OC_STACK_ERROR;
4444 OCMethod method = OC_REST_PRESENCE;
4445 resPtr = findResource((OCResource *) presenceResource.handle);
4448 return OC_STACK_NO_RESOURCE;
4451 // maxAge is 0. ResourceType is NULL.
4452 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4458 #endif // WITH_PRESENCE
4459 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4461 OCResource *resPtr = NULL;
4462 OCStackResult result = OC_STACK_ERROR;
4463 OCMethod method = OC_REST_NOMETHOD;
4464 uint32_t maxAge = 0;
4466 OIC_LOG(INFO, TAG, "Notifying all observers");
4467 #ifdef WITH_PRESENCE
4468 if(handle == presenceResource.handle)
4472 #endif // WITH_PRESENCE
4473 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4475 // Verify that the resource exists
4476 resPtr = findResource ((OCResource *) handle);
4479 return OC_STACK_NO_RESOURCE;
4483 //only increment in the case of regular observing (not presence)
4484 incrementSequenceNumber(resPtr);
4485 method = OC_REST_OBSERVE;
4486 maxAge = MAX_OBSERVE_AGE;
4487 #ifdef WITH_PRESENCE
4488 result = SendAllObserverNotification (method, resPtr, maxAge,
4489 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4491 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4498 OCNotifyListOfObservers (OCResourceHandle handle,
4499 OCObservationId *obsIdList,
4500 uint8_t numberOfIds,
4501 const OCRepPayload *payload,
4502 OCQualityOfService qos)
4504 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4506 OCResource *resPtr = NULL;
4507 //TODO: we should allow the server to define this
4508 uint32_t maxAge = MAX_OBSERVE_AGE;
4510 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4511 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4512 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4514 resPtr = findResource ((OCResource *) handle);
4515 if (NULL == resPtr || myStackMode == OC_CLIENT)
4517 return OC_STACK_NO_RESOURCE;
4521 incrementSequenceNumber(resPtr);
4523 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4524 payload, maxAge, qos));
4527 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4529 OIC_TRACE_BEGIN(%s:OCDoResponse, TAG);
4530 OCStackResult result = OC_STACK_ERROR;
4531 OCServerRequest *serverRequest = NULL;
4533 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4535 // Validate input parameters
4536 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4537 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4540 // Get pointer to request info
4541 serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
4544 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4545 result = serverRequest->ehResponseHandler(ehResponse);
4552 //#ifdef DIRECT_PAIRING
4553 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4555 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4556 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4558 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4562 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4565 const OCDPDev_t* OCGetDirectPairedDevices()
4567 return (const OCDPDev_t*)DPGetPairedDevices();
4570 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4571 OCDirectPairingCB resultCallback)
4573 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4574 if(NULL == peer || NULL == pinNumber)
4576 OIC_LOG(ERROR, TAG, "Invalid parameters");
4577 return OC_STACK_INVALID_PARAM;
4579 if (NULL == resultCallback)
4581 OIC_LOG(ERROR, TAG, "Invalid callback");
4582 return OC_STACK_INVALID_CALLBACK;
4585 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4586 pinNumber, (OCDirectPairingResultCB)resultCallback);
4588 //#endif // DIRECT_PAIRING
4590 //-----------------------------------------------------------------------------
4591 // Private internal function definitions
4592 //-----------------------------------------------------------------------------
4593 static OCDoHandle GenerateInvocationHandle()
4595 OCDoHandle handle = NULL;
4596 // Generate token here, it will be deleted when the transaction is deleted
4597 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4600 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4606 #ifdef WITH_PRESENCE
4607 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4608 OCResourceProperty resourceProperties, uint8_t enable)
4612 return OC_STACK_INVALID_PARAM;
4614 if (resourceProperties
4615 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4617 OIC_LOG(ERROR, TAG, "Invalid property");
4618 return OC_STACK_INVALID_PARAM;
4622 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4626 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4632 OCStackResult initResources()
4634 OCStackResult result = OC_STACK_OK;
4636 headResource = NULL;
4637 tailResource = NULL;
4638 // Init Virtual Resources
4639 #ifdef WITH_PRESENCE
4640 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4642 result = OCCreateResource(&presenceResource.handle,
4643 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4645 OC_RSRVD_PRESENCE_URI,
4649 //make resource inactive
4650 result = OCChangeResourceProperty(
4651 &(((OCResource *) presenceResource.handle)->resourceProperties),
4654 #ifndef WITH_ARDUINO
4655 if (result == OC_STACK_OK)
4657 result = SRMInitSecureResources();
4661 if(result == OC_STACK_OK)
4663 CreateResetProfile();
4664 result = OCCreateResource(&deviceResource,
4665 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4666 OC_RSRVD_INTERFACE_DEFAULT,
4667 OC_RSRVD_DEVICE_URI,
4671 if(result == OC_STACK_OK)
4673 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4674 OC_RSRVD_INTERFACE_READ);
4678 if(result == OC_STACK_OK)
4680 result = OCCreateResource(&platformResource,
4681 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4682 OC_RSRVD_INTERFACE_DEFAULT,
4683 OC_RSRVD_PLATFORM_URI,
4687 if(result == OC_STACK_OK)
4689 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4690 OC_RSRVD_INTERFACE_READ);
4697 void insertResource(OCResource *resource)
4701 headResource = resource;
4702 tailResource = resource;
4706 tailResource->next = resource;
4707 tailResource = resource;
4709 resource->next = NULL;
4712 OCResource *findResource(OCResource *resource)
4714 OCResource *pointer = headResource;
4718 if (pointer == resource)
4722 pointer = pointer->next;
4727 void deleteAllResources()
4729 OCResource *pointer = headResource;
4730 OCResource *temp = NULL;
4734 temp = pointer->next;
4735 #ifdef WITH_PRESENCE
4736 if (pointer != (OCResource *) presenceResource.handle)
4738 #endif // WITH_PRESENCE
4739 deleteResource(pointer);
4740 #ifdef WITH_PRESENCE
4742 #endif // WITH_PRESENCE
4745 memset(&platformResource, 0, sizeof(platformResource));
4746 memset(&deviceResource, 0, sizeof(deviceResource));
4748 memset(&brokerResource, 0, sizeof(brokerResource));
4751 SRMDeInitSecureResources();
4753 #ifdef WITH_PRESENCE
4754 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4755 // presence notification attributed to their deletion to be processed.
4756 deleteResource((OCResource *) presenceResource.handle);
4757 memset(&presenceResource, 0, sizeof(presenceResource));
4758 #endif // WITH_PRESENCE
4761 OCStackResult deleteResource(OCResource *resource)
4763 OCResource *prev = NULL;
4764 OCResource *temp = NULL;
4767 OIC_LOG(DEBUG,TAG,"resource is NULL");
4768 return OC_STACK_INVALID_PARAM;
4771 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4773 temp = headResource;
4776 if (temp == resource)
4778 // Invalidate all Resource Properties.
4779 resource->resourceProperties = (OCResourceProperty) 0;
4780 #ifdef WITH_PRESENCE
4781 if(resource != (OCResource *) presenceResource.handle)
4783 #endif // WITH_PRESENCE
4784 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4785 #ifdef WITH_PRESENCE
4788 if(presenceResource.handle)
4790 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4791 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4794 // Delete resource's all observers
4795 DeleteObserverUsingResource(resource);
4797 // Only resource in list.
4798 if (temp == headResource && temp == tailResource)
4800 headResource = NULL;
4801 tailResource = NULL;
4804 else if (temp == headResource)
4806 headResource = temp->next;
4809 else if (temp == tailResource && prev)
4811 tailResource = prev;
4812 tailResource->next = NULL;
4816 prev->next = temp->next;
4819 deleteResourceElements(temp);
4830 return OC_STACK_ERROR;
4833 void deleteResourceElements(OCResource *resource)
4842 OICFree(resource->uri);
4843 resource->uri = NULL;
4845 if (resource->rsrcType)
4847 deleteResourceType(resource->rsrcType);
4848 resource->rsrcType = NULL;
4850 if (resource->rsrcInterface)
4852 deleteResourceInterface(resource->rsrcInterface);
4853 resource->rsrcInterface = NULL;
4855 if (resource->rsrcChildResourcesHead)
4857 unbindChildResources(resource->rsrcChildResourcesHead);
4858 resource->rsrcChildResourcesHead = NULL;
4860 if (resource->rsrcAttributes)
4862 OCDeleteResourceAttributes(resource->rsrcAttributes);
4863 resource->rsrcAttributes = NULL;
4866 resource->entityHandler = NULL;
4870 void deleteResourceType(OCResourceType *resourceType)
4872 OCResourceType *next = NULL;
4874 for (OCResourceType *pointer = resourceType; pointer; pointer = next)
4876 next = pointer->next ? pointer->next : NULL;
4877 if (pointer->resourcetypename)
4879 OICFree(pointer->resourcetypename);
4880 pointer->resourcetypename = NULL;
4886 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4888 OCResourceInterface *next = NULL;
4889 for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
4891 next = pointer->next ? pointer->next : NULL;
4894 OICFree(pointer->name);
4895 pointer->name = NULL;
4901 void unbindChildResources(OCChildResource *head)
4903 OCChildResource *next = NULL;
4904 for (OCChildResource *current = head; current; current = next)
4906 next = current->next;
4911 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
4913 OCAttribute *next = NULL;
4914 for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
4916 next = pointer->next ? pointer->next : NULL;
4917 if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
4919 OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
4920 pointer->attrValue = NULL;
4922 else if (pointer->attrValue)
4924 OICFree(pointer->attrValue);
4925 pointer->attrValue = NULL;
4927 if (pointer->attrName)
4929 OICFree(pointer->attrName);
4930 pointer->attrName = NULL;
4936 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4938 OCResourceType *pointer = NULL;
4939 OCResourceType *previous = NULL;
4940 if (!resource || !resourceType)
4944 // resource type list is empty.
4945 else if (!resource->rsrcType)
4947 resource->rsrcType = resourceType;
4951 pointer = resource->rsrcType;
4955 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4957 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4958 OICFree(resourceType->resourcetypename);
4959 OICFree(resourceType);
4963 pointer = pointer->next;
4968 previous->next = resourceType;
4971 resourceType->next = NULL;
4973 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4976 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4978 OCResource *resource = NULL;
4979 OCResourceType *pointer = NULL;
4981 // Find the specified resource
4982 resource = findResource((OCResource *) handle);
4988 // Make sure a resource has a resourcetype
4989 if (!resource->rsrcType)
4994 // Iterate through the list
4995 pointer = resource->rsrcType;
4996 for(uint8_t i = 0; i< index && pointer; ++i)
4998 pointer = pointer->next;
5003 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
5005 if(resourceTypeList && resourceTypeName)
5007 OCResourceType * rtPointer = resourceTypeList;
5008 while(resourceTypeName && rtPointer)
5010 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
5011 if(rtPointer->resourcetypename &&
5012 strcmp(resourceTypeName, (const char *)
5013 (rtPointer->resourcetypename)) == 0)
5017 rtPointer = rtPointer->next;
5025 * Insert a new interface into interface linked list only if not already present.
5026 * If alredy present, 2nd arg is free'd.
5027 * Default interface will always be first if present.
5029 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
5031 OCResourceInterface *pointer = NULL;
5032 OCResourceInterface *previous = NULL;
5034 newInterface->next = NULL;
5036 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
5038 if (!*firstInterface)
5040 // If first interface is not oic.if.baseline, by default add it as first interface type.
5041 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
5043 *firstInterface = newInterface;
5047 OCStackResult result = BindResourceInterfaceToResource(resource,
5048 OC_RSRVD_INTERFACE_DEFAULT);
5049 if (result != OC_STACK_OK)
5051 OICFree(newInterface->name);
5052 OICFree(newInterface);
5055 if (*firstInterface)
5057 (*firstInterface)->next = newInterface;
5061 // If once add oic.if.baseline, later too below code take care of freeing memory.
5062 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5064 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5066 OICFree(newInterface->name);
5067 OICFree(newInterface);
5070 // This code will not hit anymore, keeping
5073 newInterface->next = *firstInterface;
5074 *firstInterface = newInterface;
5079 pointer = *firstInterface;
5082 if (strcmp(newInterface->name, pointer->name) == 0)
5084 OICFree(newInterface->name);
5085 OICFree(newInterface);
5089 pointer = pointer->next;
5094 previous->next = newInterface;
5099 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
5102 OCResource *resource = NULL;
5103 OCResourceInterface *pointer = NULL;
5105 // Find the specified resource
5106 resource = findResource((OCResource *) handle);
5112 // Make sure a resource has a resourceinterface
5113 if (!resource->rsrcInterface)
5118 // Iterate through the list
5119 pointer = resource->rsrcInterface;
5121 for (uint8_t i = 0; i < index && pointer; ++i)
5123 pointer = pointer->next;
5129 * This function splits the uri using the '?' delimiter.
5130 * "uriWithoutQuery" is the block of characters between the beginning
5131 * till the delimiter or '\0' which ever comes first.
5132 * "query" is whatever is to the right of the delimiter if present.
5133 * No delimiter sets the query to NULL.
5134 * If either are present, they will be malloc'ed into the params 2, 3.
5135 * The first param, *uri is left untouched.
5137 * NOTE: This function does not account for whitespace at the end of the uri NOR
5138 * malformed uri's with '??'. Whitespace at the end will be assumed to be
5139 * part of the query.
5141 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
5145 return OC_STACK_INVALID_URI;
5147 if(!query || !uriWithoutQuery)
5149 return OC_STACK_INVALID_PARAM;
5153 *uriWithoutQuery = NULL;
5155 size_t uriWithoutQueryLen = 0;
5156 size_t queryLen = 0;
5157 size_t uriLen = strlen(uri);
5159 char *pointerToDelimiter = strstr(uri, "?");
5161 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
5162 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
5164 if (uriWithoutQueryLen)
5166 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
5167 if (!*uriWithoutQuery)
5171 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
5175 *query = (char *) OICCalloc(queryLen + 1, 1);
5178 OICFree(*uriWithoutQuery);
5179 *uriWithoutQuery = NULL;
5182 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5188 return OC_STACK_NO_MEMORY;
5191 const char* OCGetServerInstanceIDString(void)
5193 static char sidStr[UUID_STRING_SIZE];
5195 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5197 OIC_LOG(FATAL, TAG, "GetDoxmDeviceID failed!");
5201 if (OCConvertUuidToString(sid.id, sidStr) != RAND_UUID_OK)
5203 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5210 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5212 OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5213 CAResult_t retResult = CA_STATUS_FAILED;
5214 CAResult_t caResult = CA_STATUS_OK;
5216 CATransportAdapter_t connTypes[] = {
5218 CA_ADAPTER_RFCOMM_BTEDR,
5219 CA_ADAPTER_GATT_BTLE,
5222 ,CA_ADAPTER_REMOTE_ACCESS
5229 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5231 for(int i = 0; i < numConnTypes; i++)
5233 // If CA status is not initialized, CASelectNetwork() will not be called.
5234 if (caResult != CA_STATUS_NOT_INITIALIZED)
5236 if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5238 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5239 caResult = CASelectNetwork(connTypes[i]);
5240 if (caResult == CA_STATUS_OK)
5242 retResult = CA_STATUS_OK;
5247 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5252 if (retResult != CA_STATUS_OK)
5254 return caResult; // Returns error of appropriate transport that failed fatally.
5260 OCStackResult CAResultToOCResult(CAResult_t caResult)
5266 case CA_STATUS_INVALID_PARAM:
5267 return OC_STACK_INVALID_PARAM;
5268 case CA_ADAPTER_NOT_ENABLED:
5269 return OC_STACK_ADAPTER_NOT_ENABLED;
5270 case CA_SERVER_STARTED_ALREADY:
5272 case CA_SERVER_NOT_STARTED:
5273 return OC_STACK_ERROR;
5274 case CA_DESTINATION_NOT_REACHABLE:
5275 return OC_STACK_COMM_ERROR;
5276 case CA_SOCKET_OPERATION_FAILED:
5277 return OC_STACK_COMM_ERROR;
5278 case CA_SEND_FAILED:
5279 return OC_STACK_COMM_ERROR;
5280 case CA_RECEIVE_FAILED:
5281 return OC_STACK_COMM_ERROR;
5282 case CA_MEMORY_ALLOC_FAILED:
5283 return OC_STACK_NO_MEMORY;
5284 case CA_REQUEST_TIMEOUT:
5285 return OC_STACK_TIMEOUT;
5286 case CA_DESTINATION_DISCONNECTED:
5287 return OC_STACK_COMM_ERROR;
5288 case CA_STATUS_FAILED:
5289 return OC_STACK_ERROR;
5290 case CA_NOT_SUPPORTED:
5291 return OC_STACK_NOTIMPL;
5293 return OC_STACK_ERROR;
5297 bool OCResultToSuccess(OCStackResult ocResult)
5302 case OC_STACK_RESOURCE_CREATED:
5303 case OC_STACK_RESOURCE_DELETED:
5304 case OC_STACK_CONTINUE:
5305 case OC_STACK_RESOURCE_CHANGED:
5306 case OC_STACK_SLOW_RESOURCE:
5314 OCStackResult OCSetProxyURI(const char *uri)
5316 return CAResultToOCResult(CASetProxyUri(uri));
5320 #if defined(RD_CLIENT) || defined(RD_SERVER)
5321 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5323 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5325 OCResource *resource = NULL;
5327 resource = findResource((OCResource *) handle);
5330 OIC_LOG(ERROR, TAG, "Resource not found");
5331 return OC_STACK_ERROR;
5334 resource->ins = ins;
5340 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5341 const OCClientResponse *response)
5343 // Validate input parameters
5344 VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5345 VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5347 char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5350 return OC_STACK_NO_MEMORY;
5352 strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5354 if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5356 OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5358 char rdPubUri[MAX_URI_LENGTH] = { 0 };
5359 snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5360 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5362 if (strcmp(rdPubUri, targetUri) == 0)
5364 // Update resource unique id in stack.
5367 if (response->payload)
5369 OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5370 OCRepPayload **links = NULL;
5371 size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5372 if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5373 &links, dimensions))
5376 for (; i < dimensions[0]; i++)
5379 if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5381 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5383 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5385 OCBindResourceInsToResource(handle, ins);
5394 size_t count = calcDimTotal(dimensions);
5395 for (size_t k = 0; k < count; k++)
5397 OCRepPayloadDestroy(links[k]);
5405 else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5407 OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5409 uint8_t numResources = 0;
5410 OCGetNumberOfResources(&numResources);
5412 char *ins = strstr(targetUri, OC_RSRVD_INS);
5415 for (uint8_t i = 0; i < numResources; i++)
5417 OCResourceHandle resHandle = OCGetResourceHandle(i);
5420 OCBindResourceInsToResource(resHandle, 0);
5426 const char *token = "&";
5427 char *iterTokenPtr = NULL;
5428 char *start = strtok_r(targetUri, token, &iterTokenPtr);
5430 while (start != NULL)
5432 char *query = start;
5433 query = strstr(query, OC_RSRVD_INS);
5436 int64_t queryIns = atoi(query + 4);
5437 for (uint8_t i = 0; i < numResources; i++)
5439 OCResourceHandle resHandle = OCGetResourceHandle(i);
5443 OCGetResourceIns(resHandle, &resIns);
5444 if (queryIns && queryIns == resIns)
5446 OCBindResourceInsToResource(resHandle, 0);
5452 start = strtok_r(NULL, token, &iterTokenPtr);
5461 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5465 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5469 OCResource *pointer = headResource;
5473 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5475 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5478 pointer = pointer->next;
5483 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t *ins)
5485 OCResource *resource = NULL;
5487 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5488 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5490 resource = findResource((OCResource *) handle);
5493 *ins = resource->ins;
5496 return OC_STACK_ERROR;
5500 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5501 const void* optionData, size_t optionDataLength)
5505 OIC_LOG (INFO, TAG, "Header options are NULL");
5506 return OC_STACK_INVALID_PARAM;
5511 OIC_LOG (INFO, TAG, "optionData are NULL");
5512 return OC_STACK_INVALID_PARAM;
5517 OIC_LOG (INFO, TAG, "numOptions is NULL");
5518 return OC_STACK_INVALID_PARAM;
5521 if (*numOptions >= MAX_HEADER_OPTIONS)
5523 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5524 return OC_STACK_NO_MEMORY;
5527 ocHdrOpt += *numOptions;
5528 ocHdrOpt->protocolID = OC_COAP_ID;
5529 ocHdrOpt->optionID = optionID;
5530 ocHdrOpt->optionLength =
5531 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
5532 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5533 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5539 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5540 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5542 if (!ocHdrOpt || !numOptions)
5544 OIC_LOG (INFO, TAG, "No options present");
5550 OIC_LOG (INFO, TAG, "optionData are NULL");
5551 return OC_STACK_INVALID_PARAM;
5554 if (!receivedDataLength)
5556 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5557 return OC_STACK_INVALID_PARAM;
5560 for (uint8_t i = 0; i < numOptions; i++)
5562 if (ocHdrOpt[i].optionID == optionID)
5564 if (optionDataLength >= ocHdrOpt->optionLength)
5566 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5567 *receivedDataLength = ocHdrOpt->optionLength;
5572 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5573 return OC_STACK_ERROR;
5580 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5582 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5588 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5590 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5593 * If the client observes one or more resources over a reliable connection,
5594 * then the CoAP server (or intermediary in the role of the CoAP server)
5595 * MUST remove all entries associated with the client endpoint from the lists
5596 * of observers when the connection is either closed or times out.
5600 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5601 CopyEndpointToDevAddr(info, &devAddr);
5603 // remove observer list with remote device address.
5604 DeleteObserverUsingDevAddr(&devAddr);
5608 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5611 OCStackResult ret = OC_STACK_ERROR;
5613 ret = GetDoxmDeviceID(&oicUuid);
5614 if (OC_STACK_OK == ret)
5616 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5620 OIC_LOG(ERROR, TAG, "Device ID Get error");
5625 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5628 OCStackResult ret = OC_STACK_ERROR;
5630 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5631 for (int i = 0; i < UUID_LENGTH; i++)
5633 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5635 ret = SetDoxmDeviceID(&oicUuid);
5639 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5641 bool isDeviceOwned = true;
5642 OCStackResult ret = OC_STACK_ERROR;
5644 ret = GetDoxmIsOwned(&isDeviceOwned);
5645 if (OC_STACK_OK == ret)
5647 *isOwned = isDeviceOwned;
5651 OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5656 OCStackResult OCGetDeviceOperationalState(bool* isOp)
5660 *isOp = GetPstatIsop();
5664 return OC_STACK_ERROR;
5667 void OCClearCallBackList()
5669 DeleteClientCBList();
5672 void OCClearObserverlist()
5674 DeleteObserverList();
5677 int OCEncrypt(const unsigned char *pt, size_t pt_len,
5678 unsigned char **ct, size_t *ct_len)
5680 #ifndef __SECURE_PSI__
5681 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5684 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5686 return psiEncrypt(pt, pt_len, ct, ct_len);
5687 #endif // __SECURE_PSI__
5690 int OCDecrypt(const unsigned char *ct, size_t ct_len,
5691 unsigned char **pt, size_t *pt_len)
5693 #ifndef __SECURE_PSI__
5694 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5697 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5699 return psiDecrypt(ct, ct_len, pt, pt_len);
5700 #endif // __SECURE_PSI__
5703 OCStackResult OCSetKey(const unsigned char* key)
5705 #ifndef __SECURE_PSI__
5706 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5709 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5711 return psiSetKey(key);
5712 #endif // __SECURE_PSI__
5715 OCStackResult OCGetKey(unsigned char* key)
5717 #ifndef __SECURE_PSI__
5718 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5721 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5723 return psiGetKey(key);
5724 #endif // __SECURE_PSI__
5727 OCStackResult OCSetSecurePSI(const unsigned char *key, const OCPersistentStorage *psPlain,
5728 const OCPersistentStorage *psEnc, const OCPersistentStorage *psRescue)
5730 #ifndef __SECURE_PSI__
5731 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5734 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5736 return setSecurePSI(key, psPlain, psEnc, psRescue);
5737 #endif // __SECURE_PSI__
5740 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5741 static void OtmEventHandler(const char *addr, uint16_t port, const char *uuid, int event)
5743 if (g_otmEventHandler.cb)
5745 g_otmEventHandler.cb(g_otmEventHandler.ctx, addr, port, uuid, event);
5750 * It is already declared in srmutility.h.
5751 * We can't include the header file, because of "redefined VERIFY_NON_NULL"
5753 typedef void (*OicSecOtmEventHandler_t)(const char* addr, uint16_t port,
5754 const char* uuid, int event);
5755 void SetOtmEventHandler(OicSecOtmEventHandler_t otmEventHandler);
5758 OCStackResult OCSetOtmEventHandler(void *ctx, OCOtmEventHandler cb)
5760 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5761 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5763 g_otmEventHandler.cb = cb;
5764 g_otmEventHandler.ctx = ctx;
5766 if (g_otmEventHandler.cb)
5768 OIC_LOG(DEBUG, TAG, "SET OCOtmEventHandler");
5769 SetOtmEventHandler(OtmEventHandler);
5773 OIC_LOG(DEBUG, TAG, "UNSET OCOtmEventHandler");
5774 SetOtmEventHandler(NULL);
5777 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);