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"
66 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
67 #include "routingutility.h"
68 #ifdef ROUTING_GATEWAY
69 #include "routingmanager.h"
74 #include "oickeepaliveinternal.h"
77 //#ifdef DIRECT_PAIRING
78 #include "directpairing.h"
81 #ifdef HAVE_ARDUINO_TIME_H
84 #ifdef HAVE_SYS_TIME_H
87 #include <coap/coap.h>
89 #ifdef HAVE_ARPA_INET_H
90 #include <arpa/inet.h>
94 #define UINT32_MAX (0xFFFFFFFFUL)
97 //-----------------------------------------------------------------------------
99 //-----------------------------------------------------------------------------
102 OC_STACK_UNINITIALIZED = 0,
103 OC_STACK_INITIALIZED,
104 OC_STACK_UNINIT_IN_PROGRESS
110 OC_PRESENCE_UNINITIALIZED = 0,
111 OC_PRESENCE_INITIALIZED
115 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
118 OCOtmEventHandler cb;
120 } OCOtmEventHandler_t;
123 //-----------------------------------------------------------------------------
125 //-----------------------------------------------------------------------------
126 static OCStackState stackState = OC_STACK_UNINITIALIZED;
128 OCResource *headResource = NULL;
129 static OCResource *tailResource = NULL;
130 static OCResourceHandle platformResource = {0};
131 static OCResourceHandle deviceResource = {0};
133 static OCResourceHandle brokerResource = {0};
137 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
138 static PresenceResource presenceResource = {0};
139 static uint8_t PresenceTimeOutSize = 0;
140 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
143 static OCMode myStackMode;
145 //TODO: revisit this design
146 static bool gRASetInfo = false;
148 OCDeviceEntityHandler defaultDeviceHandler;
149 void* defaultDeviceHandlerCallbackParameter = NULL;
150 static const char COAP_TCP_SCHEME[] = "coap+tcp:";
151 static const char COAPS_TCP_SCHEME[] = "coaps+tcp:";
152 static const char CORESPEC[] = "core";
154 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
155 static OCOtmEventHandler_t g_otmEventHandler = {NULL, NULL};
158 #ifdef WITH_PROCESS_EVENT
159 static oc_event g_ocProcessEvent = NULL;
160 #endif // WITH_PROCESS_EVENT
162 //-----------------------------------------------------------------------------
164 //-----------------------------------------------------------------------------
165 #define TAG "OIC_RI_STACK"
166 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
167 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
168 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
169 TAG, #arg " is NULL"); return (retVal); } }
170 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
171 TAG, #arg " is NULL"); return; } }
172 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
175 //TODO: we should allow the server to define this
176 #define MAX_OBSERVE_AGE (0x2FFFFUL)
178 #define MILLISECONDS_PER_SECOND (1000)
180 //-----------------------------------------------------------------------------
181 // Private internal function prototypes
182 //-----------------------------------------------------------------------------
185 * Generate handle of OCDoResource invocation for callback management.
187 * @return Generated OCDoResource handle.
189 static OCDoHandle GenerateInvocationHandle();
192 * Initialize resource data structures, variables, etc.
194 * @return ::OC_STACK_OK on success, some other value upon failure.
196 static OCStackResult initResources();
199 * Add a resource to the end of the linked list of resources.
201 * @param resource Resource to be added
203 static void insertResource(OCResource *resource);
206 * Find a resource in the linked list of resources.
208 * @param resource Resource to be found.
209 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
212 static OCResource *findResource(OCResource *resource);
215 * Insert a resource type into a resource's resource type linked list.
216 * If resource type already exists, it will not be inserted and the
217 * resourceType will be free'd.
218 * resourceType->next should be null to avoid memory leaks.
219 * Function returns silently for null args.
221 * @param resource Resource where resource type is to be inserted.
222 * @param resourceType Resource type to be inserted.
224 static void insertResourceType(OCResource *resource,
225 OCResourceType *resourceType);
228 * Get a resource type at the specified index within a resource.
230 * @param handle Handle of resource.
231 * @param index Index of resource type.
233 * @return Pointer to resource type if found, NULL otherwise.
235 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
239 * Insert a resource interface into a resource's resource interface linked list.
240 * If resource interface already exists, it will not be inserted and the
241 * resourceInterface will be free'd.
242 * resourceInterface->next should be null to avoid memory leaks.
244 * @param resource Resource where resource interface is to be inserted.
245 * @param resourceInterface Resource interface to be inserted.
247 static void insertResourceInterface(OCResource *resource,
248 OCResourceInterface *resourceInterface);
251 * Get a resource interface at the specified index within a resource.
253 * @param handle Handle of resource.
254 * @param index Index of resource interface.
256 * @return Pointer to resource interface if found, NULL otherwise.
258 static OCResourceInterface *findResourceInterfaceAtIndex(
259 OCResourceHandle handle, uint8_t index);
262 * Delete all of the dynamically allocated elements that were created for the resource type.
264 * @param resourceType Specified resource type.
266 static void deleteResourceType(OCResourceType *resourceType);
269 * Delete all of the dynamically allocated elements that were created for the resource interface.
271 * @param resourceInterface Specified resource interface.
273 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
276 * Unbind all child resources.
278 * @param resourceChild Specified binded resource head is deleted from parent.
280 static void unbindChildResources(OCChildResource *resourceChild);
283 * Delete all of the dynamically allocated elements that were created for the resource.
285 * @param resource Specified resource.
287 static void deleteResourceElements(OCResource *resource);
290 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
293 * @param handle Handle of resource to be deleted.
295 * @return ::OC_STACK_OK on success, some other value upon failure.
297 static OCStackResult deleteResource(OCResource *resource);
300 * Delete all of the resources in the resource list.
302 static void deleteAllResources();
305 * Increment resource sequence number. Handles rollover.
307 * @param resPtr Pointer to resource.
309 static void incrementSequenceNumber(OCResource * resPtr);
312 * Attempts to initialize every network interface that the CA Layer might have compiled in.
314 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
315 * return something other than @ref CA_STATUS_OK, then this function fails.
316 * @param transportType OCTransportAdapter value to select.
317 * @return ::CA_STATUS_OK on success, some other value upon failure.
319 static CAResult_t OCSelectNetwork(OCTransportAdapter transportType);
322 * Convert CAResponseResult_t to OCStackResult.
324 * @param caCode CAResponseResult_t code.
325 * @return ::OC_STACK_OK on success, some other value upon failure.
327 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
330 * Convert OCTransportFlags_t to CATransportModifiers_t.
332 * @param ocConType OCTransportFlags_t input.
333 * @return CATransportFlags
335 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
338 * Convert CATransportFlags_t to OCTransportModifiers_t.
340 * @param caConType CATransportFlags_t input.
341 * @return OCTransportFlags
343 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
346 * Handle response from presence request.
348 * @param endPoint CA remote endpoint.
349 * @param responseInfo CA response info.
350 * @return ::OC_STACK_OK on success, some other value upon failure.
352 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
353 const CAResponseInfo_t *responseInfo);
356 * This function will be called back by CA layer when a response is received.
358 * @param endPoint CA remote endpoint.
359 * @param responseInfo CA response info.
361 static void HandleCAResponses(const CAEndpoint_t* endPoint,
362 const CAResponseInfo_t* responseInfo);
365 * This function will be called back by CA layer when a request is received.
367 * @param endPoint CA remote endpoint.
368 * @param requestInfo CA request info.
370 static void HandleCARequests(const CAEndpoint_t* endPoint,
371 const CARequestInfo_t* requestInfo);
374 * Extract query from a URI.
376 * @param uri Full URI with query.
377 * @param query Pointer to string that will contain query.
378 * @param newURI Pointer to string that will contain URI.
379 * @return ::OC_STACK_OK on success, some other value upon failure.
381 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
384 * Finds a resource type in an OCResourceType link-list.
386 * @param resourceTypeList The link-list to be searched through.
387 * @param resourceTypeName The key to search for.
389 * @return Resource type that matches the key (ie. resourceTypeName) or
390 * NULL if there is either an invalid parameter or this function was unable to find the key.
392 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
393 const char * resourceTypeName);
397 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
398 * TTL will be set to maxAge.
400 * @param cbNode Callback Node for which presence ttl is to be reset.
401 * @param maxAge New value of ttl in seconds.
403 * @return ::OC_STACK_OK on success, some other value upon failure.
405 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
409 * Ensure the accept header option is set appropriatly before sending the requests and routing
410 * header option is updated with destination.
412 * @param object CA remote endpoint.
413 * @param requestInfo CA request info.
415 * @return ::OC_STACK_OK on success, some other value upon failure.
417 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
420 * default adapter state change callback method
422 * @param adapter CA network adapter type.
423 * @param enabled current adapter state.
425 static void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled);
428 * default connection state change callback method
430 * @param info CAEndpoint which has address, port and etc.
431 * @param isConnected current connection state.
433 static void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected);
435 //-----------------------------------------------------------------------------
436 // Internal functions
437 //-----------------------------------------------------------------------------
439 bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
441 if (!options || 0 == numOptions)
443 OIC_LOG (INFO, TAG, "No options present");
447 for (uint8_t i = 0; i < numOptions; i++)
449 if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
451 OIC_LOG(DEBUG, TAG, "Proxy URI is present");
458 uint32_t GetTicks(uint32_t milliSeconds)
463 // Guard against overflow of uint32_t
464 if (milliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
465 COAP_TICKS_PER_SECOND)
467 return now + (milliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
475 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
477 VERIFY_NON_NULL_NR(in, FATAL);
478 VERIFY_NON_NULL_NR(out, FATAL);
480 out->adapter = (OCTransportAdapter)in->adapter;
481 out->flags = CAToOCTransportFlags(in->flags);
482 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
483 out->port = in->port;
484 out->ifindex = in->ifindex;
485 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
486 /* This assert is to prevent accidental mismatch between address size macros defined in
487 * RI and CA and cause crash here. */
488 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
489 "Address size mismatch between RI and CA");
490 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
494 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
496 VERIFY_NON_NULL_NR(in, FATAL);
497 VERIFY_NON_NULL_NR(out, FATAL);
499 out->adapter = (CATransportAdapter_t)in->adapter;
500 out->flags = OCToCATransportFlags(in->flags);
501 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
502 OICStrcpy(out->remoteId, sizeof(out->remoteId), in->remoteId);
503 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
504 /* This assert is to prevent accidental mismatch between address size macros defined in
505 * RI and CA and cause crash here. */
506 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
507 "Address size mismatch between RI and CA");
508 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
510 out->port = in->port;
511 out->ifindex = in->ifindex;
514 void FixUpClientResponse(OCClientResponse *cr)
516 VERIFY_NON_NULL_NR(cr, FATAL);
518 cr->addr = &cr->devAddr;
519 cr->connType = (OCConnectivityType)
520 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
523 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
525 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
526 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
527 OIC_TRACE_BEGIN(%s:OCSendRequest, TAG);
529 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
530 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
531 if (OC_STACK_OK != rmResult)
533 OIC_LOG(ERROR, TAG, "Add destination option failed");
539 // OC stack prefer CBOR encoded payloads.
540 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
541 CAResult_t result = CASendRequest(object, requestInfo);
542 if(CA_STATUS_OK != result)
544 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
546 return CAResultToOCResult(result);
552 //-----------------------------------------------------------------------------
553 // Internal API function
554 //-----------------------------------------------------------------------------
556 // This internal function is called to update the stack with the status of
557 // observers and communication failures
558 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
560 OCStackResult result = OC_STACK_ERROR;
561 ResourceObserver * observer = NULL;
562 OCEntityHandlerRequest ehRequest = {0};
566 case OC_OBSERVER_NOT_INTERESTED:
567 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
568 observer = GetObserverUsingToken(token, tokenLength);
571 result = FormOCEntityHandlerRequest(&ehRequest,
575 (OCResourceHandle)NULL,
576 NULL, PAYLOAD_TYPE_REPRESENTATION,
578 OC_OBSERVE_DEREGISTER,
581 if (result != OC_STACK_OK)
583 FreeObserver(observer);
587 if (observer->resource && observer->resource->entityHandler)
589 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
590 observer->resource->entityHandlerCallbackParam);
593 FreeObserver(observer);
596 result = DeleteObserverUsingToken(token, tokenLength);
597 if (result == OC_STACK_OK)
599 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
603 result = OC_STACK_OK;
604 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
608 case OC_OBSERVER_STILL_INTERESTED:
609 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
610 observer = GetObserverUsingToken(token, tokenLength);
613 observer->forceHighQos = 0;
614 observer->failedCommCount = 0;
615 result = OC_STACK_OK;
616 FreeObserver(observer);
620 result = OC_STACK_OBSERVER_NOT_FOUND;
624 case OC_OBSERVER_FAILED_COMM:
625 OIC_LOG(DEBUG, TAG, "observer is unreachable");
626 observer = GetObserverUsingToken (token, tokenLength);
629 if (observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
631 result = FormOCEntityHandlerRequest(&ehRequest,
635 (OCResourceHandle)NULL,
636 NULL, PAYLOAD_TYPE_REPRESENTATION,
638 OC_OBSERVE_DEREGISTER,
641 if (result != OC_STACK_OK)
643 FreeObserver(observer);
644 return OC_STACK_ERROR;
647 if (observer->resource && observer->resource->entityHandler)
649 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
650 observer->resource->entityHandlerCallbackParam);
653 result = DeleteObserverUsingToken(token, tokenLength);
654 if (result == OC_STACK_OK)
656 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
660 result = OC_STACK_OK;
661 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
666 observer->failedCommCount++;
667 observer->forceHighQos = 1;
668 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",
669 observer->failedCommCount);
670 result = OC_STACK_CONTINUE;
673 FreeObserver(observer);
677 OIC_LOG(ERROR, TAG, "Unknown status");
678 result = OC_STACK_ERROR;
684 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
686 OCStackResult ret = OC_STACK_ERROR;
690 ret = OC_STACK_RESOURCE_CREATED;
693 ret = OC_STACK_RESOURCE_DELETED;
696 ret = OC_STACK_RESOURCE_CHANGED;
703 ret = OC_STACK_INVALID_QUERY;
705 case CA_UNAUTHORIZED_REQ:
706 ret = OC_STACK_UNAUTHORIZED_REQ;
709 ret = OC_STACK_INVALID_OPTION;
712 ret = OC_STACK_NO_RESOURCE;
714 case CA_REQUEST_ENTITY_TOO_LARGE:
715 ret = OC_STACK_TOO_LARGE_REQ;
717 case CA_METHOD_NOT_ALLOWED:
718 ret = OC_STACK_METHOD_NOT_ALLOWED;
720 case CA_NOT_ACCEPTABLE:
721 ret = OC_STACK_NOT_ACCEPTABLE;
723 case CA_FORBIDDEN_REQ:
724 ret = OC_STACK_FORBIDDEN_REQ;
726 case CA_TOO_MANY_REQUESTS:
727 ret = OC_STACK_TOO_MANY_REQUESTS;
729 case CA_INTERNAL_SERVER_ERROR:
730 ret = OC_STACK_INTERNAL_SERVER_ERROR;
732 case CA_NOT_IMPLEMENTED:
733 ret = OC_STACK_NOT_IMPLEMENTED;
736 ret = OC_STACK_BAD_GATEWAY;
738 case CA_SERVICE_UNAVAILABLE:
739 ret = OC_STACK_SERVICE_UNAVAILABLE;
741 case CA_RETRANSMIT_TIMEOUT:
742 ret = OC_STACK_GATEWAY_TIMEOUT;
744 case CA_PROXY_NOT_SUPPORTED:
745 ret = OC_STACK_PROXY_NOT_SUPPORTED;
753 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
755 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
764 // This Response Code is like HTTP 204 "No Content" but only used in
765 // response to POST and PUT requests.
769 // This Response Code is like HTTP 200 "OK" but only used in response to
774 // This should not happen but,
775 // give it a value just in case but output an error
777 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
781 case OC_STACK_RESOURCE_CREATED:
784 case OC_STACK_RESOURCE_DELETED:
787 case OC_STACK_RESOURCE_CHANGED:
790 case OC_STACK_INVALID_QUERY:
793 case OC_STACK_INVALID_OPTION:
796 case OC_STACK_NO_RESOURCE:
799 case OC_STACK_COMM_ERROR:
800 ret = CA_RETRANSMIT_TIMEOUT;
802 case OC_STACK_METHOD_NOT_ALLOWED:
803 ret = CA_METHOD_NOT_ALLOWED;
805 case OC_STACK_NOT_ACCEPTABLE:
806 ret = CA_NOT_ACCEPTABLE;
808 case OC_STACK_UNAUTHORIZED_REQ:
809 ret = CA_UNAUTHORIZED_REQ;
811 case OC_STACK_FORBIDDEN_REQ:
812 ret = CA_FORBIDDEN_REQ;
814 case OC_STACK_TOO_MANY_REQUESTS:
815 ret = CA_TOO_MANY_REQUESTS;
817 case OC_STACK_INTERNAL_SERVER_ERROR:
818 ret = CA_INTERNAL_SERVER_ERROR;
820 case OC_STACK_NOT_IMPLEMENTED:
821 ret = CA_NOT_IMPLEMENTED;
823 case OC_STACK_BAD_GATEWAY:
824 ret = CA_BAD_GATEWAY;
826 case OC_STACK_SERVICE_UNAVAILABLE:
827 ret = CA_SERVICE_UNAVAILABLE;
829 case OC_STACK_GATEWAY_TIMEOUT:
830 ret = CA_RETRANSMIT_TIMEOUT;
832 case OC_STACK_PROXY_NOT_SUPPORTED:
833 ret = CA_PROXY_NOT_SUPPORTED;
841 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
843 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
845 // supply default behavior.
846 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
848 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
850 if ((caFlags & OC_MASK_SCOPE) == 0)
852 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
857 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
859 return (OCTransportFlags)caFlags;
863 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
865 uint32_t lowerBound = 0;
866 uint32_t higherBound = 0;
868 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
870 return OC_STACK_INVALID_PARAM;
873 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
875 cbNode->presence->TTL = maxAgeSeconds;
877 for (int index = 0; index < PresenceTimeOutSize; index++)
879 // Guard against overflow
880 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
883 lowerBound = GetTicks((PresenceTimeOut[index] *
884 cbNode->presence->TTL *
885 MILLISECONDS_PER_SECOND)/100);
889 lowerBound = GetTicks(UINT32_MAX);
892 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
895 higherBound = GetTicks((PresenceTimeOut[index + 1] *
896 cbNode->presence->TTL *
897 MILLISECONDS_PER_SECOND)/100);
901 higherBound = GetTicks(UINT32_MAX);
904 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
906 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
907 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
908 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
911 cbNode->presence->TTLlevel = 0;
913 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
917 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
919 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
921 return OC_RSRVD_TRIGGER_CREATE;
923 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
925 return OC_RSRVD_TRIGGER_CHANGE;
929 return OC_RSRVD_TRIGGER_DELETE;
933 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
937 return OC_PRESENCE_TRIGGER_CREATE;
939 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
941 return OC_PRESENCE_TRIGGER_CREATE;
943 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
945 return OC_PRESENCE_TRIGGER_CHANGE;
949 return OC_PRESENCE_TRIGGER_DELETE;
952 #endif // WITH_PRESENCE
954 OCStackResult OCEncodeAddressForRFC6874(char *outputAddress,
956 const char *inputAddress)
958 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
959 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
961 size_t inputLength = strnlen(inputAddress, outputSize);
963 // inputSize includes the null terminator
964 size_t inputSize = inputLength + 1;
966 if (inputSize > outputSize)
968 OIC_LOG_V(ERROR, TAG,
969 "OCEncodeAddressForRFC6874 failed: "
970 "outputSize (%zu) < inputSize (%zu)",
971 outputSize, inputSize);
973 return OC_STACK_ERROR;
976 char* percentChar = strchr(inputAddress, '%');
978 // If there is no '%' character, then no change is required to the string.
979 if (NULL == percentChar)
981 OICStrcpy(outputAddress, outputSize, inputAddress);
985 const char* addressPart = &inputAddress[0];
986 const char* scopeIdPart = percentChar + 1;
988 // Sanity check to make sure this string doesn't have more '%' characters
989 if (NULL != strchr(scopeIdPart, '%'))
991 return OC_STACK_ERROR;
994 // If no string follows the first '%', then the input was invalid.
995 if (scopeIdPart[0] == '\0')
997 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
998 return OC_STACK_ERROR;
1001 // Check to see if the string is already encoded
1002 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
1004 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Input string is already encoded");
1005 return OC_STACK_ERROR;
1008 // Fail if we don't have room for encoded string's two additional chars
1009 if (outputSize < (inputSize + 2))
1011 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: encoded output will not fit!");
1012 return OC_STACK_ERROR;
1015 // Restore the null terminator with an escaped '%' character, per RFC 6874
1016 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
1017 OICStrcat(outputAddress, outputSize, "%25");
1018 OICStrcat(outputAddress, outputSize, scopeIdPart);
1023 OCStackResult OCDecodeAddressForRFC6874(char *outputAddress,
1025 const char *inputAddress,
1028 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
1029 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
1033 end = inputAddress + strlen(inputAddress);
1035 size_t inputLength = end - inputAddress;
1037 const char *percent = strchr(inputAddress, '%');
1038 if (!percent || (percent > end))
1040 OICStrcpyPartial(outputAddress, outputSize, inputAddress, inputLength);
1044 if (percent[1] != '2' || percent[2] != '5')
1046 return OC_STACK_INVALID_URI;
1049 int addrlen = percent - inputAddress + 1;
1050 OICStrcpyPartial(outputAddress, outputSize, inputAddress, addrlen);
1051 OICStrcpyPartial(outputAddress + addrlen, outputSize - addrlen,
1052 percent + 3, end - percent - 3);
1058 #ifdef WITH_PRESENCE
1060 * The cononical presence allows constructed URIs to be string compared.
1062 * requestUri must be a char array of size CA_MAX_URI_LENGTH
1064 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
1065 char *presenceUri, bool isMulticast)
1067 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
1068 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1072 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1073 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1076 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1077 if (ep->adapter == CA_ADAPTER_IP)
1079 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1081 if ('\0' == ep->addr[0]) // multicast
1083 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1087 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1089 OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1090 sizeof(addressEncoded),
1093 if (OC_STACK_OK != result)
1098 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1099 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1104 if ('\0' == ep->addr[0]) // multicast
1106 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1107 ep->port = OC_MULTICAST_PORT;
1109 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1110 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1114 // might work for other adapters (untested, but better than nothing)
1115 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1116 OC_RSRVD_PRESENCE_URI);
1120 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1121 const CAResponseInfo_t *responseInfo)
1123 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1124 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1126 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1127 ClientCB * cbNode = NULL;
1128 char *resourceTypeName = NULL;
1129 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1130 OCStackResult result = OC_STACK_ERROR;
1131 uint32_t maxAge = 0;
1133 char presenceUri[CA_MAX_URI_LENGTH];
1135 int presenceSubscribe = 0;
1136 int multicastPresenceSubscribe = 0;
1138 if (responseInfo->result != CA_CONTENT)
1140 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1141 return OC_STACK_ERROR;
1144 response.payload = NULL;
1145 response.result = OC_STACK_OK;
1147 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1148 FixUpClientResponse(&response);
1150 if (responseInfo->info.payload)
1152 result = OCParsePayload(&response.payload,
1153 PAYLOAD_TYPE_PRESENCE,
1154 responseInfo->info.payload,
1155 responseInfo->info.payloadSize);
1157 if(result != OC_STACK_OK)
1159 OIC_LOG(ERROR, TAG, "Presence parse failed");
1162 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1164 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1165 result = OC_STACK_ERROR;
1168 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1169 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1170 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1173 // check for unicast presence
1174 uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1175 responseInfo->isMulticast);
1176 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1178 return OC_STACK_INVALID_URI;
1180 OIC_LOG(INFO, TAG, "check for unicast presence");
1181 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1184 presenceSubscribe = 1;
1188 // check for multicast presence
1189 OIC_LOG(INFO, TAG, "check for multicast presence");
1190 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1193 multicastPresenceSubscribe = 1;
1197 if (!presenceSubscribe && !multicastPresenceSubscribe)
1199 OIC_LOG(INFO, TAG, "Received a presence notification, "
1200 "but need to register presence callback, ignoring");
1204 if (presenceSubscribe)
1206 if(cbNode->sequenceNumber == response.sequenceNumber)
1208 OIC_LOG(INFO, TAG, "No presence change");
1209 ResetPresenceTTL(cbNode, maxAge);
1210 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1216 OIC_LOG(INFO, TAG, "Stopping presence");
1217 response.result = OC_STACK_PRESENCE_STOPPED;
1218 if(cbNode->presence)
1220 OICFree(cbNode->presence->timeOut);
1221 OICFree(cbNode->presence);
1222 cbNode->presence = NULL;
1227 if(!cbNode->presence)
1229 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1231 if(!(cbNode->presence))
1233 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1234 result = OC_STACK_NO_MEMORY;
1238 VERIFY_NON_NULL_V(cbNode->presence);
1239 cbNode->presence->timeOut = NULL;
1240 cbNode->presence->timeOut = (uint32_t *)
1241 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1242 if(!(cbNode->presence->timeOut)){
1244 "Could not allocate memory for cbNode->presence->timeOut");
1245 OICFree(cbNode->presence);
1246 cbNode->presence = NULL;
1247 result = OC_STACK_NO_MEMORY;
1252 ResetPresenceTTL(cbNode, maxAge);
1254 cbNode->sequenceNumber = response.sequenceNumber;
1259 // This is the multicast case
1260 OIC_LOG(INFO, TAG, "this is the multicast presence");
1263 OIC_LOG(INFO, TAG, "Stopping presence");
1264 response.result = OC_STACK_PRESENCE_STOPPED;
1268 // Ensure that a filter is actually applied.
1269 if (resourceTypeName && cbNode->filterResourceType)
1271 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1272 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1278 OIC_LOG(INFO, TAG, "Before calling into application address space for presence");
1279 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1280 OIC_LOG(INFO, TAG, "After calling into application address space for presence");
1282 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1284 FindAndDeleteClientCB(cbNode);
1288 OCPayloadDestroy(response.payload);
1291 #endif // WITH_PRESENCE
1293 OCStackResult HandleBatchResponse(char *requestUri, OCRepPayload **payload)
1295 if (requestUri && *payload)
1297 char *interfaceName = NULL;
1298 char *rtTypeName = NULL;
1299 char *uriQuery = NULL;
1300 char *uriWithoutQuery = NULL;
1301 if (OC_STACK_OK == getQueryFromUri(requestUri, &uriQuery, &uriWithoutQuery))
1303 if (OC_STACK_OK == ExtractFiltersFromQuery(uriQuery, &interfaceName, &rtTypeName))
1305 if (interfaceName && (0 == strcmp(OC_RSRVD_INTERFACE_BATCH, interfaceName)))
1307 char *uri = (*payload)->uri;
1308 if (uri && 0 != strcmp(uriWithoutQuery, uri))
1310 OCRepPayload *newPayload = OCRepPayloadCreate();
1313 OCRepPayloadSetUri(newPayload, uri);
1314 newPayload->next = *payload;
1315 *payload = newPayload;
1322 OICFree(interfaceName);
1323 OICFree(rtTypeName);
1325 OICFree(uriWithoutQuery);
1328 return OC_STACK_INVALID_PARAM;
1331 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1333 OIC_TRACE_MARK(%s:OCHandleResponse:%s, TAG, responseInfo->info.resourceUri);
1334 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1336 #ifdef WITH_PRESENCE
1337 if(responseInfo->info.resourceUri &&
1338 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1340 HandlePresenceResponse(endPoint, responseInfo);
1345 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1346 responseInfo->info.tokenLength, NULL, NULL);
1350 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1352 // check obs header option
1353 bool obsHeaderOpt = false;
1354 CAHeaderOption_t *options = responseInfo->info.options;
1355 for (uint8_t i = 0; i< responseInfo->info.numOptions; i++)
1357 if (options && options[i].protocolID == CA_COAP_ID &&
1358 options[i].optionID == COAP_OPTION_OBSERVE)
1360 obsHeaderOpt = true;
1365 if(responseInfo->result == CA_EMPTY)
1367 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1368 // We do not have a case for the client to receive a RESET
1369 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1371 //This is the case of receiving an ACK on a request to a slow resource!
1372 OIC_LOG(INFO, TAG, "This is a pure ACK");
1373 //TODO: should we inform the client
1374 // app that at least the request was received at the server?
1377 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1379 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1381 OCClientResponse response =
1382 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1383 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1384 FixUpClientResponse(&response);
1385 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1386 memcpy(response.identity.id, responseInfo->info.identity.id,
1387 sizeof (response.identity.id));
1388 response.identity.id_length = responseInfo->info.identity.id_length;
1390 response.result = CAResponseToOCStackResult(responseInfo->result);
1391 OIC_LOG(INFO, TAG, "Before calling into application address space for reTrans timeout");
1392 cbNode->callBack(cbNode->context,
1393 cbNode->handle, &response);
1394 OIC_LOG(INFO, TAG, "After calling into application address space for reTrans timeout");
1395 FindAndDeleteClientCB(cbNode);
1396 OICFree((void *)response.resourceUri);
1399 else if ((cbNode->method == OC_REST_OBSERVE || cbNode->method == OC_REST_OBSERVE_ALL)
1400 && (responseInfo->result == CA_CONTENT) && !obsHeaderOpt)
1402 OCClientResponse response =
1403 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1404 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1405 FixUpClientResponse(&response);
1406 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1407 memcpy(response.identity.id, responseInfo->info.identity.id,
1408 sizeof (response.identity.id));
1409 response.identity.id_length = responseInfo->info.identity.id_length;
1410 response.result = OC_STACK_UNAUTHORIZED_REQ;
1412 OIC_LOG(INFO, TAG, "Before calling into application address space for observe resp");
1413 cbNode->callBack(cbNode->context,
1416 OIC_LOG(INFO, TAG, "After calling into application address space for observe resp");
1418 FindAndDeleteClientCB(cbNode);
1419 OICFree(response.resourceUri);
1424 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1426 OCClientResponse response;
1427 memset(&response, 0, sizeof(OCClientResponse));
1428 response.devAddr.adapter = OC_DEFAULT_ADAPTER;
1430 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1431 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1432 FixUpClientResponse(&response);
1433 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1434 memcpy(response.identity.id, responseInfo->info.identity.id,
1435 sizeof (response.identity.id));
1436 response.identity.id_length = responseInfo->info.identity.id_length;
1438 response.result = CAResponseToOCStackResult(responseInfo->result);
1440 if(responseInfo->info.payload &&
1441 responseInfo->info.payloadSize)
1443 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1444 // check the security resource
1445 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1447 type = PAYLOAD_TYPE_SECURITY;
1449 else if (cbNode->method == OC_REST_DISCOVER)
1451 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1452 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1454 type = PAYLOAD_TYPE_DISCOVERY;
1457 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1459 type = PAYLOAD_TYPE_DISCOVERY;
1462 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1464 type = PAYLOAD_TYPE_REPRESENTATION;
1466 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1468 type = PAYLOAD_TYPE_REPRESENTATION;
1471 #ifdef ROUTING_GATEWAY
1472 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1474 type = PAYLOAD_TYPE_REPRESENTATION;
1477 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1479 type = PAYLOAD_TYPE_REPRESENTATION;
1482 else if (strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1484 type = PAYLOAD_TYPE_REPRESENTATION;
1489 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1490 cbNode->method, cbNode->requestUri);
1491 OICFree((void *)response.resourceUri);
1495 else if (cbNode->method == OC_REST_GET ||
1496 cbNode->method == OC_REST_PUT ||
1497 cbNode->method == OC_REST_POST ||
1498 cbNode->method == OC_REST_OBSERVE ||
1499 cbNode->method == OC_REST_OBSERVE_ALL ||
1500 cbNode->method == OC_REST_DELETE)
1502 if (cbNode->requestUri)
1504 if (0 == strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri))
1506 type = PAYLOAD_TYPE_REPRESENTATION;
1508 else if (0 == strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri))
1510 type = PAYLOAD_TYPE_REPRESENTATION;
1512 if (type == PAYLOAD_TYPE_INVALID)
1514 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1515 cbNode->method, cbNode->requestUri);
1516 type = PAYLOAD_TYPE_REPRESENTATION;
1521 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1522 type = PAYLOAD_TYPE_REPRESENTATION;
1527 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1528 cbNode->method, cbNode->requestUri);
1529 OICFree((void *)response.resourceUri);
1533 // In case of error, still want application to receive the error message.
1534 if (OCResultToSuccess(response.result) || PAYLOAD_TYPE_REPRESENTATION == type)
1536 if(OC_STACK_OK != OCParsePayload(&response.payload,
1538 responseInfo->info.payload,
1539 responseInfo->info.payloadSize))
1541 OIC_LOG(ERROR, TAG, "Error converting payload");
1542 OCPayloadDestroy(response.payload);
1543 OICFree((void *)response.resourceUri);
1549 OICFree((void *)response.resourceUri);
1550 response.resourceUri = OICStrdup(cbNode->requestUri);
1554 response.numRcvdVendorSpecificHeaderOptions = 0;
1555 if(responseInfo->info.numOptions > 0)
1558 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1559 if(responseInfo->info.options
1560 && responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1563 uint32_t observationOption;
1564 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1565 for (observationOption=0, i=0;
1566 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1570 (observationOption << 8) | optionData[i];
1572 response.sequenceNumber = observationOption;
1573 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1578 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1581 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1583 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1584 OCPayloadDestroy(response.payload);
1585 OICFree((void *)response.resourceUri);
1589 if (response.numRcvdVendorSpecificHeaderOptions > 0)
1591 response.rcvdVendorSpecificHeaderOptions =
1592 (OCHeaderOption *) OICCalloc(response.numRcvdVendorSpecificHeaderOptions, sizeof(OCHeaderOption));
1593 if (NULL == response.rcvdVendorSpecificHeaderOptions)
1595 OIC_LOG(ERROR, TAG, "Failed to allocate memory for vendor header options");
1596 OCPayloadDestroy(response.payload);
1597 OICFree((void *)response.resourceUri);
1601 memcpy(response.rcvdVendorSpecificHeaderOptions, responseInfo->info.options + start,
1602 response.numRcvdVendorSpecificHeaderOptions*sizeof(OCHeaderOption));
1606 if (cbNode->method == OC_REST_OBSERVE &&
1607 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1608 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1609 response.sequenceNumber <= cbNode->sequenceNumber)
1611 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1612 response.sequenceNumber);
1617 if (cbNode->requestUri)
1619 // if request uri is '/oic/rd', update ins value of resource.
1620 char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
1623 OCUpdateResourceInsWithResponse(cbNode->requestUri, &response);
1627 // set remoteID(device ID) into OCClientResponse callback parameter
1628 if (OC_REST_DISCOVER == cbNode->method)
1630 OIC_LOG(INFO, TAG, "cbNode method is OC_REST_DISCOVER");
1631 OCDiscoveryPayload *payload = (OCDiscoveryPayload*) response.payload;
1632 // Payload can be empty in case of error message.
1633 if (payload && payload->sid)
1635 OICStrcpy(response.devAddr.remoteId, sizeof(response.devAddr.remoteId),
1637 OIC_LOG_V(INFO_PRIVATE, TAG, "Device ID of response : %s",
1638 response.devAddr.remoteId);
1641 if(NULL == response.resourceUri)
1643 response.resourceUri = OICStrdup(cbNode->requestUri);
1647 if (cbNode->requestUri)
1649 OIC_LOG_V(INFO, TAG, "cbNode requestUri is %s", cbNode->requestUri);
1650 if (cbNode->method == OC_REST_POST &&
1651 strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1653 OCHandleKeepAliveResponse(endPoint, response.payload);
1657 if (response.payload && response.payload->type == PAYLOAD_TYPE_REPRESENTATION)
1659 OIC_LOG(INFO, TAG, "Handle batch response");
1660 HandleBatchResponse(cbNode->requestUri, (OCRepPayload **)&response.payload);
1663 OIC_LOG(INFO, TAG, "Before calling into application address space for handleResponse");
1664 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1667 OIC_LOG(INFO, TAG, "After calling into application address space for handleResponse");
1669 cbNode->sequenceNumber = response.sequenceNumber;
1671 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1673 FindAndDeleteClientCB(cbNode);
1677 // To keep discovery callbacks active.
1678 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1679 MILLISECONDS_PER_SECOND);
1683 //Need to send ACK when the response is CON
1684 if(responseInfo->info.type == CA_MSG_CONFIRM)
1686 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1688 OIC_LOG(INFO, TAG, "Received a confirmable message. Sending EMPTY");
1689 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1690 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1694 OICFree((void *)response.resourceUri);
1695 OCPayloadDestroy(response.payload);
1696 OICFree(response.rcvdVendorSpecificHeaderOptions);
1701 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1702 responseInfo->info.tokenLength);
1706 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1707 if(responseInfo->result == CA_EMPTY)
1709 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1710 if(responseInfo->info.type == CA_MSG_RESET)
1712 OIC_LOG(INFO, TAG, "This is a RESET");
1713 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1714 OC_OBSERVER_NOT_INTERESTED);
1716 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1718 OIC_LOG(INFO, TAG, "This is a pure ACK");
1719 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1720 OC_OBSERVER_STILL_INTERESTED);
1723 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1725 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1726 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1727 OC_OBSERVER_FAILED_COMM);
1730 FreeObserver(observer);
1734 if(!cbNode && !observer)
1736 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1737 || myStackMode == OC_GATEWAY)
1739 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1740 if(responseInfo->result == CA_EMPTY)
1742 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1746 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1748 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1749 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1750 CA_MSG_RESET, 0, NULL, NULL, 0, NULL,
1751 CA_RESPONSE_FOR_RES);
1756 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1757 || myStackMode == OC_GATEWAY)
1759 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1760 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1762 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1763 responseInfo->info.messageId);
1765 if (responseInfo->info.type == CA_MSG_RESET)
1767 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1768 responseInfo->info.messageId);
1776 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1778 VERIFY_NON_NULL_NR(endPoint, FATAL);
1779 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1781 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1782 OIC_TRACE_BEGIN(%s:HandleCAResponses, TAG);
1784 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1785 #ifdef ROUTING_GATEWAY
1786 bool needRIHandling = false;
1788 * Routing manager is going to update either of endpoint or response or both.
1789 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1790 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1793 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1795 if(ret != OC_STACK_OK || !needRIHandling)
1797 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1804 * Put source in sender endpoint so that the next packet from application can be routed to
1805 * proper destination and remove "RM" coap header option before passing request / response to
1806 * RI as this option will make no sense to either RI or application.
1808 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1809 (uint8_t *) &(responseInfo->info.numOptions),
1810 (CAEndpoint_t *) endPoint);
1813 OCHandleResponse(endPoint, responseInfo);
1815 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1819 * This function handles error response from CA
1820 * code shall be added to handle the errors
1822 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1824 VERIFY_NON_NULL_NR(endPoint, FATAL);
1825 VERIFY_NON_NULL_NR(errorInfo, FATAL);
1827 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1828 OIC_TRACE_BEGIN(%s:HandleCAErrorResponse, TAG);
1830 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1831 errorInfo->info.tokenLength, NULL, NULL);
1834 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1835 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1836 FixUpClientResponse(&response);
1837 response.resourceUri = errorInfo->info.resourceUri;
1838 memcpy(response.identity.id, errorInfo->info.identity.id,
1839 sizeof (response.identity.id));
1840 response.identity.id_length = errorInfo->info.identity.id_length;
1841 response.result = CAResultToOCResult(errorInfo->result);
1843 OIC_LOG(INFO, TAG, "Before calling into application address space for error response");
1844 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1845 OIC_LOG(INFO, TAG, "After calling into application address space for error response");
1848 ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1849 errorInfo->info.tokenLength);
1852 OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1853 OCStackResult result = CAResultToOCResult(errorInfo->result);
1854 if (OC_STACK_COMM_ERROR == result)
1856 OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1857 OC_OBSERVER_FAILED_COMM);
1861 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1866 * This function sends out Direct Stack Responses. These are responses that are not coming
1867 * from the application entity handler. These responses have no payload and are usually ACKs,
1868 * RESETs or some error conditions that were caught by the stack.
1870 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1871 const CAResponseResult_t responseResult, const CAMessageType_t type,
1872 const uint8_t numOptions, const CAHeaderOption_t *options,
1873 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1874 CADataType_t dataType)
1876 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1878 if (endPoint->flags & CA_MULTICAST)
1880 OIC_LOG(ERROR, TAG, "It is unnecessary to respond to a multicast request");
1884 CAResponseInfo_t respInfo = { .result = responseResult };
1885 respInfo.info.messageId = coapID;
1886 respInfo.info.numOptions = numOptions;
1888 if (respInfo.info.numOptions)
1890 respInfo.info.options =
1891 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1892 memcpy (respInfo.info.options, options,
1893 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1897 respInfo.info.payload = NULL;
1898 respInfo.info.token = token;
1899 respInfo.info.tokenLength = tokenLength;
1900 respInfo.info.type = type;
1901 respInfo.info.resourceUri = OICStrdup (resourceUri);
1902 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1903 respInfo.info.dataType = dataType;
1905 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1906 // Add the destination to route option from the endpoint->routeData.
1907 bool doPost = false;
1908 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1909 if(OC_STACK_OK != result)
1911 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1912 OICFree (respInfo.info.resourceUri);
1913 OICFree (respInfo.info.options);
1918 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1919 CARequestInfo_t reqInfo = {.method = CA_POST };
1920 /* The following initialization is not done in a single initializer block as in
1921 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1922 * does not have designated initalizers. This is a work-around for now.
1924 reqInfo.info.type = CA_MSG_NONCONFIRM;
1925 reqInfo.info.messageId = coapID;
1926 reqInfo.info.tokenLength = tokenLength;
1927 reqInfo.info.token = token;
1928 reqInfo.info.numOptions = respInfo.info.numOptions;
1929 reqInfo.info.payload = NULL;
1930 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1931 if (reqInfo.info.numOptions)
1933 reqInfo.info.options =
1934 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1935 if (NULL == reqInfo.info.options)
1937 OIC_LOG(ERROR, TAG, "Calloc failed");
1938 OICFree (reqInfo.info.resourceUri);
1939 OICFree (respInfo.info.resourceUri);
1940 OICFree (respInfo.info.options);
1941 return OC_STACK_NO_MEMORY;
1943 memcpy (reqInfo.info.options, respInfo.info.options,
1944 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1947 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1948 OICFree (reqInfo.info.resourceUri);
1949 OICFree (reqInfo.info.options);
1950 OICFree (respInfo.info.resourceUri);
1951 OICFree (respInfo.info.options);
1952 if (CA_STATUS_OK != caResult)
1954 OIC_LOG(ERROR, TAG, "CASendRequest error");
1955 return CAResultToOCResult(caResult);
1961 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1963 // resourceUri in the info field is cloned in the CA layer and
1964 // thus ownership is still here.
1965 OICFree (respInfo.info.resourceUri);
1966 OICFree (respInfo.info.options);
1967 if(CA_STATUS_OK != caResult)
1969 OIC_LOG(ERROR, TAG, "CASendResponse error");
1970 return CAResultToOCResult(caResult);
1973 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1977 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1979 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1980 OCStackResult result = OC_STACK_ERROR;
1981 if(!protocolRequest)
1983 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1984 return OC_STACK_INVALID_PARAM;
1987 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1988 protocolRequest->tokenLength);
1991 OIC_LOG(INFO, TAG, "This is a new Server Request");
1992 result = AddServerRequest(&request, protocolRequest->coapID,
1993 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1994 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1995 protocolRequest->observationOption, protocolRequest->qos,
1996 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1997 protocolRequest->payload, protocolRequest->requestToken,
1998 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1999 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
2000 &protocolRequest->devAddr);
2001 if (OC_STACK_OK != result)
2003 OIC_LOG(ERROR, TAG, "Error adding server request");
2009 OIC_LOG(ERROR, TAG, "Out of Memory");
2010 return OC_STACK_NO_MEMORY;
2013 if(!protocolRequest->reqMorePacket)
2015 request->requestComplete = 1;
2020 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
2023 if(request->requestComplete)
2025 OIC_LOG(INFO, TAG, "This Server Request is complete");
2026 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2027 OCResource *resource = NULL;
2028 result = DetermineResourceHandling (request, &resHandling, &resource);
2029 if (result == OC_STACK_OK)
2031 result = ProcessRequest(resHandling, resource, request);
2036 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2037 result = OC_STACK_CONTINUE;
2042 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2044 OIC_TRACE_MARK(%s:OCHandleRequests:%s, TAG, requestInfo->info.resourceUri);
2045 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2047 OCStackResult requestResult = OC_STACK_ERROR;
2049 if(myStackMode == OC_CLIENT)
2051 //TODO: should the client be responding to requests?
2055 OCServerProtocolRequest serverRequest = {0};
2057 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2059 char * uriWithoutQuery = NULL;
2060 char * query = NULL;
2062 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2064 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2066 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2069 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2070 OIC_LOG_V(INFO, TAG, "Query : %s", query);
2072 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2074 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2075 OICFree(uriWithoutQuery);
2079 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2080 OICFree(uriWithoutQuery);
2087 if(strlen(query) < MAX_QUERY_LENGTH)
2089 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2094 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2100 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2102 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2103 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2104 if (!serverRequest.payload)
2106 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2109 memcpy (serverRequest.payload, requestInfo->info.payload,
2110 requestInfo->info.payloadSize);
2114 serverRequest.reqTotalSize = 0;
2117 switch (requestInfo->method)
2120 serverRequest.method = OC_REST_GET;
2123 serverRequest.method = OC_REST_PUT;
2126 serverRequest.method = OC_REST_POST;
2129 serverRequest.method = OC_REST_DELETE;
2132 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2133 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2134 requestInfo->info.type, requestInfo->info.numOptions,
2135 requestInfo->info.options, requestInfo->info.token,
2136 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2138 OICFree(serverRequest.payload);
2142 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2143 requestInfo->info.tokenLength);
2145 serverRequest.tokenLength = requestInfo->info.tokenLength;
2146 if (serverRequest.tokenLength) {
2148 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2150 if (!serverRequest.requestToken)
2152 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2153 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2154 requestInfo->info.type, requestInfo->info.numOptions,
2155 requestInfo->info.options, requestInfo->info.token,
2156 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2158 OICFree(serverRequest.payload);
2161 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2164 switch (requestInfo->info.acceptFormat)
2166 case CA_FORMAT_APPLICATION_CBOR:
2167 serverRequest.acceptFormat = OC_FORMAT_CBOR;
2169 case CA_FORMAT_UNDEFINED:
2170 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2173 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2176 if (requestInfo->info.type == CA_MSG_CONFIRM)
2178 serverRequest.qos = OC_HIGH_QOS;
2182 serverRequest.qos = OC_LOW_QOS;
2184 // CA does not need the following field
2185 // Are we sure CA does not need them? how is it responding to multicast
2186 serverRequest.delayedResNeeded = 0;
2188 serverRequest.coapID = requestInfo->info.messageId;
2190 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2192 // copy vendor specific header options
2193 uint8_t tempNum = (requestInfo->info.numOptions);
2195 // Assume no observation requested and it is a pure GET.
2196 // If obs registration/de-registration requested it'll be fetched from the
2197 // options in GetObserveHeaderOption()
2198 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2200 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2201 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2204 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2205 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2206 requestInfo->info.type, requestInfo->info.numOptions,
2207 requestInfo->info.options, requestInfo->info.token,
2208 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2210 OICFree(serverRequest.payload);
2211 OICFree(serverRequest.requestToken);
2215 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2216 if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2218 serverRequest.rcvdVendorSpecificHeaderOptions = (OCHeaderOption*) OICCalloc(tempNum, sizeof(OCHeaderOption));
2219 if (NULL == serverRequest.rcvdVendorSpecificHeaderOptions)
2221 OIC_LOG(ERROR, TAG, "Failed to allocated memory to vnd header options!");
2222 OICFree(serverRequest.payload);
2223 OICFree(serverRequest.requestToken);
2227 memcpy (serverRequest.rcvdVendorSpecificHeaderOptions, requestInfo->info.options,
2228 sizeof(CAHeaderOption_t)*tempNum);
2231 requestResult = HandleStackRequests (&serverRequest);
2233 // Send ACK to client as precursor to slow response
2234 if (requestResult == OC_STACK_SLOW_RESOURCE)
2236 if (requestInfo->info.type == CA_MSG_CONFIRM)
2238 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2239 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2244 if (requestResult == OC_STACK_RESOURCE_ERROR
2245 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2247 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2250 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2252 if (requestResult == OC_STACK_RESOURCE_ERROR)
2254 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2256 else if (!OCResultToSuccess(requestResult))
2258 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2262 else if(!OCResultToSuccess(requestResult))
2264 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2266 // Delete observer node if it is OBSERVE failure from app
2267 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2269 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2272 CAResponseResult_t stackResponse =
2273 OCToCAStackResult(requestResult, serverRequest.method);
2275 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2276 requestInfo->info.type, requestInfo->info.numOptions,
2277 requestInfo->info.options, requestInfo->info.token,
2278 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2281 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2282 // The token is copied in there, and is thus still owned by this function.
2283 OICFree(serverRequest.payload);
2284 OICFree(serverRequest.requestToken);
2285 OICFree(serverRequest.rcvdVendorSpecificHeaderOptions);
2286 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2289 //This function will be called back by CA layer when a request is received
2290 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2292 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2293 OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2296 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2303 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2308 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2309 #ifdef ROUTING_GATEWAY
2310 bool needRIHandling = false;
2311 bool isEmptyMsg = false;
2313 * Routing manager is going to update either of endpoint or request or both.
2314 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2315 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2316 * destination. It can also remove "RM" coap header option before passing request / response to
2317 * RI as this option will make no sense to either RI or application.
2319 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2320 &needRIHandling, &isEmptyMsg);
2321 if(OC_STACK_OK != ret || !needRIHandling)
2323 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2330 * Put source in sender endpoint so that the next packet from application can be routed to
2331 * proper destination and remove RM header option.
2333 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2334 (uint8_t *) &(requestInfo->info.numOptions),
2335 (CAEndpoint_t *) endPoint);
2337 #ifdef ROUTING_GATEWAY
2341 * In Gateways, the MSGType in route option is used to check if the actual
2342 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2343 * EMPTY response is sent in the form of POST request which need to be changed
2344 * to a EMPTY response by RM. This translation is done in this part of the code.
2346 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2347 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2348 .info.messageId = requestInfo->info.messageId,
2349 .info.type = CA_MSG_ACKNOWLEDGE};
2350 OCHandleResponse(endPoint, &respInfo);
2356 // Normal handling of the packet
2357 OCHandleRequests(endPoint, requestInfo);
2359 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2363 //-----------------------------------------------------------------------------
2365 //-----------------------------------------------------------------------------
2367 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2370 !raInfo->username ||
2371 !raInfo->hostname ||
2372 !raInfo->xmpp_domain)
2375 return OC_STACK_INVALID_PARAM;
2377 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2378 gRASetInfo = (result == OC_STACK_OK)? true : false;
2384 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2388 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2391 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2393 OC_UNUSED(serverFlags);
2394 OC_UNUSED(clientFlags);
2396 OIC_LOG(DEBUG, TAG, "call OCInit1");
2397 return OCInit2(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS, OC_DEFAULT_ADAPTER);
2400 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2401 OCTransportAdapter transportType)
2403 if(stackState == OC_STACK_INITIALIZED)
2405 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2406 OCStop() between them are ignored.");
2410 #ifndef ROUTING_GATEWAY
2411 if (OC_GATEWAY == mode)
2413 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2414 return OC_STACK_INVALID_PARAM;
2421 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2422 return OC_STACK_ERROR;
2426 OCStackResult result = OC_STACK_ERROR;
2427 OIC_LOG(INFO, TAG, "Entering OCInit");
2430 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2431 || (mode == OC_GATEWAY)))
2433 OIC_LOG(ERROR, TAG, "Invalid mode");
2434 return OC_STACK_ERROR;
2438 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2440 caglobals.client = true;
2442 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2444 caglobals.server = true;
2447 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2448 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2450 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2452 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2453 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2455 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2458 defaultDeviceHandler = NULL;
2459 defaultDeviceHandlerCallbackParameter = NULL;
2461 result = InitializeScheduleResourceList();
2462 VERIFY_SUCCESS(result, OC_STACK_OK);
2464 result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2465 VERIFY_SUCCESS(result, OC_STACK_OK);
2467 result = CAResultToOCResult(OCSelectNetwork(transportType));
2468 VERIFY_SUCCESS(result, OC_STACK_OK);
2470 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2471 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2472 VERIFY_SUCCESS(result, OC_STACK_OK);
2474 switch (myStackMode)
2477 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2478 result = CAResultToOCResult(CAStartDiscoveryServer());
2479 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2482 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2483 result = CAResultToOCResult(CAStartListeningServer());
2484 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2486 case OC_CLIENT_SERVER:
2488 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2489 result = CAResultToOCResult(CAStartListeningServer());
2490 if(result == OC_STACK_OK)
2492 result = CAResultToOCResult(CAStartDiscoveryServer());
2496 VERIFY_SUCCESS(result, OC_STACK_OK);
2499 CARegisterKeepAliveHandler(OCHandleKeepAliveConnCB);
2502 #ifdef WITH_PRESENCE
2503 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2504 #endif // WITH_PRESENCE
2506 //Update Stack state to initialized
2507 stackState = OC_STACK_INITIALIZED;
2509 // Initialize resource
2510 if(myStackMode != OC_CLIENT)
2512 result = initResources();
2515 // Initialize the SRM Policy Engine
2516 if(result == OC_STACK_OK)
2518 result = SRMInitPolicyEngine();
2519 // TODO after BeachHead delivery: consolidate into single SRMInit()
2521 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2522 RMSetStackMode(mode);
2523 #ifdef ROUTING_GATEWAY
2524 if (OC_GATEWAY == myStackMode)
2526 result = RMInitialize();
2532 if (result == OC_STACK_OK)
2534 result = OCInitializeKeepAlive(myStackMode);
2538 InitializeObserverList();
2541 if(result != OC_STACK_OK)
2543 OIC_LOG(ERROR, TAG, "Stack initialization error");
2544 TerminateScheduleResourceList();
2545 deleteAllResources();
2547 stackState = OC_STACK_UNINITIALIZED;
2552 OCStackResult OCStop()
2554 OIC_LOG(INFO, TAG, "Entering OCStop");
2556 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2558 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2561 else if (stackState != OC_STACK_INITIALIZED)
2563 OIC_LOG(INFO, TAG, "Stack not initialized");
2564 return OC_STACK_ERROR;
2567 // unset cautil config
2568 CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2569 CAUtilSetBTConfigure(configs);
2571 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2573 CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2574 OCDefaultConnectionStateChangedHandler);
2576 #ifdef WITH_PRESENCE
2577 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2578 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2579 presenceResource.presenceTTL = 0;
2580 presenceState = OC_PRESENCE_UNINITIALIZED;
2581 #endif // WITH_PRESENCE
2583 #ifdef ROUTING_GATEWAY
2584 if (OC_GATEWAY == myStackMode)
2591 OCTerminateKeepAlive(myStackMode);
2594 TerminateScheduleResourceList();
2595 // Remove all observers
2596 DeleteObserverList();
2597 // Free memory dynamically allocated for resources
2598 deleteAllResources();
2599 // Remove all the client callbacks
2600 DeleteClientCBList();
2601 // Terminate connectivity-abstraction layer.
2604 // De-init the SRM Policy Engine
2605 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2606 SRMDeInitPolicyEngine();
2608 // Destroy Observer List Mutex
2609 TerminateObserverList();
2611 stackState = OC_STACK_UNINITIALIZED;
2615 OCStackResult OCStartMulticastServer()
2617 if(stackState != OC_STACK_INITIALIZED)
2619 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2620 return OC_STACK_ERROR;
2622 CAResult_t ret = CAStartListeningServer();
2623 if (CA_STATUS_OK != ret)
2625 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2626 return OC_STACK_ERROR;
2631 OCStackResult OCStopMulticastServer()
2633 CAResult_t ret = CAStopListeningServer();
2634 if (CA_STATUS_OK != ret)
2636 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2637 return OC_STACK_ERROR;
2642 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2647 return CA_MSG_CONFIRM;
2652 return CA_MSG_NONCONFIRM;
2656 OCStackResult ParseRequestUri(const char *fullUri,
2657 OCTransportAdapter adapter,
2658 OCTransportFlags flags,
2659 OCDevAddr **devAddr,
2661 char **resourceType)
2663 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2665 OCStackResult result = OC_STACK_OK;
2666 OCDevAddr *da = NULL;
2670 // provide defaults for all returned values
2677 *resourceUri = NULL;
2681 *resourceType = NULL;
2684 // delimit url prefix, if any
2685 const char *start = fullUri;
2686 char *slash2 = strstr(start, "//");
2691 char *slash = strchr(start, '/');
2694 return OC_STACK_INVALID_URI;
2697 // process url scheme
2698 size_t prefixLen = slash2 - fullUri;
2702 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2703 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2709 // TODO: this logic should come in with unit tests exercising the various strings
2710 // processs url prefix, if any
2711 size_t urlLen = slash - start;
2715 if (urlLen && devAddr)
2716 { // construct OCDevAddr
2717 if (start[0] == '[')
2719 char *close = strchr(++start, ']');
2720 if (!close || close > slash)
2722 return OC_STACK_INVALID_URI;
2725 if (close[1] == ':')
2732 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2736 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2738 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2742 char *dot = strchr(start, '.');
2743 if (dot && dot < slash)
2745 colon = strchr(start, ':');
2746 end = (colon && colon < slash) ? colon : slash;
2751 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2755 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2757 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2765 if (len >= sizeof(da->addr))
2767 return OC_STACK_INVALID_URI;
2769 // collect port, if any
2770 if (colon && colon < slash)
2772 for (colon++; colon < slash; colon++)
2775 if (c < '0' || c > '9')
2777 return OC_STACK_INVALID_URI;
2779 port = 10 * port + c - '0';
2784 if (len >= sizeof(da->addr))
2786 return OC_STACK_INVALID_URI;
2789 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2792 return OC_STACK_NO_MEMORY;
2795 // Decode address per RFC 6874.
2796 result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2797 if (result != OC_STACK_OK)
2804 da->adapter = adapter;
2806 if (!strncmp(fullUri, "coaps", 5))
2808 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2813 // process resource uri, if any
2815 { // request uri and query
2816 size_t ulen = strlen(slash); // resource uri length
2817 size_t tlen = 0; // resource type length
2820 static const char strPresence[] = "/oic/ad?rt=";
2821 static const size_t lenPresence = sizeof(strPresence) - 1;
2822 if (!strncmp(slash, strPresence, lenPresence))
2824 type = slash + lenPresence;
2825 tlen = ulen - lenPresence;
2830 *resourceUri = (char *)OICMalloc(ulen + 1);
2833 result = OC_STACK_NO_MEMORY;
2836 OICStrcpy(*resourceUri, (ulen + 1), slash);
2839 if (type && resourceType)
2841 *resourceType = (char *)OICMalloc(tlen + 1);
2844 result = OC_STACK_NO_MEMORY;
2848 OICStrcpy(*resourceType, (tlen+1), type);
2855 // free all returned values
2862 OICFree(*resourceUri);
2866 OICFree(*resourceType);
2871 #ifdef WITH_PRESENCE
2872 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2876 char uri[CA_MAX_URI_LENGTH];
2878 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2880 *requestUri = OICStrdup(uri);
2883 return OC_STACK_NO_MEMORY;
2888 #endif // WITH_PRESENCE
2891 * Discover or Perform requests on a specified resource
2893 OCStackResult OCDoResource(OCDoHandle *handle,
2895 const char *requestUri,
2896 const OCDevAddr *destination,
2898 OCConnectivityType connectivityType,
2899 OCQualityOfService qos,
2900 OCCallbackData *cbData,
2901 OCHeaderOption *options,
2904 OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
2905 connectivityType, qos, cbData, options, numOptions);
2907 // This is the owner of the payload object, so we free it
2908 OCPayloadDestroy(payload);
2913 * Discover or Perform requests on a specified resource
2915 OCStackResult OCDoRequest(OCDoHandle *handle,
2917 const char *requestUri,
2918 const OCDevAddr *destination,
2920 OCConnectivityType connectivityType,
2921 OCQualityOfService qos,
2922 OCCallbackData *cbData,
2923 OCHeaderOption *options,
2926 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2927 OIC_TRACE_BEGIN(%s:OCDoRequest, TAG);
2929 // Validate input parameters
2930 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2931 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2933 OCStackResult result = OC_STACK_ERROR;
2934 CAResult_t caResult;
2935 CAToken_t token = NULL;
2936 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2937 ClientCB *clientCB = NULL;
2938 OCDoHandle resHandle = NULL;
2939 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2940 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2942 OCTransportAdapter adapter;
2943 OCTransportFlags flags;
2944 // the request contents are put here
2945 CARequestInfo_t requestInfo = {.method = CA_GET};
2946 // requestUri will be parsed into the following three variables
2947 OCDevAddr *devAddr = NULL;
2948 char *resourceUri = NULL;
2949 char *resourceType = NULL;
2952 * Support original behavior with address on resourceUri argument.
2954 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2955 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2959 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2960 if (result != OC_STACK_OK)
2962 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2966 else if (!checkProxyUri(options, numOptions))
2968 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2975 case OC_REST_OBSERVE:
2976 case OC_REST_OBSERVE_ALL:
2977 requestInfo.method = CA_GET;
2980 requestInfo.method = CA_PUT;
2983 requestInfo.method = CA_POST;
2985 case OC_REST_DELETE:
2986 requestInfo.method = CA_DELETE;
2988 case OC_REST_DISCOVER:
2989 #ifdef WITH_PRESENCE
2990 case OC_REST_PRESENCE:
2992 if (destination || devAddr)
2994 requestInfo.isMulticast = false;
2998 tmpDevAddr.adapter = adapter;
2999 tmpDevAddr.flags = flags;
3000 destination = &tmpDevAddr;
3001 requestInfo.isMulticast = true;
3004 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
3005 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
3006 // replacing method type with GET.
3007 requestInfo.method = CA_GET;
3010 result = OC_STACK_INVALID_METHOD;
3014 if (!devAddr && !destination)
3016 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
3017 result = OC_STACK_INVALID_PARAM;
3021 /* If not original behavior, use destination argument */
3022 if (destination && !devAddr)
3024 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
3027 result = OC_STACK_NO_MEMORY;
3030 OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
3031 *devAddr = *destination;
3036 OIC_LOG_V(INFO_PRIVATE, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
3037 if (!requestInfo.isMulticast)
3039 OIC_LOG_V(DEBUG, TAG, "remoteAddr of devAddr : [%s]:[%d]",
3040 devAddr->addr, devAddr->port);
3044 resHandle = GenerateInvocationHandle();
3047 result = OC_STACK_NO_MEMORY;
3051 caResult = CAGenerateToken(&token, tokenLength);
3052 if (caResult != CA_STATUS_OK)
3054 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3055 result= OC_STACK_ERROR;
3059 // fill in request data
3060 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3061 requestInfo.info.token = token;
3062 requestInfo.info.tokenLength = tokenLength;
3064 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3066 result = CreateObserveHeaderOption (&(requestInfo.info.options),
3067 options, numOptions, OC_OBSERVE_REGISTER);
3068 if (result != OC_STACK_OK)
3072 requestInfo.info.numOptions = numOptions + 1;
3076 requestInfo.info.numOptions = numOptions;
3077 requestInfo.info.options =
3078 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3079 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3080 numOptions * sizeof(CAHeaderOption_t));
3083 CopyDevAddrToEndpoint(devAddr, &endpoint);
3088 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3091 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3094 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3098 requestInfo.info.payload = NULL;
3099 requestInfo.info.payloadSize = 0;
3100 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3103 // prepare for response
3104 #ifdef WITH_PRESENCE
3105 if (method == OC_REST_PRESENCE)
3107 char *presenceUri = NULL;
3108 result = OCPreparePresence(&endpoint, &presenceUri,
3109 requestInfo.isMulticast);
3110 if (OC_STACK_OK != result)
3115 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3116 // Presence notification will form a canonical uri to
3117 // look for callbacks into the application.
3120 OICFree(resourceUri);
3122 resourceUri = presenceUri;
3126 // update resourceUri onto requestInfo after check presence uri
3127 requestInfo.info.resourceUri = resourceUri;
3129 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3130 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3131 method, devAddr, resourceUri, resourceType, ttl);
3132 if (OC_STACK_OK != result)
3137 cbData = NULL; // Client CB list entry now owns it
3138 token = NULL; // Client CB list entry now owns it
3139 devAddr = NULL; // Client CB list entry now owns it
3140 resourceUri = NULL; // Client CB list entry now owns it
3141 resourceType = NULL; // Client CB list entry now owns it
3143 #ifdef WITH_PRESENCE
3144 if (method == OC_REST_PRESENCE)
3146 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3150 *handle = resHandle;
3152 #ifdef WITH_PROCESS_EVENT
3153 OCSendProcessEventSignal();
3154 #endif // WITH_PROCESS_EVENT
3161 result = OCSendRequest(&endpoint, &requestInfo);
3162 if (OC_STACK_OK != result)
3169 *handle = resHandle;
3173 if (result != OC_STACK_OK)
3175 OIC_LOG(ERROR, TAG, "OCDoResource error");
3176 if (NULL != cbData && NULL != cbData->cd)
3178 cbData->cd(cbData->context);
3180 FindAndDeleteClientCB(clientCB);
3181 CADestroyToken(token);
3189 OICFree(requestInfo.info.payload);
3191 OICFree(resourceUri);
3192 OICFree(resourceType);
3193 OICFree(requestInfo.info.options);
3198 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3202 * This ftn is implemented one of two ways in the case of observation:
3204 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3205 * Remove the callback associated on client side.
3206 * When the next notification comes in from server,
3207 * reply with RESET message to server.
3208 * Keep in mind that the server will react to RESET only
3209 * if the last notification was sent as CON
3211 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3212 * and it is associated with an observe request
3213 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3214 * Send CON Observe request to server with
3215 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3216 * Remove the callback associated on client side.
3218 OCStackResult ret = OC_STACK_OK;
3219 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3220 CARequestInfo_t requestInfo = {.method = CA_GET};
3224 return OC_STACK_INVALID_PARAM;
3227 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3230 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3231 return OC_STACK_ERROR;
3234 switch (clientCB->method)
3236 case OC_REST_OBSERVE:
3237 case OC_REST_OBSERVE_ALL:
3239 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3241 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3243 if (((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS) ||
3244 ((endpoint.adapter & CA_ADAPTER_TCP) && OC_LOW_QOS_WITH_TCP == qos))
3246 OIC_LOG_V(INFO, TAG, "the %s observe callback is removed", clientCB->requestUri);
3247 FindAndDeleteClientCB(clientCB);
3251 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3253 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3254 requestInfo.info.token = clientCB->token;
3255 requestInfo.info.tokenLength = clientCB->tokenLength;
3257 if (CreateObserveHeaderOption (&(requestInfo.info.options),
3258 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3260 return OC_STACK_ERROR;
3262 requestInfo.info.numOptions = numOptions + 1;
3263 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3266 ret = OCSendRequest(&endpoint, &requestInfo);
3268 if (requestInfo.info.options)
3270 OICFree (requestInfo.info.options);
3272 if (requestInfo.info.resourceUri)
3274 OICFree (requestInfo.info.resourceUri);
3279 case OC_REST_DISCOVER:
3280 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3281 clientCB->requestUri);
3282 FindAndDeleteClientCB(clientCB);
3285 #ifdef WITH_PRESENCE
3286 case OC_REST_PRESENCE:
3287 FindAndDeleteClientCB(clientCB);
3293 case OC_REST_DELETE:
3294 OIC_LOG_V(INFO, TAG, "Cancelling request callback for resource %s",
3295 clientCB->requestUri);
3296 FindAndDeleteClientCB(clientCB);
3300 ret = OC_STACK_INVALID_METHOD;
3308 * @brief Register Persistent storage callback.
3309 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3311 * OC_STACK_OK - No errors; Success
3312 * OC_STACK_INVALID_PARAM - Invalid parameter
3314 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3316 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3317 if(!persistentStorageHandler)
3319 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3320 return OC_STACK_INVALID_PARAM;
3324 if( !persistentStorageHandler->open ||
3325 !persistentStorageHandler->close ||
3326 !persistentStorageHandler->read ||
3327 !persistentStorageHandler->unlink ||
3328 !persistentStorageHandler->write)
3330 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3331 return OC_STACK_INVALID_PARAM;
3334 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3337 #ifdef WITH_PRESENCE
3339 #ifdef WITH_PROCESS_EVENT
3340 OCStackResult OCProcessPresence(uint32_t *nextEventTime)
3341 #else // WITH_PROCESS_EVENT
3342 OCStackResult OCProcessPresence(void)
3343 #endif // !WITH_PROCESS_EVENT
3345 OCStackResult result = OC_STACK_OK;
3347 // the following line floods the log with messages that are irrelevant
3348 // to most purposes. Uncomment as needed.
3349 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3350 ClientCB* cbNode = NULL;
3351 ClientCB* tempcbNode = NULL;
3352 OCClientResponse clientResponse;
3353 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3355 LL_FOREACH_SAFE(cbList, cbNode, tempcbNode)
3357 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3362 uint32_t now = GetTicks(0);
3363 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3364 cbNode->presence->TTLlevel);
3365 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3367 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3372 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3374 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3375 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3377 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3379 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3381 clientResponse.sequenceNumber = 0;
3382 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3383 clientResponse.devAddr = *cbNode->devAddr;
3384 FixUpClientResponse(&clientResponse);
3385 clientResponse.payload = NULL;
3387 // Increment the TTLLevel (going to a next state), so we don't keep
3388 // sending presence notification to client.
3389 cbNode->presence->TTLlevel++;
3390 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3391 cbNode->presence->TTLlevel);
3393 OIC_LOG(INFO, TAG, "Before calling into application address space for presence timeout");
3394 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3395 OIC_LOG(INFO, TAG, "After calling into application address space for presence timeout");
3397 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3399 FindAndDeleteClientCB(cbNode);
3404 uint32_t timeout = cbNode->presence->timeOut[cbNode->presence->TTLlevel];
3407 #ifdef WITH_PROCESS_EVENT
3408 if (nextEventTime && (timeout - now) < *nextEventTime)
3410 *nextEventTime = timeout - now;
3412 #endif // WITH_PROCESS_EVENT
3416 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3417 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3418 CARequestInfo_t requestInfo = {.method = CA_GET};
3420 OIC_LOG(DEBUG, TAG, "time to test server presence");
3422 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3424 requestData.type = CA_MSG_NONCONFIRM;
3425 requestData.token = cbNode->token;
3426 requestData.tokenLength = cbNode->tokenLength;
3427 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3428 requestInfo.method = CA_GET;
3429 requestInfo.info = requestData;
3431 result = OCSendRequest(&endpoint, &requestInfo);
3432 if (OC_STACK_OK != result)
3437 cbNode->presence->TTLlevel++;
3438 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3441 if (result != OC_STACK_OK)
3443 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3448 #endif // WITH_PRESENCE
3450 #ifdef WITH_PROCESS_EVENT
3451 OCStackResult OCProcess(void)
3453 uint32_t nextEventTime;
3454 return OCProcessEvent(&nextEventTime);
3457 OCStackResult OCProcessEvent(uint32_t *nextEventTime)
3459 if (stackState == OC_STACK_UNINITIALIZED)
3461 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3462 return OC_STACK_ERROR;
3465 *nextEventTime = UINT32_MAX;
3467 #ifdef WITH_PRESENCE
3468 OCProcessPresence(nextEventTime);
3469 OIC_LOG_V(INFO, TAG, "OCProcessPresence next event time : %u", *nextEventTime);
3471 CAHandleRequestResponse();
3474 #ifdef ROUTING_GATEWAY
3475 RMProcess(nextEventTime);
3479 OCProcessKeepAlive(nextEventTime);
3480 OIC_LOG_V(INFO, TAG, "OCProcessKeepAlive next event time : %u", *nextEventTime);
3485 void OCRegisterProcessEvent(oc_event event)
3487 g_ocProcessEvent = event;
3488 CARegisterProcessEvent(event);
3491 void OCSendProcessEventSignal(void)
3493 if (g_ocProcessEvent)
3495 oc_event_signal(g_ocProcessEvent);
3498 #else // WITH_PROCESS_EVENT
3500 OCStackResult OCProcess()
3502 if (stackState == OC_STACK_UNINITIALIZED)
3504 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3505 return OC_STACK_ERROR;
3507 #ifdef WITH_PRESENCE
3508 OCProcessPresence();
3510 CAHandleRequestResponse();
3512 #ifdef ROUTING_GATEWAY
3517 OCProcessKeepAlive();
3521 #endif // !WITH_PROCESS_EVENT
3523 #ifdef WITH_PRESENCE
3524 OCStackResult OCStartPresence(const uint32_t ttl)
3526 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3527 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3528 OCChangeResourceProperty(
3529 &(((OCResource *)presenceResource.handle)->resourceProperties),
3532 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3534 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3535 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3539 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3540 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3544 presenceResource.presenceTTL = ttl;
3547 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3550 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3552 presenceState = OC_PRESENCE_INITIALIZED;
3554 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3556 CAToken_t caToken = NULL;
3557 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3558 if (caResult != CA_STATUS_OK)
3560 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3561 CADestroyToken(caToken);
3562 return OC_STACK_ERROR;
3565 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3566 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3567 CADestroyToken(caToken);
3570 // Each time OCStartPresence is called
3571 // a different random 32-bit integer number is used
3572 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3574 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3575 OC_PRESENCE_TRIGGER_CREATE);
3578 OCStackResult OCStopPresence()
3580 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3581 OCStackResult result = OC_STACK_ERROR;
3583 if(presenceResource.handle)
3585 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3587 // make resource inactive
3588 result = OCChangeResourceProperty(
3589 &(((OCResource *) presenceResource.handle)->resourceProperties),
3593 if(result != OC_STACK_OK)
3596 "Changing the presence resource properties to ACTIVE not successful");
3600 return SendStopNotification();
3604 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3605 void* callbackParameter)
3607 defaultDeviceHandler = entityHandler;
3608 defaultDeviceHandlerCallbackParameter = callbackParameter;
3613 OCStackResult OCCreateResource(OCResourceHandle *handle,
3614 const char *resourceTypeName,
3615 const char *resourceInterfaceName,
3616 const char *uri, OCEntityHandler entityHandler,
3617 void* callbackParam,
3618 uint8_t resourceProperties)
3621 OCResource *pointer = NULL;
3622 OCStackResult result = OC_STACK_ERROR;
3624 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3626 if(myStackMode == OC_CLIENT)
3628 return OC_STACK_INVALID_PARAM;
3630 // Validate parameters
3631 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3633 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3634 return OC_STACK_INVALID_URI;
3636 // Is it presented during resource discovery?
3637 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3639 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3640 return OC_STACK_INVALID_PARAM;
3643 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3645 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3649 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3651 // Make sure resourceProperties bitmask has allowed properties specified
3652 if (resourceProperties
3653 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3654 OC_EXPLICIT_DISCOVERABLE
3663 OIC_LOG(ERROR, TAG, "Invalid property");
3664 return OC_STACK_INVALID_PARAM;
3667 // If the headResource is NULL, then no resources have been created...
3668 pointer = headResource;
3671 // At least one resources is in the resource list, so we need to search for
3672 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3675 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3677 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3678 return OC_STACK_INVALID_PARAM;
3680 pointer = pointer->next;
3683 // Create the pointer and insert it into the resource list
3684 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3687 result = OC_STACK_NO_MEMORY;
3690 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3692 insertResource(pointer);
3695 pointer->uri = OICStrdup(uri);
3698 result = OC_STACK_NO_MEMORY;
3702 // Set properties. Set OC_ACTIVE
3703 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3706 // Add the resourcetype to the resource
3707 result = BindResourceTypeToResource(pointer, resourceTypeName);
3708 if (result != OC_STACK_OK)
3710 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3714 // Add the resourceinterface to the resource
3715 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3716 if (result != OC_STACK_OK)
3718 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3722 // If an entity handler has been passed, attach it to the newly created
3723 // resource. Otherwise, set the default entity handler.
3726 pointer->entityHandler = entityHandler;
3727 pointer->entityHandlerCallbackParam = callbackParam;
3731 pointer->entityHandler = defaultResourceEHandler;
3732 pointer->entityHandlerCallbackParam = NULL;
3735 // Initialize a pointer indicating child resources in case of collection
3736 pointer->rsrcChildResourcesHead = NULL;
3739 result = OC_STACK_OK;
3741 #ifdef WITH_PRESENCE
3742 if (presenceResource.handle)
3744 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3745 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3749 if (result != OC_STACK_OK)
3751 // Deep delete of resource and other dynamic elements that it contains
3752 deleteResource(pointer);
3757 OCStackResult OCBindResource(
3758 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3760 OCResource *resource = NULL;
3761 OCChildResource *tempChildResource = NULL;
3762 OCChildResource *newChildResource = NULL;
3764 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3766 // Validate parameters
3767 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3768 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3769 // Container cannot contain itself
3770 if (collectionHandle == resourceHandle)
3772 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3773 return OC_STACK_INVALID_PARAM;
3776 // Use the handle to find the resource in the resource linked list
3777 resource = findResource((OCResource *) collectionHandle);
3780 OIC_LOG(ERROR, TAG, "Collection handle not found");
3781 return OC_STACK_INVALID_PARAM;
3784 // Look for an open slot to add add the child resource.
3785 // If found, add it and return success
3787 tempChildResource = resource->rsrcChildResourcesHead;
3789 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3791 // TODO: what if one of child resource was deregistered without unbinding?
3792 tempChildResource = tempChildResource->next;
3795 // Do memory allocation for child resource
3796 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3797 if(!newChildResource)
3799 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3800 return OC_STACK_ERROR;
3803 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3804 newChildResource->next = NULL;
3806 if(!resource->rsrcChildResourcesHead)
3808 resource->rsrcChildResourcesHead = newChildResource;
3811 tempChildResource->next = newChildResource;
3814 OIC_LOG(INFO, TAG, "resource bound");
3816 #ifdef WITH_PRESENCE
3817 if (presenceResource.handle)
3819 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3820 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3821 OC_PRESENCE_TRIGGER_CHANGE);
3828 OCStackResult OCUnBindResource(
3829 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3831 OCResource *resource = NULL;
3832 OCChildResource *tempChildResource = NULL;
3833 OCChildResource *tempLastChildResource = NULL;
3835 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3837 // Validate parameters
3838 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3839 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3840 // Container cannot contain itself
3841 if (collectionHandle == resourceHandle)
3843 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3844 return OC_STACK_INVALID_PARAM;
3847 // Use the handle to find the resource in the resource linked list
3848 resource = findResource((OCResource *) collectionHandle);
3851 OIC_LOG(ERROR, TAG, "Collection handle not found");
3852 return OC_STACK_INVALID_PARAM;
3855 // Look for an open slot to add add the child resource.
3856 // If found, add it and return success
3857 if(!resource->rsrcChildResourcesHead)
3859 OIC_LOG(INFO, TAG, "resource not found in collection");
3861 // Unable to add resourceHandle, so return error
3862 return OC_STACK_ERROR;
3866 tempChildResource = resource->rsrcChildResourcesHead;
3868 while (tempChildResource)
3870 if(tempChildResource->rsrcResource == resourceHandle)
3872 // if resource going to be unbinded is the head one.
3873 if( tempChildResource == resource->rsrcChildResourcesHead )
3875 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3876 OICFree(resource->rsrcChildResourcesHead);
3877 resource->rsrcChildResourcesHead = temp;
3882 OCChildResource *temp = tempChildResource->next;
3883 OICFree(tempChildResource);
3884 if (tempLastChildResource)
3886 tempLastChildResource->next = temp;
3891 OIC_LOG(INFO, TAG, "resource unbound");
3893 // Send notification when resource is unbounded successfully.
3894 #ifdef WITH_PRESENCE
3895 if (presenceResource.handle)
3897 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3898 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3899 OC_PRESENCE_TRIGGER_CHANGE);
3902 tempChildResource = NULL;
3903 tempLastChildResource = NULL;
3909 tempLastChildResource = tempChildResource;
3910 tempChildResource = tempChildResource->next;
3913 OIC_LOG(INFO, TAG, "resource not found in collection");
3915 tempChildResource = NULL;
3916 tempLastChildResource = NULL;
3918 // Unable to add resourceHandle, so return error
3919 return OC_STACK_ERROR;
3922 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3924 if (!resourceItemName)
3928 // Per RFC 6690 only registered values must follow the first rule below.
3929 // At this point in time the only values registered begin with "core", and
3930 // all other values are specified as opaque strings where multiple values
3931 // are separated by a space.
3932 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3934 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3936 if (resourceItemName[index] != '.'
3937 && resourceItemName[index] != '-'
3938 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3939 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3947 for (size_t index = 0; resourceItemName[index]; ++index)
3949 if (resourceItemName[index] == ' '
3950 || resourceItemName[index] == '\t'
3951 || resourceItemName[index] == '\r'
3952 || resourceItemName[index] == '\n')
3962 OCStackResult BindResourceTypeToResource(OCResource* resource,
3963 const char *resourceTypeName)
3965 OCResourceType *pointer = NULL;
3967 OCStackResult result = OC_STACK_ERROR;
3969 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3971 if (!ValidateResourceTypeInterface(resourceTypeName))
3973 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3974 return OC_STACK_INVALID_PARAM;
3977 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3980 result = OC_STACK_NO_MEMORY;
3984 str = OICStrdup(resourceTypeName);
3987 result = OC_STACK_NO_MEMORY;
3990 pointer->resourcetypename = str;
3991 pointer->next = NULL;
3993 insertResourceType(resource, pointer);
3994 result = OC_STACK_OK;
3997 if (result != OC_STACK_OK)
4006 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
4007 const char *resourceInterfaceName)
4009 OCResourceInterface *pointer = NULL;
4011 OCStackResult result = OC_STACK_ERROR;
4013 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
4015 if (!ValidateResourceTypeInterface(resourceInterfaceName))
4017 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
4018 return OC_STACK_INVALID_PARAM;
4021 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
4023 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
4026 result = OC_STACK_NO_MEMORY;
4030 str = OICStrdup(resourceInterfaceName);
4033 result = OC_STACK_NO_MEMORY;
4036 pointer->name = str;
4038 // Bind the resourceinterface to the resource
4039 insertResourceInterface(resource, pointer);
4041 result = OC_STACK_OK;
4044 if (result != OC_STACK_OK)
4053 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
4054 const char *resourceTypeName)
4057 OCStackResult result = OC_STACK_ERROR;
4058 OCResource *resource = NULL;
4060 resource = findResource((OCResource *) handle);
4063 OIC_LOG(ERROR, TAG, "Resource not found");
4064 return OC_STACK_ERROR;
4067 result = BindResourceTypeToResource(resource, resourceTypeName);
4069 #ifdef WITH_PRESENCE
4070 if(presenceResource.handle)
4072 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4073 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4080 OCStackResult OCResetResourceTypes(OCResourceHandle handle,
4081 const char *newResourceType)
4083 OCStackResult result = OC_STACK_ERROR;
4084 OCResource *resource = NULL;
4086 resource = findResource((OCResource *) handle);
4089 OIC_LOG(ERROR, TAG, "Resource not found");
4090 return OC_STACK_ERROR;
4093 // Clear all bound resource types
4094 deleteResourceType(resource->rsrcType);
4095 resource->rsrcType = NULL;
4097 // Bind new resource type to resource
4098 result = BindResourceTypeToResource(resource, newResourceType);
4100 #ifdef WITH_PRESENCE
4101 if(presenceResource.handle)
4103 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4104 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4111 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
4112 const char *resourceInterfaceName)
4115 OCStackResult result = OC_STACK_ERROR;
4116 OCResource *resource = NULL;
4118 resource = findResource((OCResource *) handle);
4121 OIC_LOG(ERROR, TAG, "Resource not found");
4122 return OC_STACK_ERROR;
4125 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
4127 #ifdef WITH_PRESENCE
4128 if (presenceResource.handle)
4130 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4131 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4138 OCStackResult OCResetResourceInterfaces(OCResourceHandle handle,
4139 const char *newResourceInterface)
4141 OCStackResult result = OC_STACK_ERROR;
4142 OCResource *resource = NULL;
4144 resource = findResource((OCResource *) handle);
4147 OIC_LOG(ERROR, TAG, "Resource not found");
4148 return OC_STACK_ERROR;
4151 // Clear all bound interface
4152 deleteResourceInterface(resource->rsrcInterface);
4153 resource->rsrcInterface = NULL;
4155 // Bind new interface to resource
4156 result = BindResourceInterfaceToResource(resource, newResourceInterface);
4158 #ifdef WITH_PRESENCE
4159 if (presenceResource.handle)
4161 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4162 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4169 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
4171 OCResource *pointer = headResource;
4173 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
4177 *numResources = *numResources + 1;
4178 pointer = pointer->next;
4183 OCResourceHandle OCGetResourceHandle(uint8_t index)
4185 OCResource *pointer = headResource;
4187 for( uint8_t i = 0; i < index && pointer; ++i)
4189 pointer = pointer->next;
4191 return (OCResourceHandle) pointer;
4194 OCStackResult OCDeleteResource(OCResourceHandle handle)
4198 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4199 return OC_STACK_INVALID_PARAM;
4202 OCResource *resource = findResource((OCResource *) handle);
4203 if (resource == NULL)
4205 OIC_LOG(ERROR, TAG, "Resource not found");
4206 return OC_STACK_NO_RESOURCE;
4209 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4211 OIC_LOG(ERROR, TAG, "Error deleting resource");
4212 return OC_STACK_ERROR;
4218 const char *OCGetResourceUri(OCResourceHandle handle)
4220 OCResource *resource = NULL;
4222 resource = findResource((OCResource *) handle);
4225 return resource->uri;
4227 return (const char *) NULL;
4230 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4232 OCResource *resource = NULL;
4234 resource = findResource((OCResource *) handle);
4237 return resource->resourceProperties;
4239 return (OCResourceProperty)-1;
4242 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4243 uint8_t *numResourceTypes)
4245 OCResource *resource = NULL;
4246 OCResourceType *pointer = NULL;
4248 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4249 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4251 *numResourceTypes = 0;
4253 resource = findResource((OCResource *) handle);
4256 pointer = resource->rsrcType;
4259 *numResourceTypes = *numResourceTypes + 1;
4260 pointer = pointer->next;
4266 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4268 OCResourceType *resourceType = NULL;
4270 resourceType = findResourceTypeAtIndex(handle, index);
4273 return resourceType->resourcetypename;
4275 return (const char *) NULL;
4278 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4279 uint8_t *numResourceInterfaces)
4281 OCResourceInterface *pointer = NULL;
4282 OCResource *resource = NULL;
4284 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4285 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4287 *numResourceInterfaces = 0;
4288 resource = findResource((OCResource *) handle);
4291 pointer = resource->rsrcInterface;
4294 *numResourceInterfaces = *numResourceInterfaces + 1;
4295 pointer = pointer->next;
4301 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4303 OCResourceInterface *resourceInterface = NULL;
4305 resourceInterface = findResourceInterfaceAtIndex(handle, index);
4306 if (resourceInterface)
4308 return resourceInterface->name;
4310 return (const char *) NULL;
4313 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4316 OCResource *resource = NULL;
4317 OCChildResource *tempChildResource = NULL;
4320 resource = findResource((OCResource *) collectionHandle);
4326 tempChildResource = resource->rsrcChildResourcesHead;
4328 while(tempChildResource)
4332 return tempChildResource->rsrcResource;
4335 tempChildResource = tempChildResource->next;
4338 // In this case, the number of resource handles in the collection exceeds the index
4339 tempChildResource = NULL;
4343 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4344 OCEntityHandler entityHandler,
4345 void* callbackParam)
4347 OCResource *resource = NULL;
4349 // Validate parameters
4350 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4352 // Use the handle to find the resource in the resource linked list
4353 resource = findResource((OCResource *)handle);
4356 OIC_LOG(ERROR, TAG, "Resource not found");
4357 return OC_STACK_ERROR;
4361 resource->entityHandler = entityHandler;
4362 resource->entityHandlerCallbackParam = callbackParam;
4364 #ifdef WITH_PRESENCE
4365 if (presenceResource.handle)
4367 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4368 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4375 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4377 OCResource *resource = NULL;
4379 resource = findResource((OCResource *)handle);
4382 OIC_LOG(ERROR, TAG, "Resource not found");
4387 return resource->entityHandler;
4390 void incrementSequenceNumber(OCResource * resPtr)
4392 // Increment the sequence number
4393 resPtr->sequenceNum += 1;
4394 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4396 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4401 #ifdef WITH_PRESENCE
4402 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4403 OCPresenceTrigger trigger)
4405 OIC_LOG(INFO, TAG, "SendPresenceNotification");
4406 OCResource *resPtr = NULL;
4407 OCStackResult result = OC_STACK_ERROR;
4408 OCMethod method = OC_REST_PRESENCE;
4409 uint32_t maxAge = 0;
4410 resPtr = findResource((OCResource *) presenceResource.handle);
4413 return OC_STACK_NO_RESOURCE;
4416 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4418 maxAge = presenceResource.presenceTTL;
4420 result = SendAllObserverNotification(method, resPtr, maxAge,
4421 trigger, resourceType, OC_LOW_QOS);
4427 OCStackResult SendStopNotification()
4429 OIC_LOG(INFO, TAG, "SendStopNotification");
4430 OCResource *resPtr = NULL;
4431 OCStackResult result = OC_STACK_ERROR;
4432 OCMethod method = OC_REST_PRESENCE;
4433 resPtr = findResource((OCResource *) presenceResource.handle);
4436 return OC_STACK_NO_RESOURCE;
4439 // maxAge is 0. ResourceType is NULL.
4440 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4446 #endif // WITH_PRESENCE
4447 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4449 OCResource *resPtr = NULL;
4450 OCStackResult result = OC_STACK_ERROR;
4451 OCMethod method = OC_REST_NOMETHOD;
4452 uint32_t maxAge = 0;
4454 OIC_LOG(INFO, TAG, "Notifying all observers");
4455 #ifdef WITH_PRESENCE
4456 if(handle == presenceResource.handle)
4460 #endif // WITH_PRESENCE
4461 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4463 // Verify that the resource exists
4464 resPtr = findResource ((OCResource *) handle);
4467 return OC_STACK_NO_RESOURCE;
4471 //only increment in the case of regular observing (not presence)
4472 incrementSequenceNumber(resPtr);
4473 method = OC_REST_OBSERVE;
4474 maxAge = MAX_OBSERVE_AGE;
4475 #ifdef WITH_PRESENCE
4476 result = SendAllObserverNotification (method, resPtr, maxAge,
4477 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4479 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4486 OCNotifyListOfObservers (OCResourceHandle handle,
4487 OCObservationId *obsIdList,
4488 uint8_t numberOfIds,
4489 const OCRepPayload *payload,
4490 OCQualityOfService qos)
4492 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4494 OCResource *resPtr = NULL;
4495 //TODO: we should allow the server to define this
4496 uint32_t maxAge = MAX_OBSERVE_AGE;
4498 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4499 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4500 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4502 resPtr = findResource ((OCResource *) handle);
4503 if (NULL == resPtr || myStackMode == OC_CLIENT)
4505 return OC_STACK_NO_RESOURCE;
4509 incrementSequenceNumber(resPtr);
4511 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4512 payload, maxAge, qos));
4515 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4517 OIC_TRACE_BEGIN(%s:OCDoResponse, TAG);
4518 OCStackResult result = OC_STACK_ERROR;
4519 OCServerRequest *serverRequest = NULL;
4521 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4523 // Validate input parameters
4524 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4525 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4528 // Get pointer to request info
4529 serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
4532 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4533 result = serverRequest->ehResponseHandler(ehResponse);
4540 //#ifdef DIRECT_PAIRING
4541 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4543 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4544 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4546 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4550 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4553 const OCDPDev_t* OCGetDirectPairedDevices()
4555 return (const OCDPDev_t*)DPGetPairedDevices();
4558 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4559 OCDirectPairingCB resultCallback)
4561 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4562 if(NULL == peer || NULL == pinNumber)
4564 OIC_LOG(ERROR, TAG, "Invalid parameters");
4565 return OC_STACK_INVALID_PARAM;
4567 if (NULL == resultCallback)
4569 OIC_LOG(ERROR, TAG, "Invalid callback");
4570 return OC_STACK_INVALID_CALLBACK;
4573 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4574 pinNumber, (OCDirectPairingResultCB)resultCallback);
4576 //#endif // DIRECT_PAIRING
4578 //-----------------------------------------------------------------------------
4579 // Private internal function definitions
4580 //-----------------------------------------------------------------------------
4581 static OCDoHandle GenerateInvocationHandle()
4583 OCDoHandle handle = NULL;
4584 // Generate token here, it will be deleted when the transaction is deleted
4585 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4588 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4594 #ifdef WITH_PRESENCE
4595 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4596 OCResourceProperty resourceProperties, uint8_t enable)
4600 return OC_STACK_INVALID_PARAM;
4602 if (resourceProperties
4603 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4605 OIC_LOG(ERROR, TAG, "Invalid property");
4606 return OC_STACK_INVALID_PARAM;
4610 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4614 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4620 OCStackResult initResources()
4622 OCStackResult result = OC_STACK_OK;
4624 headResource = NULL;
4625 tailResource = NULL;
4626 // Init Virtual Resources
4627 #ifdef WITH_PRESENCE
4628 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4630 result = OCCreateResource(&presenceResource.handle,
4631 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4633 OC_RSRVD_PRESENCE_URI,
4637 //make resource inactive
4638 result = OCChangeResourceProperty(
4639 &(((OCResource *) presenceResource.handle)->resourceProperties),
4642 #ifndef WITH_ARDUINO
4643 if (result == OC_STACK_OK)
4645 result = SRMInitSecureResources();
4649 if(result == OC_STACK_OK)
4651 CreateResetProfile();
4652 result = OCCreateResource(&deviceResource,
4653 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4654 OC_RSRVD_INTERFACE_DEFAULT,
4655 OC_RSRVD_DEVICE_URI,
4659 if(result == OC_STACK_OK)
4661 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4662 OC_RSRVD_INTERFACE_READ);
4666 if(result == OC_STACK_OK)
4668 result = OCCreateResource(&platformResource,
4669 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4670 OC_RSRVD_INTERFACE_DEFAULT,
4671 OC_RSRVD_PLATFORM_URI,
4675 if(result == OC_STACK_OK)
4677 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4678 OC_RSRVD_INTERFACE_READ);
4685 void insertResource(OCResource *resource)
4689 headResource = resource;
4690 tailResource = resource;
4694 tailResource->next = resource;
4695 tailResource = resource;
4697 resource->next = NULL;
4700 OCResource *findResource(OCResource *resource)
4702 OCResource *pointer = headResource;
4706 if (pointer == resource)
4710 pointer = pointer->next;
4715 void deleteAllResources()
4717 OCResource *pointer = headResource;
4718 OCResource *temp = NULL;
4722 temp = pointer->next;
4723 #ifdef WITH_PRESENCE
4724 if (pointer != (OCResource *) presenceResource.handle)
4726 #endif // WITH_PRESENCE
4727 deleteResource(pointer);
4728 #ifdef WITH_PRESENCE
4730 #endif // WITH_PRESENCE
4733 memset(&platformResource, 0, sizeof(platformResource));
4734 memset(&deviceResource, 0, sizeof(deviceResource));
4736 memset(&brokerResource, 0, sizeof(brokerResource));
4739 SRMDeInitSecureResources();
4741 #ifdef WITH_PRESENCE
4742 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4743 // presence notification attributed to their deletion to be processed.
4744 deleteResource((OCResource *) presenceResource.handle);
4745 memset(&presenceResource, 0, sizeof(presenceResource));
4746 #endif // WITH_PRESENCE
4749 OCStackResult deleteResource(OCResource *resource)
4751 OCResource *prev = NULL;
4752 OCResource *temp = NULL;
4755 OIC_LOG(DEBUG,TAG,"resource is NULL");
4756 return OC_STACK_INVALID_PARAM;
4759 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4761 temp = headResource;
4764 if (temp == resource)
4766 // Invalidate all Resource Properties.
4767 resource->resourceProperties = (OCResourceProperty) 0;
4768 #ifdef WITH_PRESENCE
4769 if(resource != (OCResource *) presenceResource.handle)
4771 #endif // WITH_PRESENCE
4772 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4773 #ifdef WITH_PRESENCE
4776 if(presenceResource.handle)
4778 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4779 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4782 // Delete resource's all observers
4783 DeleteObserverUsingResource(resource);
4785 // Only resource in list.
4786 if (temp == headResource && temp == tailResource)
4788 headResource = NULL;
4789 tailResource = NULL;
4792 else if (temp == headResource)
4794 headResource = temp->next;
4797 else if (temp == tailResource && prev)
4799 tailResource = prev;
4800 tailResource->next = NULL;
4804 prev->next = temp->next;
4807 deleteResourceElements(temp);
4818 return OC_STACK_ERROR;
4821 void deleteResourceElements(OCResource *resource)
4830 OICFree(resource->uri);
4831 resource->uri = NULL;
4833 if (resource->rsrcType)
4835 deleteResourceType(resource->rsrcType);
4836 resource->rsrcType = NULL;
4838 if (resource->rsrcInterface)
4840 deleteResourceInterface(resource->rsrcInterface);
4841 resource->rsrcInterface = NULL;
4843 if (resource->rsrcChildResourcesHead)
4845 unbindChildResources(resource->rsrcChildResourcesHead);
4846 resource->rsrcChildResourcesHead = NULL;
4848 if (resource->rsrcAttributes)
4850 OCDeleteResourceAttributes(resource->rsrcAttributes);
4851 resource->rsrcAttributes = NULL;
4854 resource->entityHandler = NULL;
4858 void deleteResourceType(OCResourceType *resourceType)
4860 OCResourceType *next = NULL;
4862 for (OCResourceType *pointer = resourceType; pointer; pointer = next)
4864 next = pointer->next ? pointer->next : NULL;
4865 if (pointer->resourcetypename)
4867 OICFree(pointer->resourcetypename);
4868 pointer->resourcetypename = NULL;
4874 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4876 OCResourceInterface *next = NULL;
4877 for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
4879 next = pointer->next ? pointer->next : NULL;
4882 OICFree(pointer->name);
4883 pointer->name = NULL;
4889 void unbindChildResources(OCChildResource *head)
4891 OCChildResource *next = NULL;
4892 for (OCChildResource *current = head; current; current = next)
4894 next = current->next;
4899 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
4901 OCAttribute *next = NULL;
4902 for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
4904 next = pointer->next ? pointer->next : NULL;
4905 if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
4907 OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
4908 pointer->attrValue = NULL;
4910 else if (pointer->attrValue)
4912 OICFree(pointer->attrValue);
4913 pointer->attrValue = NULL;
4915 if (pointer->attrName)
4917 OICFree(pointer->attrName);
4918 pointer->attrName = NULL;
4924 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4926 OCResourceType *pointer = NULL;
4927 OCResourceType *previous = NULL;
4928 if (!resource || !resourceType)
4932 // resource type list is empty.
4933 else if (!resource->rsrcType)
4935 resource->rsrcType = resourceType;
4939 pointer = resource->rsrcType;
4943 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4945 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4946 OICFree(resourceType->resourcetypename);
4947 OICFree(resourceType);
4951 pointer = pointer->next;
4956 previous->next = resourceType;
4959 resourceType->next = NULL;
4961 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4964 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4966 OCResource *resource = NULL;
4967 OCResourceType *pointer = NULL;
4969 // Find the specified resource
4970 resource = findResource((OCResource *) handle);
4976 // Make sure a resource has a resourcetype
4977 if (!resource->rsrcType)
4982 // Iterate through the list
4983 pointer = resource->rsrcType;
4984 for(uint8_t i = 0; i< index && pointer; ++i)
4986 pointer = pointer->next;
4991 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4993 if(resourceTypeList && resourceTypeName)
4995 OCResourceType * rtPointer = resourceTypeList;
4996 while(resourceTypeName && rtPointer)
4998 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4999 if(rtPointer->resourcetypename &&
5000 strcmp(resourceTypeName, (const char *)
5001 (rtPointer->resourcetypename)) == 0)
5005 rtPointer = rtPointer->next;
5013 * Insert a new interface into interface linked list only if not already present.
5014 * If alredy present, 2nd arg is free'd.
5015 * Default interface will always be first if present.
5017 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
5019 OCResourceInterface *pointer = NULL;
5020 OCResourceInterface *previous = NULL;
5022 newInterface->next = NULL;
5024 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
5026 if (!*firstInterface)
5028 // If first interface is not oic.if.baseline, by default add it as first interface type.
5029 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
5031 *firstInterface = newInterface;
5035 OCStackResult result = BindResourceInterfaceToResource(resource,
5036 OC_RSRVD_INTERFACE_DEFAULT);
5037 if (result != OC_STACK_OK)
5039 OICFree(newInterface->name);
5040 OICFree(newInterface);
5043 if (*firstInterface)
5045 (*firstInterface)->next = newInterface;
5049 // If once add oic.if.baseline, later too below code take care of freeing memory.
5050 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5052 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5054 OICFree(newInterface->name);
5055 OICFree(newInterface);
5058 // This code will not hit anymore, keeping
5061 newInterface->next = *firstInterface;
5062 *firstInterface = newInterface;
5067 pointer = *firstInterface;
5070 if (strcmp(newInterface->name, pointer->name) == 0)
5072 OICFree(newInterface->name);
5073 OICFree(newInterface);
5077 pointer = pointer->next;
5082 previous->next = newInterface;
5087 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
5090 OCResource *resource = NULL;
5091 OCResourceInterface *pointer = NULL;
5093 // Find the specified resource
5094 resource = findResource((OCResource *) handle);
5100 // Make sure a resource has a resourceinterface
5101 if (!resource->rsrcInterface)
5106 // Iterate through the list
5107 pointer = resource->rsrcInterface;
5109 for (uint8_t i = 0; i < index && pointer; ++i)
5111 pointer = pointer->next;
5117 * This function splits the uri using the '?' delimiter.
5118 * "uriWithoutQuery" is the block of characters between the beginning
5119 * till the delimiter or '\0' which ever comes first.
5120 * "query" is whatever is to the right of the delimiter if present.
5121 * No delimiter sets the query to NULL.
5122 * If either are present, they will be malloc'ed into the params 2, 3.
5123 * The first param, *uri is left untouched.
5125 * NOTE: This function does not account for whitespace at the end of the uri NOR
5126 * malformed uri's with '??'. Whitespace at the end will be assumed to be
5127 * part of the query.
5129 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
5133 return OC_STACK_INVALID_URI;
5135 if(!query || !uriWithoutQuery)
5137 return OC_STACK_INVALID_PARAM;
5141 *uriWithoutQuery = NULL;
5143 size_t uriWithoutQueryLen = 0;
5144 size_t queryLen = 0;
5145 size_t uriLen = strlen(uri);
5147 char *pointerToDelimiter = strstr(uri, "?");
5149 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
5150 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
5152 if (uriWithoutQueryLen)
5154 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
5155 if (!*uriWithoutQuery)
5159 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
5163 *query = (char *) OICCalloc(queryLen + 1, 1);
5166 OICFree(*uriWithoutQuery);
5167 *uriWithoutQuery = NULL;
5170 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5176 return OC_STACK_NO_MEMORY;
5179 const char* OCGetServerInstanceIDString(void)
5181 static char sidStr[UUID_STRING_SIZE];
5183 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5185 OIC_LOG(FATAL, TAG, "GetDoxmDeviceID failed!");
5189 if (OCConvertUuidToString(sid.id, sidStr) != RAND_UUID_OK)
5191 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5198 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5200 OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5201 CAResult_t retResult = CA_STATUS_FAILED;
5202 CAResult_t caResult = CA_STATUS_OK;
5204 CATransportAdapter_t connTypes[] = {
5206 CA_ADAPTER_RFCOMM_BTEDR,
5207 CA_ADAPTER_GATT_BTLE,
5210 ,CA_ADAPTER_REMOTE_ACCESS
5217 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5219 for(int i = 0; i < numConnTypes; i++)
5221 // If CA status is not initialized, CASelectNetwork() will not be called.
5222 if (caResult != CA_STATUS_NOT_INITIALIZED)
5224 if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5226 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5227 caResult = CASelectNetwork(connTypes[i]);
5228 if (caResult == CA_STATUS_OK)
5230 retResult = CA_STATUS_OK;
5235 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5240 if (retResult != CA_STATUS_OK)
5242 return caResult; // Returns error of appropriate transport that failed fatally.
5248 OCStackResult CAResultToOCResult(CAResult_t caResult)
5254 case CA_STATUS_INVALID_PARAM:
5255 return OC_STACK_INVALID_PARAM;
5256 case CA_ADAPTER_NOT_ENABLED:
5257 return OC_STACK_ADAPTER_NOT_ENABLED;
5258 case CA_SERVER_STARTED_ALREADY:
5260 case CA_SERVER_NOT_STARTED:
5261 return OC_STACK_ERROR;
5262 case CA_DESTINATION_NOT_REACHABLE:
5263 return OC_STACK_COMM_ERROR;
5264 case CA_SOCKET_OPERATION_FAILED:
5265 return OC_STACK_COMM_ERROR;
5266 case CA_SEND_FAILED:
5267 return OC_STACK_COMM_ERROR;
5268 case CA_RECEIVE_FAILED:
5269 return OC_STACK_COMM_ERROR;
5270 case CA_MEMORY_ALLOC_FAILED:
5271 return OC_STACK_NO_MEMORY;
5272 case CA_REQUEST_TIMEOUT:
5273 return OC_STACK_TIMEOUT;
5274 case CA_DESTINATION_DISCONNECTED:
5275 return OC_STACK_COMM_ERROR;
5276 case CA_STATUS_FAILED:
5277 return OC_STACK_ERROR;
5278 case CA_NOT_SUPPORTED:
5279 return OC_STACK_NOTIMPL;
5281 return OC_STACK_ERROR;
5285 bool OCResultToSuccess(OCStackResult ocResult)
5290 case OC_STACK_RESOURCE_CREATED:
5291 case OC_STACK_RESOURCE_DELETED:
5292 case OC_STACK_CONTINUE:
5293 case OC_STACK_RESOURCE_CHANGED:
5294 case OC_STACK_SLOW_RESOURCE:
5302 OCStackResult OCSetProxyURI(const char *uri)
5304 return CAResultToOCResult(CASetProxyUri(uri));
5308 #if defined(RD_CLIENT) || defined(RD_SERVER)
5309 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5311 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5313 OCResource *resource = NULL;
5315 resource = findResource((OCResource *) handle);
5318 OIC_LOG(ERROR, TAG, "Resource not found");
5319 return OC_STACK_ERROR;
5322 resource->ins = ins;
5328 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5329 const OCClientResponse *response)
5331 // Validate input parameters
5332 VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5333 VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5335 char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5338 return OC_STACK_NO_MEMORY;
5340 strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5342 if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5344 OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5346 char rdPubUri[MAX_URI_LENGTH] = { 0 };
5347 snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5348 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5350 if (strcmp(rdPubUri, targetUri) == 0)
5352 // Update resource unique id in stack.
5355 if (response->payload)
5357 OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5358 OCRepPayload **links = NULL;
5359 size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5360 if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5361 &links, dimensions))
5364 for (; i < dimensions[0]; i++)
5367 if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5369 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5371 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5373 OCBindResourceInsToResource(handle, ins);
5382 size_t count = calcDimTotal(dimensions);
5383 for (size_t k = 0; k < count; k++)
5385 OCRepPayloadDestroy(links[k]);
5393 else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5395 OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5397 uint8_t numResources = 0;
5398 OCGetNumberOfResources(&numResources);
5400 char *ins = strstr(targetUri, OC_RSRVD_INS);
5403 for (uint8_t i = 0; i < numResources; i++)
5405 OCResourceHandle resHandle = OCGetResourceHandle(i);
5408 OCBindResourceInsToResource(resHandle, 0);
5414 const char *token = "&";
5415 char *iterTokenPtr = NULL;
5416 char *start = strtok_r(targetUri, token, &iterTokenPtr);
5418 while (start != NULL)
5420 char *query = start;
5421 query = strstr(query, OC_RSRVD_INS);
5424 int64_t queryIns = atoi(query + 4);
5425 for (uint8_t i = 0; i < numResources; i++)
5427 OCResourceHandle resHandle = OCGetResourceHandle(i);
5431 OCGetResourceIns(resHandle, &resIns);
5432 if (queryIns && queryIns == resIns)
5434 OCBindResourceInsToResource(resHandle, 0);
5440 start = strtok_r(NULL, token, &iterTokenPtr);
5449 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5453 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5457 OCResource *pointer = headResource;
5461 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5463 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5466 pointer = pointer->next;
5471 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t *ins)
5473 OCResource *resource = NULL;
5475 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5476 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5478 resource = findResource((OCResource *) handle);
5481 *ins = resource->ins;
5484 return OC_STACK_ERROR;
5488 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5489 const void* optionData, size_t optionDataLength)
5493 OIC_LOG (INFO, TAG, "Header options are NULL");
5494 return OC_STACK_INVALID_PARAM;
5499 OIC_LOG (INFO, TAG, "optionData are NULL");
5500 return OC_STACK_INVALID_PARAM;
5505 OIC_LOG (INFO, TAG, "numOptions is NULL");
5506 return OC_STACK_INVALID_PARAM;
5509 if (*numOptions >= MAX_HEADER_OPTIONS)
5511 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5512 return OC_STACK_NO_MEMORY;
5515 ocHdrOpt += *numOptions;
5516 ocHdrOpt->protocolID = OC_COAP_ID;
5517 ocHdrOpt->optionID = optionID;
5518 ocHdrOpt->optionLength =
5519 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
5520 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5521 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5527 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5528 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5530 if (!ocHdrOpt || !numOptions)
5532 OIC_LOG (INFO, TAG, "No options present");
5538 OIC_LOG (INFO, TAG, "optionData are NULL");
5539 return OC_STACK_INVALID_PARAM;
5542 if (!receivedDataLength)
5544 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5545 return OC_STACK_INVALID_PARAM;
5548 for (uint8_t i = 0; i < numOptions; i++)
5550 if (ocHdrOpt[i].optionID == optionID)
5552 if (optionDataLength >= ocHdrOpt->optionLength)
5554 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5555 *receivedDataLength = ocHdrOpt->optionLength;
5560 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5561 return OC_STACK_ERROR;
5568 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5570 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5576 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5578 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5581 * If the client observes one or more resources over a reliable connection,
5582 * then the CoAP server (or intermediary in the role of the CoAP server)
5583 * MUST remove all entries associated with the client endpoint from the lists
5584 * of observers when the connection is either closed or times out.
5588 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5589 CopyEndpointToDevAddr(info, &devAddr);
5591 // remove observer list with remote device address.
5592 DeleteObserverUsingDevAddr(&devAddr);
5596 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5599 OCStackResult ret = OC_STACK_ERROR;
5601 ret = GetDoxmDeviceID(&oicUuid);
5602 if (OC_STACK_OK == ret)
5604 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5608 OIC_LOG(ERROR, TAG, "Device ID Get error");
5613 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5616 OCStackResult ret = OC_STACK_ERROR;
5618 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5619 for (int i = 0; i < UUID_LENGTH; i++)
5621 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5623 ret = SetDoxmDeviceID(&oicUuid);
5627 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5629 bool isDeviceOwned = true;
5630 OCStackResult ret = OC_STACK_ERROR;
5632 ret = GetDoxmIsOwned(&isDeviceOwned);
5633 if (OC_STACK_OK == ret)
5635 *isOwned = isDeviceOwned;
5639 OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5644 OCStackResult OCGetDeviceOperationalState(bool* isOp)
5648 *isOp = GetPstatIsop();
5652 return OC_STACK_ERROR;
5655 void OCClearCallBackList()
5657 DeleteClientCBList();
5660 void OCClearObserverlist()
5662 DeleteObserverList();
5665 int OCEncrypt(const unsigned char *pt, size_t pt_len,
5666 unsigned char **ct, size_t *ct_len)
5668 #ifndef __SECURE_PSI__
5669 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5672 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5674 return psiEncrypt(pt, pt_len, ct, ct_len);
5675 #endif // __SECURE_PSI__
5678 int OCDecrypt(const unsigned char *ct, size_t ct_len,
5679 unsigned char **pt, size_t *pt_len)
5681 #ifndef __SECURE_PSI__
5682 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5685 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5687 return psiDecrypt(ct, ct_len, pt, pt_len);
5688 #endif // __SECURE_PSI__
5691 OCStackResult OCSetKey(const unsigned char* key)
5693 #ifndef __SECURE_PSI__
5694 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5697 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5699 return psiSetKey(key);
5700 #endif // __SECURE_PSI__
5703 OCStackResult OCGetKey(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 psiGetKey(key);
5712 #endif // __SECURE_PSI__
5715 OCStackResult OCSetSecurePSI(const unsigned char *key, const OCPersistentStorage *psPlain,
5716 const OCPersistentStorage *psEnc, const OCPersistentStorage *psRescue)
5718 #ifndef __SECURE_PSI__
5719 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5722 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5724 return setSecurePSI(key, psPlain, psEnc, psRescue);
5725 #endif // __SECURE_PSI__
5728 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5729 static void OtmEventHandler(const char *addr, uint16_t port, const char *uuid, int event)
5731 if (g_otmEventHandler.cb)
5733 g_otmEventHandler.cb(g_otmEventHandler.ctx, addr, port, uuid, event);
5738 * It is already declared in srmutility.h.
5739 * We can't include the header file, because of "redefined VERIFY_NON_NULL"
5741 typedef void (*OicSecOtmEventHandler_t)(const char* addr, uint16_t port,
5742 const char* uuid, int event);
5743 void SetOtmEventHandler(OicSecOtmEventHandler_t otmEventHandler);
5746 OCStackResult OCSetOtmEventHandler(void *ctx, OCOtmEventHandler cb)
5748 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5749 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5751 g_otmEventHandler.cb = cb;
5752 g_otmEventHandler.ctx = ctx;
5754 if (g_otmEventHandler.cb)
5756 OIC_LOG(DEBUG, TAG, "SET OCOtmEventHandler");
5757 SetOtmEventHandler(OtmEventHandler);
5761 OIC_LOG(DEBUG, TAG, "UNSET OCOtmEventHandler");
5762 SetOtmEventHandler(NULL);
5765 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);