1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //-----------------------------------------------------------------------------
24 //-----------------------------------------------------------------------------
26 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
27 // causes header files to expose definitions
28 // corresponding to the POSIX.1-2001 base
29 // specification (excluding the XSI extension).
30 // For POSIX.1-2001 base specification,
31 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
32 #define _POSIX_C_SOURCE 200112L
33 #ifndef __STDC_FORMAT_MACROS
34 #define __STDC_FORMAT_MACROS
36 #ifndef __STDC_LIMIT_MACROS
37 #define __STDC_LIMIT_MACROS
39 #include "iotivity_config.h"
45 #include "ocstackinternal.h"
46 #include "ocresourcehandler.h"
47 #include "occlientcb.h"
48 #include "ocobserve.h"
50 #include "oic_malloc.h"
51 #include "oic_string.h"
54 #include "ocserverrequest.h"
55 #include "secureresourcemanager.h"
56 #include "psinterface.h"
58 #include "doxmresource.h"
60 #include "cainterface.h"
61 #include "ocpayload.h"
62 #include "ocpayloadcbor.h"
63 #include "cautilinterface.h"
64 #include "camessagehandler.h"
67 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
68 #include "routingutility.h"
69 #ifdef ROUTING_GATEWAY
70 #include "routingmanager.h"
75 #include "oickeepaliveinternal.h"
78 //#ifdef DIRECT_PAIRING
79 #include "directpairing.h"
82 #ifdef HAVE_ARDUINO_TIME_H
85 #ifdef HAVE_SYS_TIME_H
88 #include <coap/coap.h>
90 #ifdef HAVE_ARPA_INET_H
91 #include <arpa/inet.h>
95 #define UINT32_MAX (0xFFFFFFFFUL)
98 //-----------------------------------------------------------------------------
100 //-----------------------------------------------------------------------------
103 OC_STACK_UNINITIALIZED = 0,
104 OC_STACK_INITIALIZED,
105 OC_STACK_UNINIT_IN_PROGRESS
111 OC_PRESENCE_UNINITIALIZED = 0,
112 OC_PRESENCE_INITIALIZED
116 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
119 OCOtmEventHandler cb;
121 } OCOtmEventHandler_t;
124 //-----------------------------------------------------------------------------
126 //-----------------------------------------------------------------------------
127 static OCStackState stackState = OC_STACK_UNINITIALIZED;
129 OCResource *headResource = NULL;
130 static OCResource *tailResource = NULL;
131 static OCResourceHandle platformResource = {0};
132 static OCResourceHandle deviceResource = {0};
134 static OCResourceHandle brokerResource = {0};
138 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
139 static PresenceResource presenceResource = {0};
140 static uint8_t PresenceTimeOutSize = 0;
141 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
144 static OCMode myStackMode;
146 //TODO: revisit this design
147 static bool gRASetInfo = false;
149 OCDeviceEntityHandler defaultDeviceHandler;
150 void* defaultDeviceHandlerCallbackParameter = NULL;
151 static const char COAP_TCP_SCHEME[] = "coap+tcp:";
152 static const char COAPS_TCP_SCHEME[] = "coaps+tcp:";
153 static const char CORESPEC[] = "core";
155 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
156 static OCOtmEventHandler_t g_otmEventHandler = {NULL, NULL};
159 #ifdef WITH_PROCESS_EVENT
160 static oc_event g_ocProcessEvent = NULL;
161 #endif // WITH_PROCESS_EVENT
163 //-----------------------------------------------------------------------------
165 //-----------------------------------------------------------------------------
166 #define TAG "OIC_RI_STACK"
167 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
168 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
169 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
170 TAG, #arg " is NULL"); return (retVal); } }
171 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
172 TAG, #arg " is NULL"); return; } }
173 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
176 //TODO: we should allow the server to define this
177 #define MAX_OBSERVE_AGE (0x2FFFFUL)
179 #define MILLISECONDS_PER_SECOND (1000)
181 //-----------------------------------------------------------------------------
182 // Private internal function prototypes
183 //-----------------------------------------------------------------------------
186 * Generate handle of OCDoResource invocation for callback management.
188 * @return Generated OCDoResource handle.
190 static OCDoHandle GenerateInvocationHandle();
193 * Initialize resource data structures, variables, etc.
195 * @return ::OC_STACK_OK on success, some other value upon failure.
197 static OCStackResult initResources();
200 * Add a resource to the end of the linked list of resources.
202 * @param resource Resource to be added
204 static void insertResource(OCResource *resource);
207 * Find a resource in the linked list of resources.
209 * @param resource Resource to be found.
210 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
213 static OCResource *findResource(OCResource *resource);
216 * Insert a resource type into a resource's resource type linked list.
217 * If resource type already exists, it will not be inserted and the
218 * resourceType will be free'd.
219 * resourceType->next should be null to avoid memory leaks.
220 * Function returns silently for null args.
222 * @param resource Resource where resource type is to be inserted.
223 * @param resourceType Resource type to be inserted.
225 static void insertResourceType(OCResource *resource,
226 OCResourceType *resourceType);
229 * Get a resource type at the specified index within a resource.
231 * @param handle Handle of resource.
232 * @param index Index of resource type.
234 * @return Pointer to resource type if found, NULL otherwise.
236 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
240 * Insert a resource interface into a resource's resource interface linked list.
241 * If resource interface already exists, it will not be inserted and the
242 * resourceInterface will be free'd.
243 * resourceInterface->next should be null to avoid memory leaks.
245 * @param resource Resource where resource interface is to be inserted.
246 * @param resourceInterface Resource interface to be inserted.
248 static void insertResourceInterface(OCResource *resource,
249 OCResourceInterface *resourceInterface);
252 * Get a resource interface at the specified index within a resource.
254 * @param handle Handle of resource.
255 * @param index Index of resource interface.
257 * @return Pointer to resource interface if found, NULL otherwise.
259 static OCResourceInterface *findResourceInterfaceAtIndex(
260 OCResourceHandle handle, uint8_t index);
263 * Delete all of the dynamically allocated elements that were created for the resource type.
265 * @param resourceType Specified resource type.
267 static void deleteResourceType(OCResourceType *resourceType);
270 * Delete all of the dynamically allocated elements that were created for the resource interface.
272 * @param resourceInterface Specified resource interface.
274 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
277 * Unbind all child resources.
279 * @param resourceChild Specified binded resource head is deleted from parent.
281 static void unbindChildResources(OCChildResource *resourceChild);
284 * Delete all of the dynamically allocated elements that were created for the resource.
286 * @param resource Specified resource.
288 static void deleteResourceElements(OCResource *resource);
291 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
294 * @param handle Handle of resource to be deleted.
296 * @return ::OC_STACK_OK on success, some other value upon failure.
298 static OCStackResult deleteResource(OCResource *resource);
301 * Delete all of the resources in the resource list.
303 static void deleteAllResources();
306 * Increment resource sequence number. Handles rollover.
308 * @param resPtr Pointer to resource.
310 static void incrementSequenceNumber(OCResource * resPtr);
313 * Attempts to initialize every network interface that the CA Layer might have compiled in.
315 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
316 * return something other than @ref CA_STATUS_OK, then this function fails.
317 * @param transportType OCTransportAdapter value to select.
318 * @return ::CA_STATUS_OK on success, some other value upon failure.
320 static CAResult_t OCSelectNetwork(OCTransportAdapter transportType);
323 * Convert CAResponseResult_t to OCStackResult.
325 * @param caCode CAResponseResult_t code.
326 * @return ::OC_STACK_OK on success, some other value upon failure.
328 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
331 * Convert OCTransportFlags_t to CATransportModifiers_t.
333 * @param ocConType OCTransportFlags_t input.
334 * @return CATransportFlags
336 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
339 * Convert CATransportFlags_t to OCTransportModifiers_t.
341 * @param caConType CATransportFlags_t input.
342 * @return OCTransportFlags
344 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
347 * Handle response from presence request.
349 * @param endPoint CA remote endpoint.
350 * @param responseInfo CA response info.
351 * @return ::OC_STACK_OK on success, some other value upon failure.
353 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
354 const CAResponseInfo_t *responseInfo);
357 * This function will be called back by CA layer when a response is received.
359 * @param endPoint CA remote endpoint.
360 * @param responseInfo CA response info.
362 static void HandleCAResponses(const CAEndpoint_t* endPoint,
363 const CAResponseInfo_t* responseInfo);
366 * This function will be called back by CA layer when a request is received.
368 * @param endPoint CA remote endpoint.
369 * @param requestInfo CA request info.
371 static void HandleCARequests(const CAEndpoint_t* endPoint,
372 const CARequestInfo_t* requestInfo);
375 * Extract query from a URI.
377 * @param uri Full URI with query.
378 * @param query Pointer to string that will contain query.
379 * @param newURI Pointer to string that will contain URI.
380 * @return ::OC_STACK_OK on success, some other value upon failure.
382 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
385 * Finds a resource type in an OCResourceType link-list.
387 * @param resourceTypeList The link-list to be searched through.
388 * @param resourceTypeName The key to search for.
390 * @return Resource type that matches the key (ie. resourceTypeName) or
391 * NULL if there is either an invalid parameter or this function was unable to find the key.
393 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
394 const char * resourceTypeName);
398 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
399 * TTL will be set to maxAge.
401 * @param cbNode Callback Node for which presence ttl is to be reset.
402 * @param maxAge New value of ttl in seconds.
404 * @return ::OC_STACK_OK on success, some other value upon failure.
406 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
410 * Ensure the accept header option is set appropriatly before sending the requests and routing
411 * header option is updated with destination.
413 * @param object CA remote endpoint.
414 * @param requestInfo CA request info.
416 * @return ::OC_STACK_OK on success, some other value upon failure.
418 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
421 * default adapter state change callback method
423 * @param adapter CA network adapter type.
424 * @param enabled current adapter state.
426 static void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled);
429 * default connection state change callback method
431 * @param info CAEndpoint which has address, port and etc.
432 * @param isConnected current connection state.
434 static void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected);
436 //-----------------------------------------------------------------------------
437 // Internal functions
438 //-----------------------------------------------------------------------------
440 bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
442 if (!options || 0 == numOptions)
444 OIC_LOG (INFO, TAG, "No options present");
448 for (uint8_t i = 0; i < numOptions; i++)
450 if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
452 OIC_LOG(DEBUG, TAG, "Proxy URI is present");
459 uint32_t GetTicks(uint32_t milliSeconds)
464 // Guard against overflow of uint32_t
465 if (milliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
466 COAP_TICKS_PER_SECOND)
468 return now + (milliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
476 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
478 VERIFY_NON_NULL_NR(in, FATAL);
479 VERIFY_NON_NULL_NR(out, FATAL);
481 out->adapter = (OCTransportAdapter)in->adapter;
482 out->flags = CAToOCTransportFlags(in->flags);
483 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
484 out->port = in->port;
485 out->ifindex = in->ifindex;
486 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
487 /* This assert is to prevent accidental mismatch between address size macros defined in
488 * RI and CA and cause crash here. */
489 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
490 "Address size mismatch between RI and CA");
491 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
495 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
497 VERIFY_NON_NULL_NR(in, FATAL);
498 VERIFY_NON_NULL_NR(out, FATAL);
500 out->adapter = (CATransportAdapter_t)in->adapter;
501 out->flags = OCToCATransportFlags(in->flags);
502 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
503 OICStrcpy(out->remoteId, sizeof(out->remoteId), in->remoteId);
504 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
505 /* This assert is to prevent accidental mismatch between address size macros defined in
506 * RI and CA and cause crash here. */
507 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
508 "Address size mismatch between RI and CA");
509 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
511 out->port = in->port;
512 out->ifindex = in->ifindex;
515 void FixUpClientResponse(OCClientResponse *cr)
517 VERIFY_NON_NULL_NR(cr, FATAL);
519 cr->addr = &cr->devAddr;
520 cr->connType = (OCConnectivityType)
521 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
524 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
526 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
527 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
528 OIC_TRACE_BEGIN(%s:OCSendRequest, TAG);
530 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
531 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
532 if (OC_STACK_OK != rmResult)
534 OIC_LOG(ERROR, TAG, "Add destination option failed");
540 // OC stack prefer CBOR encoded payloads.
541 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
542 CAResult_t result = CASendRequest(object, requestInfo);
543 if(CA_STATUS_OK != result)
545 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
547 return CAResultToOCResult(result);
553 //-----------------------------------------------------------------------------
554 // Internal API function
555 //-----------------------------------------------------------------------------
557 // This internal function is called to update the stack with the status of
558 // observers and communication failures
559 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
561 OCStackResult result = OC_STACK_ERROR;
562 ResourceObserver * observer = NULL;
563 OCEntityHandlerRequest ehRequest = {0};
567 case OC_OBSERVER_NOT_INTERESTED:
568 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
569 observer = GetObserverUsingToken(token, tokenLength);
572 result = FormOCEntityHandlerRequest(&ehRequest,
576 (OCResourceHandle)NULL,
577 NULL, PAYLOAD_TYPE_REPRESENTATION,
579 OC_OBSERVE_DEREGISTER,
582 if (result != OC_STACK_OK)
584 FreeObserver(observer);
588 if (observer->resource && observer->resource->entityHandler)
590 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
591 observer->resource->entityHandlerCallbackParam);
594 FreeObserver(observer);
597 result = DeleteObserverUsingToken(token, tokenLength);
598 if (result == OC_STACK_OK)
600 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
604 result = OC_STACK_OK;
605 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
609 case OC_OBSERVER_STILL_INTERESTED:
610 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
611 observer = GetObserverUsingToken(token, tokenLength);
614 observer->forceHighQos = 0;
615 observer->failedCommCount = 0;
616 result = OC_STACK_OK;
617 FreeObserver(observer);
621 result = OC_STACK_OBSERVER_NOT_FOUND;
625 case OC_OBSERVER_FAILED_COMM:
626 OIC_LOG(DEBUG, TAG, "observer is unreachable");
627 observer = GetObserverUsingToken (token, tokenLength);
630 if (observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
632 result = FormOCEntityHandlerRequest(&ehRequest,
636 (OCResourceHandle)NULL,
637 NULL, PAYLOAD_TYPE_REPRESENTATION,
639 OC_OBSERVE_DEREGISTER,
642 if (result != OC_STACK_OK)
644 FreeObserver(observer);
645 return OC_STACK_ERROR;
648 if (observer->resource && observer->resource->entityHandler)
650 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
651 observer->resource->entityHandlerCallbackParam);
654 result = DeleteObserverUsingToken(token, tokenLength);
655 if (result == OC_STACK_OK)
657 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
661 result = OC_STACK_OK;
662 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
667 observer->failedCommCount++;
668 observer->forceHighQos = 1;
669 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",
670 observer->failedCommCount);
671 result = OC_STACK_CONTINUE;
674 FreeObserver(observer);
678 OIC_LOG(ERROR, TAG, "Unknown status");
679 result = OC_STACK_ERROR;
685 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
687 OCStackResult ret = OC_STACK_ERROR;
691 ret = OC_STACK_RESOURCE_CREATED;
694 ret = OC_STACK_RESOURCE_DELETED;
697 ret = OC_STACK_RESOURCE_CHANGED;
704 ret = OC_STACK_INVALID_QUERY;
706 case CA_UNAUTHORIZED_REQ:
707 ret = OC_STACK_UNAUTHORIZED_REQ;
710 ret = OC_STACK_INVALID_OPTION;
713 ret = OC_STACK_NO_RESOURCE;
715 case CA_REQUEST_ENTITY_TOO_LARGE:
716 ret = OC_STACK_TOO_LARGE_REQ;
718 case CA_METHOD_NOT_ALLOWED:
719 ret = OC_STACK_METHOD_NOT_ALLOWED;
721 case CA_NOT_ACCEPTABLE:
722 ret = OC_STACK_NOT_ACCEPTABLE;
724 case CA_FORBIDDEN_REQ:
725 ret = OC_STACK_FORBIDDEN_REQ;
727 case CA_TOO_MANY_REQUESTS:
728 ret = OC_STACK_TOO_MANY_REQUESTS;
730 case CA_INTERNAL_SERVER_ERROR:
731 ret = OC_STACK_INTERNAL_SERVER_ERROR;
733 case CA_NOT_IMPLEMENTED:
734 ret = OC_STACK_NOT_IMPLEMENTED;
737 ret = OC_STACK_BAD_GATEWAY;
739 case CA_SERVICE_UNAVAILABLE:
740 ret = OC_STACK_SERVICE_UNAVAILABLE;
742 case CA_RETRANSMIT_TIMEOUT:
743 ret = OC_STACK_GATEWAY_TIMEOUT;
745 case CA_PROXY_NOT_SUPPORTED:
746 ret = OC_STACK_PROXY_NOT_SUPPORTED;
754 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
756 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
765 // This Response Code is like HTTP 204 "No Content" but only used in
766 // response to POST and PUT requests.
770 // This Response Code is like HTTP 200 "OK" but only used in response to
775 // This should not happen but,
776 // give it a value just in case but output an error
778 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
782 case OC_STACK_RESOURCE_CREATED:
785 case OC_STACK_RESOURCE_DELETED:
788 case OC_STACK_RESOURCE_CHANGED:
791 case OC_STACK_INVALID_QUERY:
794 case OC_STACK_INVALID_OPTION:
797 case OC_STACK_NO_RESOURCE:
800 case OC_STACK_COMM_ERROR:
801 ret = CA_RETRANSMIT_TIMEOUT;
803 case OC_STACK_METHOD_NOT_ALLOWED:
804 ret = CA_METHOD_NOT_ALLOWED;
806 case OC_STACK_NOT_ACCEPTABLE:
807 ret = CA_NOT_ACCEPTABLE;
809 case OC_STACK_UNAUTHORIZED_REQ:
810 ret = CA_UNAUTHORIZED_REQ;
812 case OC_STACK_FORBIDDEN_REQ:
813 ret = CA_FORBIDDEN_REQ;
815 case OC_STACK_TOO_MANY_REQUESTS:
816 ret = CA_TOO_MANY_REQUESTS;
818 case OC_STACK_INTERNAL_SERVER_ERROR:
819 ret = CA_INTERNAL_SERVER_ERROR;
821 case OC_STACK_NOT_IMPLEMENTED:
822 ret = CA_NOT_IMPLEMENTED;
824 case OC_STACK_BAD_GATEWAY:
825 ret = CA_BAD_GATEWAY;
827 case OC_STACK_SERVICE_UNAVAILABLE:
828 ret = CA_SERVICE_UNAVAILABLE;
830 case OC_STACK_GATEWAY_TIMEOUT:
831 ret = CA_RETRANSMIT_TIMEOUT;
833 case OC_STACK_PROXY_NOT_SUPPORTED:
834 ret = CA_PROXY_NOT_SUPPORTED;
842 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
844 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
846 // supply default behavior.
847 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
849 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
851 if ((caFlags & OC_MASK_SCOPE) == 0)
853 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
858 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
860 return (OCTransportFlags)caFlags;
864 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
866 uint32_t lowerBound = 0;
867 uint32_t higherBound = 0;
869 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
871 return OC_STACK_INVALID_PARAM;
874 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
876 cbNode->presence->TTL = maxAgeSeconds;
878 for (int index = 0; index < PresenceTimeOutSize; index++)
880 // Guard against overflow
881 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
884 lowerBound = GetTicks((PresenceTimeOut[index] *
885 cbNode->presence->TTL *
886 MILLISECONDS_PER_SECOND)/100);
890 lowerBound = GetTicks(UINT32_MAX);
893 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
896 higherBound = GetTicks((PresenceTimeOut[index + 1] *
897 cbNode->presence->TTL *
898 MILLISECONDS_PER_SECOND)/100);
902 higherBound = GetTicks(UINT32_MAX);
905 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
907 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
908 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
909 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
912 cbNode->presence->TTLlevel = 0;
914 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
918 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
920 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
922 return OC_RSRVD_TRIGGER_CREATE;
924 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
926 return OC_RSRVD_TRIGGER_CHANGE;
930 return OC_RSRVD_TRIGGER_DELETE;
934 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
938 return OC_PRESENCE_TRIGGER_CREATE;
940 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
942 return OC_PRESENCE_TRIGGER_CREATE;
944 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
946 return OC_PRESENCE_TRIGGER_CHANGE;
950 return OC_PRESENCE_TRIGGER_DELETE;
953 #endif // WITH_PRESENCE
955 OCStackResult OCEncodeAddressForRFC6874(char *outputAddress,
957 const char *inputAddress)
959 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
960 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
962 size_t inputLength = strnlen(inputAddress, outputSize);
964 // inputSize includes the null terminator
965 size_t inputSize = inputLength + 1;
967 if (inputSize > outputSize)
969 OIC_LOG_V(ERROR, TAG,
970 "OCEncodeAddressForRFC6874 failed: "
971 "outputSize (%zu) < inputSize (%zu)",
972 outputSize, inputSize);
974 return OC_STACK_ERROR;
977 char* percentChar = strchr(inputAddress, '%');
979 // If there is no '%' character, then no change is required to the string.
980 if (NULL == percentChar)
982 OICStrcpy(outputAddress, outputSize, inputAddress);
986 const char* addressPart = &inputAddress[0];
987 const char* scopeIdPart = percentChar + 1;
989 // Sanity check to make sure this string doesn't have more '%' characters
990 if (NULL != strchr(scopeIdPart, '%'))
992 return OC_STACK_ERROR;
995 // If no string follows the first '%', then the input was invalid.
996 if (scopeIdPart[0] == '\0')
998 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
999 return OC_STACK_ERROR;
1002 // Check to see if the string is already encoded
1003 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
1005 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Input string is already encoded");
1006 return OC_STACK_ERROR;
1009 // Fail if we don't have room for encoded string's two additional chars
1010 if (outputSize < (inputSize + 2))
1012 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: encoded output will not fit!");
1013 return OC_STACK_ERROR;
1016 // Restore the null terminator with an escaped '%' character, per RFC 6874
1017 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
1018 OICStrcat(outputAddress, outputSize, "%25");
1019 OICStrcat(outputAddress, outputSize, scopeIdPart);
1024 OCStackResult OCDecodeAddressForRFC6874(char *outputAddress,
1026 const char *inputAddress,
1029 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
1030 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
1034 end = inputAddress + strlen(inputAddress);
1036 size_t inputLength = end - inputAddress;
1038 const char *percent = strchr(inputAddress, '%');
1039 if (!percent || (percent > end))
1041 OICStrcpyPartial(outputAddress, outputSize, inputAddress, inputLength);
1045 if (percent[1] != '2' || percent[2] != '5')
1047 return OC_STACK_INVALID_URI;
1050 int addrlen = percent - inputAddress + 1;
1051 OICStrcpyPartial(outputAddress, outputSize, inputAddress, addrlen);
1052 OICStrcpyPartial(outputAddress + addrlen, outputSize - addrlen,
1053 percent + 3, end - percent - 3);
1059 #ifdef WITH_PRESENCE
1061 * The cononical presence allows constructed URIs to be string compared.
1063 * requestUri must be a char array of size CA_MAX_URI_LENGTH
1065 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
1066 char *presenceUri, bool isMulticast)
1068 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
1069 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1073 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1074 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1077 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1078 if (ep->adapter == CA_ADAPTER_IP)
1080 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1082 if ('\0' == ep->addr[0]) // multicast
1084 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1088 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1090 OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1091 sizeof(addressEncoded),
1094 if (OC_STACK_OK != result)
1099 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1100 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1105 if ('\0' == ep->addr[0]) // multicast
1107 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1108 ep->port = OC_MULTICAST_PORT;
1110 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1111 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1115 // might work for other adapters (untested, but better than nothing)
1116 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1117 OC_RSRVD_PRESENCE_URI);
1121 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1122 const CAResponseInfo_t *responseInfo)
1124 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1125 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1127 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1128 ClientCB * cbNode = NULL;
1129 char *resourceTypeName = NULL;
1130 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1131 OCStackResult result = OC_STACK_ERROR;
1132 uint32_t maxAge = 0;
1134 char presenceUri[CA_MAX_URI_LENGTH];
1136 int presenceSubscribe = 0;
1137 int multicastPresenceSubscribe = 0;
1139 if (responseInfo->result != CA_CONTENT)
1141 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1142 return OC_STACK_ERROR;
1145 response.payload = NULL;
1146 response.result = OC_STACK_OK;
1148 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1149 FixUpClientResponse(&response);
1151 if (responseInfo->info.payload)
1153 result = OCParsePayload(&response.payload,
1154 PAYLOAD_TYPE_PRESENCE,
1155 responseInfo->info.payload,
1156 responseInfo->info.payloadSize);
1158 if(result != OC_STACK_OK)
1160 OIC_LOG(ERROR, TAG, "Presence parse failed");
1163 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1165 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1166 result = OC_STACK_ERROR;
1169 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1170 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1171 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1174 // check for unicast presence
1175 uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1176 responseInfo->isMulticast);
1177 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1179 return OC_STACK_INVALID_URI;
1181 OIC_LOG(INFO, TAG, "check for unicast presence");
1182 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1185 presenceSubscribe = 1;
1189 // check for multicast presence
1190 OIC_LOG(INFO, TAG, "check for multicast presence");
1191 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1194 multicastPresenceSubscribe = 1;
1198 if (!presenceSubscribe && !multicastPresenceSubscribe)
1200 OIC_LOG(INFO, TAG, "Received a presence notification, "
1201 "but need to register presence callback, ignoring");
1205 if (presenceSubscribe)
1207 if(cbNode->sequenceNumber == response.sequenceNumber)
1209 OIC_LOG(INFO, TAG, "No presence change");
1210 ResetPresenceTTL(cbNode, maxAge);
1211 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1217 OIC_LOG(INFO, TAG, "Stopping presence");
1218 response.result = OC_STACK_PRESENCE_STOPPED;
1219 if(cbNode->presence)
1221 OICFree(cbNode->presence->timeOut);
1222 OICFree(cbNode->presence);
1223 cbNode->presence = NULL;
1228 if(!cbNode->presence)
1230 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1232 if(!(cbNode->presence))
1234 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1235 result = OC_STACK_NO_MEMORY;
1239 VERIFY_NON_NULL_V(cbNode->presence);
1240 cbNode->presence->timeOut = NULL;
1241 cbNode->presence->timeOut = (uint32_t *)
1242 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1243 if(!(cbNode->presence->timeOut)){
1245 "Could not allocate memory for cbNode->presence->timeOut");
1246 OICFree(cbNode->presence);
1247 cbNode->presence = NULL;
1248 result = OC_STACK_NO_MEMORY;
1253 ResetPresenceTTL(cbNode, maxAge);
1255 cbNode->sequenceNumber = response.sequenceNumber;
1260 // This is the multicast case
1261 OIC_LOG(INFO, TAG, "this is the multicast presence");
1264 OIC_LOG(INFO, TAG, "Stopping presence");
1265 response.result = OC_STACK_PRESENCE_STOPPED;
1269 // Ensure that a filter is actually applied.
1270 if (resourceTypeName && cbNode->filterResourceType)
1272 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1273 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1279 OIC_LOG(INFO, TAG, "Before calling into application address space for presence");
1280 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1281 OIC_LOG(INFO, TAG, "After calling into application address space for presence");
1283 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1285 FindAndDeleteClientCB(cbNode);
1289 OCPayloadDestroy(response.payload);
1292 #endif // WITH_PRESENCE
1294 OCStackResult HandleBatchResponse(char *requestUri, OCRepPayload **payload)
1296 if (requestUri && *payload)
1298 char *interfaceName = NULL;
1299 char *rtTypeName = NULL;
1300 char *uriQuery = NULL;
1301 char *uriWithoutQuery = NULL;
1302 if (OC_STACK_OK == getQueryFromUri(requestUri, &uriQuery, &uriWithoutQuery))
1304 if (OC_STACK_OK == ExtractFiltersFromQuery(uriQuery, &interfaceName, &rtTypeName))
1306 if (interfaceName && (0 == strcmp(OC_RSRVD_INTERFACE_BATCH, interfaceName)))
1308 char *uri = (*payload)->uri;
1309 if (uri && 0 != strcmp(uriWithoutQuery, uri))
1311 OCRepPayload *newPayload = OCRepPayloadCreate();
1314 OCRepPayloadSetUri(newPayload, uri);
1315 newPayload->next = *payload;
1316 *payload = newPayload;
1323 OICFree(interfaceName);
1324 OICFree(rtTypeName);
1326 OICFree(uriWithoutQuery);
1329 return OC_STACK_INVALID_PARAM;
1332 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1334 OIC_TRACE_MARK(%s:OCHandleResponse:%s, TAG, responseInfo->info.resourceUri);
1335 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1337 #ifdef WITH_PRESENCE
1338 if(responseInfo->info.resourceUri &&
1339 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1341 HandlePresenceResponse(endPoint, responseInfo);
1346 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1347 responseInfo->info.tokenLength, NULL, NULL);
1351 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1353 // check obs header option
1354 bool obsHeaderOpt = false;
1355 CAHeaderOption_t *options = responseInfo->info.options;
1356 for (uint8_t i = 0; i< responseInfo->info.numOptions; i++)
1358 if (options && options[i].protocolID == CA_COAP_ID &&
1359 options[i].optionID == COAP_OPTION_OBSERVE)
1361 obsHeaderOpt = true;
1366 if(responseInfo->result == CA_EMPTY)
1368 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1369 // We do not have a case for the client to receive a RESET
1370 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1372 //This is the case of receiving an ACK on a request to a slow resource!
1373 OIC_LOG(INFO, TAG, "This is a pure ACK");
1374 //TODO: should we inform the client
1375 // app that at least the request was received at the server?
1378 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1380 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1382 OCClientResponse response =
1383 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1384 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1385 FixUpClientResponse(&response);
1386 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1387 memcpy(response.identity.id, responseInfo->info.identity.id,
1388 sizeof (response.identity.id));
1389 response.identity.id_length = responseInfo->info.identity.id_length;
1391 response.result = CAResponseToOCStackResult(responseInfo->result);
1392 OIC_LOG(INFO, TAG, "Before calling into application address space for reTrans timeout");
1393 cbNode->callBack(cbNode->context,
1394 cbNode->handle, &response);
1395 OIC_LOG(INFO, TAG, "After calling into application address space for reTrans timeout");
1396 FindAndDeleteClientCB(cbNode);
1397 OICFree((void *)response.resourceUri);
1400 else if ((cbNode->method == OC_REST_OBSERVE || cbNode->method == OC_REST_OBSERVE_ALL)
1401 && (responseInfo->result == CA_CONTENT) && !obsHeaderOpt)
1403 OCClientResponse response =
1404 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1405 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1406 FixUpClientResponse(&response);
1407 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1408 memcpy(response.identity.id, responseInfo->info.identity.id,
1409 sizeof (response.identity.id));
1410 response.identity.id_length = responseInfo->info.identity.id_length;
1411 response.result = OC_STACK_UNAUTHORIZED_REQ;
1413 OIC_LOG(INFO, TAG, "Before calling into application address space for observe resp");
1414 cbNode->callBack(cbNode->context,
1417 OIC_LOG(INFO, TAG, "After calling into application address space for observe resp");
1419 FindAndDeleteClientCB(cbNode);
1420 OICFree(response.resourceUri);
1425 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1427 OCClientResponse response;
1428 memset(&response, 0, sizeof(OCClientResponse));
1429 response.devAddr.adapter = OC_DEFAULT_ADAPTER;
1431 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1432 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1433 FixUpClientResponse(&response);
1434 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1435 memcpy(response.identity.id, responseInfo->info.identity.id,
1436 sizeof (response.identity.id));
1437 response.identity.id_length = responseInfo->info.identity.id_length;
1439 response.result = CAResponseToOCStackResult(responseInfo->result);
1441 if(responseInfo->info.payload &&
1442 responseInfo->info.payloadSize)
1444 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1445 // check the security resource
1446 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1448 type = PAYLOAD_TYPE_SECURITY;
1450 else if (cbNode->method == OC_REST_DISCOVER)
1452 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1453 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1455 type = PAYLOAD_TYPE_DISCOVERY;
1458 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1460 type = PAYLOAD_TYPE_DISCOVERY;
1463 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1465 type = PAYLOAD_TYPE_REPRESENTATION;
1467 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1469 type = PAYLOAD_TYPE_REPRESENTATION;
1472 #ifdef ROUTING_GATEWAY
1473 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1475 type = PAYLOAD_TYPE_REPRESENTATION;
1478 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1480 type = PAYLOAD_TYPE_REPRESENTATION;
1483 else if (strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1485 type = PAYLOAD_TYPE_REPRESENTATION;
1490 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1491 cbNode->method, cbNode->requestUri);
1492 OICFree((void *)response.resourceUri);
1496 else if (cbNode->method == OC_REST_GET ||
1497 cbNode->method == OC_REST_PUT ||
1498 cbNode->method == OC_REST_POST ||
1499 cbNode->method == OC_REST_OBSERVE ||
1500 cbNode->method == OC_REST_OBSERVE_ALL ||
1501 cbNode->method == OC_REST_DELETE)
1503 if (cbNode->requestUri)
1505 if (0 == strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri))
1507 type = PAYLOAD_TYPE_REPRESENTATION;
1509 else if (0 == strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri))
1511 type = PAYLOAD_TYPE_REPRESENTATION;
1513 if (type == PAYLOAD_TYPE_INVALID)
1515 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1516 cbNode->method, cbNode->requestUri);
1517 type = PAYLOAD_TYPE_REPRESENTATION;
1522 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1523 type = PAYLOAD_TYPE_REPRESENTATION;
1528 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1529 cbNode->method, cbNode->requestUri);
1530 OICFree((void *)response.resourceUri);
1534 // In case of error, still want application to receive the error message.
1535 if (OCResultToSuccess(response.result) || PAYLOAD_TYPE_REPRESENTATION == type)
1537 if(OC_STACK_OK != OCParsePayload(&response.payload,
1539 responseInfo->info.payload,
1540 responseInfo->info.payloadSize))
1542 OIC_LOG(ERROR, TAG, "Error converting payload");
1543 OCPayloadDestroy(response.payload);
1544 OICFree((void *)response.resourceUri);
1550 OICFree((void *)response.resourceUri);
1551 response.resourceUri = OICStrdup(cbNode->requestUri);
1555 response.numRcvdVendorSpecificHeaderOptions = 0;
1556 if(responseInfo->info.numOptions > 0)
1559 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1560 if(responseInfo->info.options
1561 && responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1564 uint32_t observationOption;
1565 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1566 for (observationOption=0, i=0;
1567 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1571 (observationOption << 8) | optionData[i];
1573 response.sequenceNumber = observationOption;
1574 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1579 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1582 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1584 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1585 OCPayloadDestroy(response.payload);
1586 OICFree((void *)response.resourceUri);
1590 if (response.numRcvdVendorSpecificHeaderOptions > 0)
1592 response.rcvdVendorSpecificHeaderOptions =
1593 (OCHeaderOption *) OICCalloc(response.numRcvdVendorSpecificHeaderOptions, sizeof(OCHeaderOption));
1594 if (NULL == response.rcvdVendorSpecificHeaderOptions)
1596 OIC_LOG(ERROR, TAG, "Failed to allocate memory for vendor header options");
1597 OCPayloadDestroy(response.payload);
1598 OICFree((void *)response.resourceUri);
1602 memcpy(response.rcvdVendorSpecificHeaderOptions, responseInfo->info.options + start,
1603 response.numRcvdVendorSpecificHeaderOptions*sizeof(OCHeaderOption));
1607 if (cbNode->method == OC_REST_OBSERVE &&
1608 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1609 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1610 response.sequenceNumber <= cbNode->sequenceNumber)
1612 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1613 response.sequenceNumber);
1618 if (cbNode->requestUri)
1620 // if request uri is '/oic/rd', update ins value of resource.
1621 char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
1624 OCUpdateResourceInsWithResponse(cbNode->requestUri, &response);
1628 // set remoteID(device ID) into OCClientResponse callback parameter
1629 if (OC_REST_DISCOVER == cbNode->method)
1631 OIC_LOG(INFO, TAG, "cbNode method is OC_REST_DISCOVER");
1632 OCDiscoveryPayload *payload = (OCDiscoveryPayload*) response.payload;
1633 // Payload can be empty in case of error message.
1634 if (payload && payload->sid)
1636 OICStrcpy(response.devAddr.remoteId, sizeof(response.devAddr.remoteId),
1638 OIC_LOG_V(INFO_PRIVATE, TAG, "Device ID of response : %s",
1639 response.devAddr.remoteId);
1642 if(NULL == response.resourceUri)
1644 response.resourceUri = OICStrdup(cbNode->requestUri);
1648 if (cbNode->requestUri)
1650 OIC_LOG_V(INFO, TAG, "cbNode requestUri is %s", cbNode->requestUri);
1651 if (cbNode->method == OC_REST_POST &&
1652 strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1654 OCHandleKeepAliveResponse(endPoint, response.payload);
1658 if (response.payload && response.payload->type == PAYLOAD_TYPE_REPRESENTATION)
1660 OIC_LOG(INFO, TAG, "Handle batch response");
1661 HandleBatchResponse(cbNode->requestUri, (OCRepPayload **)&response.payload);
1664 OIC_LOG(INFO, TAG, "Before calling into application address space for handleResponse");
1665 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1668 OIC_LOG(INFO, TAG, "After calling into application address space for handleResponse");
1670 cbNode->sequenceNumber = response.sequenceNumber;
1672 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1674 FindAndDeleteClientCB(cbNode);
1678 // To keep discovery callbacks active.
1679 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1680 MILLISECONDS_PER_SECOND);
1684 //Need to send ACK when the response is CON
1685 if(responseInfo->info.type == CA_MSG_CONFIRM)
1687 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1689 OIC_LOG(INFO, TAG, "Received a confirmable message. Sending EMPTY");
1690 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1691 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1695 OICFree((void *)response.resourceUri);
1696 OCPayloadDestroy(response.payload);
1697 OICFree(response.rcvdVendorSpecificHeaderOptions);
1702 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1703 responseInfo->info.tokenLength);
1707 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1708 if(responseInfo->result == CA_EMPTY)
1710 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1711 if(responseInfo->info.type == CA_MSG_RESET)
1713 OIC_LOG(INFO, TAG, "This is a RESET");
1714 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1715 OC_OBSERVER_NOT_INTERESTED);
1717 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1719 OIC_LOG(INFO, TAG, "This is a pure ACK");
1720 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1721 OC_OBSERVER_STILL_INTERESTED);
1724 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1726 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1727 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1728 OC_OBSERVER_FAILED_COMM);
1731 FreeObserver(observer);
1735 if(!cbNode && !observer)
1737 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1738 || myStackMode == OC_GATEWAY)
1740 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1741 if(responseInfo->result == CA_EMPTY)
1743 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1747 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1749 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1750 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1751 CA_MSG_RESET, 0, NULL, NULL, 0, NULL,
1752 CA_RESPONSE_FOR_RES);
1757 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1758 || myStackMode == OC_GATEWAY)
1760 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1761 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1763 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1764 responseInfo->info.messageId);
1766 if (responseInfo->info.type == CA_MSG_RESET)
1768 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1769 responseInfo->info.messageId);
1777 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1779 VERIFY_NON_NULL_NR(endPoint, FATAL);
1780 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1782 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1783 OIC_TRACE_BEGIN(%s:HandleCAResponses, TAG);
1785 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1786 #ifdef ROUTING_GATEWAY
1787 bool needRIHandling = false;
1789 * Routing manager is going to update either of endpoint or response or both.
1790 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1791 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1794 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1796 if(ret != OC_STACK_OK || !needRIHandling)
1798 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1805 * Put source in sender endpoint so that the next packet from application can be routed to
1806 * proper destination and remove "RM" coap header option before passing request / response to
1807 * RI as this option will make no sense to either RI or application.
1809 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1810 (uint8_t *) &(responseInfo->info.numOptions),
1811 (CAEndpoint_t *) endPoint);
1814 OCHandleResponse(endPoint, responseInfo);
1816 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1820 * This function handles error response from CA
1821 * code shall be added to handle the errors
1823 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1825 VERIFY_NON_NULL_NR(endPoint, FATAL);
1826 VERIFY_NON_NULL_NR(errorInfo, FATAL);
1828 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1829 OIC_TRACE_BEGIN(%s:HandleCAErrorResponse, TAG);
1831 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1832 errorInfo->info.tokenLength, NULL, NULL);
1835 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1836 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1837 FixUpClientResponse(&response);
1838 response.resourceUri = errorInfo->info.resourceUri;
1839 memcpy(response.identity.id, errorInfo->info.identity.id,
1840 sizeof (response.identity.id));
1841 response.identity.id_length = errorInfo->info.identity.id_length;
1842 response.result = CAResultToOCResult(errorInfo->result);
1844 OIC_LOG(INFO, TAG, "Before calling into application address space for error response");
1845 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1846 OIC_LOG(INFO, TAG, "After calling into application address space for error response");
1849 ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1850 errorInfo->info.tokenLength);
1853 OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1854 OCStackResult result = CAResultToOCResult(errorInfo->result);
1855 if (OC_STACK_COMM_ERROR == result)
1857 OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1858 OC_OBSERVER_FAILED_COMM);
1862 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1867 * This function sends out Direct Stack Responses. These are responses that are not coming
1868 * from the application entity handler. These responses have no payload and are usually ACKs,
1869 * RESETs or some error conditions that were caught by the stack.
1871 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1872 const CAResponseResult_t responseResult, const CAMessageType_t type,
1873 const uint8_t numOptions, const CAHeaderOption_t *options,
1874 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1875 CADataType_t dataType)
1877 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1879 if (endPoint->flags & CA_MULTICAST)
1881 OIC_LOG(ERROR, TAG, "It is unnecessary to respond to a multicast request");
1885 CAResponseInfo_t respInfo = { .result = responseResult };
1886 respInfo.info.messageId = coapID;
1887 respInfo.info.numOptions = numOptions;
1889 if (respInfo.info.numOptions)
1891 respInfo.info.options =
1892 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1893 memcpy (respInfo.info.options, options,
1894 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1898 respInfo.info.payload = NULL;
1899 respInfo.info.token = token;
1900 respInfo.info.tokenLength = tokenLength;
1901 respInfo.info.type = type;
1902 respInfo.info.resourceUri = OICStrdup (resourceUri);
1903 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1904 respInfo.info.dataType = dataType;
1906 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1907 // Add the destination to route option from the endpoint->routeData.
1908 bool doPost = false;
1909 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1910 if(OC_STACK_OK != result)
1912 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1913 OICFree (respInfo.info.resourceUri);
1914 OICFree (respInfo.info.options);
1919 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1920 CARequestInfo_t reqInfo = {.method = CA_POST };
1921 /* The following initialization is not done in a single initializer block as in
1922 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1923 * does not have designated initalizers. This is a work-around for now.
1925 reqInfo.info.type = CA_MSG_NONCONFIRM;
1926 reqInfo.info.messageId = coapID;
1927 reqInfo.info.tokenLength = tokenLength;
1928 reqInfo.info.token = token;
1929 reqInfo.info.numOptions = respInfo.info.numOptions;
1930 reqInfo.info.payload = NULL;
1931 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1932 if (reqInfo.info.numOptions)
1934 reqInfo.info.options =
1935 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1936 if (NULL == reqInfo.info.options)
1938 OIC_LOG(ERROR, TAG, "Calloc failed");
1939 OICFree (reqInfo.info.resourceUri);
1940 OICFree (respInfo.info.resourceUri);
1941 OICFree (respInfo.info.options);
1942 return OC_STACK_NO_MEMORY;
1944 memcpy (reqInfo.info.options, respInfo.info.options,
1945 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1948 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1949 OICFree (reqInfo.info.resourceUri);
1950 OICFree (reqInfo.info.options);
1951 OICFree (respInfo.info.resourceUri);
1952 OICFree (respInfo.info.options);
1953 if (CA_STATUS_OK != caResult)
1955 OIC_LOG(ERROR, TAG, "CASendRequest error");
1956 return CAResultToOCResult(caResult);
1962 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1964 // resourceUri in the info field is cloned in the CA layer and
1965 // thus ownership is still here.
1966 OICFree (respInfo.info.resourceUri);
1967 OICFree (respInfo.info.options);
1968 if(CA_STATUS_OK != caResult)
1970 OIC_LOG(ERROR, TAG, "CASendResponse error");
1971 return CAResultToOCResult(caResult);
1974 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1978 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1980 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1981 OCStackResult result = OC_STACK_ERROR;
1982 if(!protocolRequest)
1984 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1985 return OC_STACK_INVALID_PARAM;
1988 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1989 protocolRequest->tokenLength);
1992 OIC_LOG(INFO, TAG, "This is a new Server Request");
1993 result = AddServerRequest(&request, protocolRequest->coapID,
1994 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1995 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1996 protocolRequest->observationOption, protocolRequest->qos,
1997 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1998 protocolRequest->payload, protocolRequest->requestToken,
1999 protocolRequest->tokenLength, protocolRequest->resourceUrl,
2000 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
2001 &protocolRequest->devAddr);
2002 if (OC_STACK_OK != result)
2004 OIC_LOG(ERROR, TAG, "Error adding server request");
2010 OIC_LOG(ERROR, TAG, "Out of Memory");
2011 return OC_STACK_NO_MEMORY;
2014 if(!protocolRequest->reqMorePacket)
2016 request->requestComplete = 1;
2019 OIC_LOG_V(WARNING, TAG, "Server request ID = [%u]", request->requestId);
2023 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
2024 return OC_STACK_DUPLICATE_REQUEST;
2027 if(request->requestComplete)
2029 OIC_LOG(INFO, TAG, "This Server Request is complete");
2030 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2031 OCResource *resource = NULL;
2032 result = DetermineResourceHandling (request, &resHandling, &resource);
2033 if (result == OC_STACK_OK)
2035 result = ProcessRequest(resHandling, resource, request);
2040 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2041 result = OC_STACK_CONTINUE;
2046 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2048 OIC_TRACE_MARK(%s:OCHandleRequests:%s, TAG, requestInfo->info.resourceUri);
2049 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2051 OCStackResult requestResult = OC_STACK_ERROR;
2053 if(myStackMode == OC_CLIENT)
2055 //TODO: should the client be responding to requests?
2059 OCServerProtocolRequest serverRequest = {0};
2061 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2063 char * uriWithoutQuery = NULL;
2064 char * query = NULL;
2066 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2068 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2070 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2073 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2074 OIC_LOG_V(INFO, TAG, "Query : %s", query);
2076 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2078 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2079 OICFree(uriWithoutQuery);
2083 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2084 OICFree(uriWithoutQuery);
2091 if(strlen(query) < MAX_QUERY_LENGTH)
2093 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2098 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2104 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2106 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2107 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2108 if (!serverRequest.payload)
2110 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2113 memcpy (serverRequest.payload, requestInfo->info.payload,
2114 requestInfo->info.payloadSize);
2118 serverRequest.reqTotalSize = 0;
2121 switch (requestInfo->method)
2124 serverRequest.method = OC_REST_GET;
2127 serverRequest.method = OC_REST_PUT;
2130 serverRequest.method = OC_REST_POST;
2133 serverRequest.method = OC_REST_DELETE;
2136 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2137 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2138 requestInfo->info.type, requestInfo->info.numOptions,
2139 requestInfo->info.options, requestInfo->info.token,
2140 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2142 OICFree(serverRequest.payload);
2146 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2147 requestInfo->info.tokenLength);
2149 serverRequest.tokenLength = requestInfo->info.tokenLength;
2150 if (serverRequest.tokenLength) {
2152 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2154 if (!serverRequest.requestToken)
2156 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2157 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2158 requestInfo->info.type, requestInfo->info.numOptions,
2159 requestInfo->info.options, requestInfo->info.token,
2160 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2162 OICFree(serverRequest.payload);
2165 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2168 switch (requestInfo->info.acceptFormat)
2170 case CA_FORMAT_APPLICATION_CBOR:
2171 serverRequest.acceptFormat = OC_FORMAT_CBOR;
2173 case CA_FORMAT_UNDEFINED:
2174 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2177 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2180 if (requestInfo->info.type == CA_MSG_CONFIRM)
2182 serverRequest.qos = OC_HIGH_QOS;
2186 serverRequest.qos = OC_LOW_QOS;
2188 // CA does not need the following field
2189 // Are we sure CA does not need them? how is it responding to multicast
2190 serverRequest.delayedResNeeded = 0;
2192 serverRequest.coapID = requestInfo->info.messageId;
2194 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2196 // copy vendor specific header options
2197 uint8_t tempNum = (requestInfo->info.numOptions);
2199 // Assume no observation requested and it is a pure GET.
2200 // If obs registration/de-registration requested it'll be fetched from the
2201 // options in GetObserveHeaderOption()
2202 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2204 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2205 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2208 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2209 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2210 requestInfo->info.type, requestInfo->info.numOptions,
2211 requestInfo->info.options, requestInfo->info.token,
2212 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2214 OICFree(serverRequest.payload);
2215 OICFree(serverRequest.requestToken);
2219 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2220 if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2222 serverRequest.rcvdVendorSpecificHeaderOptions = (OCHeaderOption*) OICCalloc(tempNum, sizeof(OCHeaderOption));
2223 if (NULL == serverRequest.rcvdVendorSpecificHeaderOptions)
2225 OIC_LOG(ERROR, TAG, "Failed to allocated memory to vnd header options!");
2226 OICFree(serverRequest.payload);
2227 OICFree(serverRequest.requestToken);
2231 memcpy (serverRequest.rcvdVendorSpecificHeaderOptions, requestInfo->info.options,
2232 sizeof(CAHeaderOption_t)*tempNum);
2235 requestResult = HandleStackRequests (&serverRequest);
2237 // Send ACK to client as precursor to slow response
2238 if (requestResult == OC_STACK_SLOW_RESOURCE)
2240 if (requestInfo->info.type == CA_MSG_CONFIRM)
2242 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2243 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2248 if (requestResult == OC_STACK_RESOURCE_ERROR
2249 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2251 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2254 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2256 if (requestResult == OC_STACK_RESOURCE_ERROR)
2258 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2260 else if (!OCResultToSuccess(requestResult))
2262 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2266 else if(!OCResultToSuccess(requestResult))
2268 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2270 // Delete observer node if it is OBSERVE failure from app
2271 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2273 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2276 CAResponseResult_t stackResponse =
2277 OCToCAStackResult(requestResult, serverRequest.method);
2279 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2280 requestInfo->info.type, requestInfo->info.numOptions,
2281 requestInfo->info.options, requestInfo->info.token,
2282 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2285 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2286 // The token is copied in there, and is thus still owned by this function.
2287 OICFree(serverRequest.payload);
2288 OICFree(serverRequest.requestToken);
2289 OICFree(serverRequest.rcvdVendorSpecificHeaderOptions);
2290 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2293 //This function will be called back by CA layer when a request is received
2294 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2296 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2297 OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2300 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2307 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2312 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2313 #ifdef ROUTING_GATEWAY
2314 bool needRIHandling = false;
2315 bool isEmptyMsg = false;
2317 * Routing manager is going to update either of endpoint or request or both.
2318 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2319 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2320 * destination. It can also remove "RM" coap header option before passing request / response to
2321 * RI as this option will make no sense to either RI or application.
2323 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2324 &needRIHandling, &isEmptyMsg);
2325 if(OC_STACK_OK != ret || !needRIHandling)
2327 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2334 * Put source in sender endpoint so that the next packet from application can be routed to
2335 * proper destination and remove RM header option.
2337 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2338 (uint8_t *) &(requestInfo->info.numOptions),
2339 (CAEndpoint_t *) endPoint);
2341 #ifdef ROUTING_GATEWAY
2345 * In Gateways, the MSGType in route option is used to check if the actual
2346 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2347 * EMPTY response is sent in the form of POST request which need to be changed
2348 * to a EMPTY response by RM. This translation is done in this part of the code.
2350 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2351 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2352 .info.messageId = requestInfo->info.messageId,
2353 .info.type = CA_MSG_ACKNOWLEDGE};
2354 OCHandleResponse(endPoint, &respInfo);
2360 // Normal handling of the packet
2361 OCHandleRequests(endPoint, requestInfo);
2363 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2367 //-----------------------------------------------------------------------------
2369 //-----------------------------------------------------------------------------
2371 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2374 !raInfo->username ||
2375 !raInfo->hostname ||
2376 !raInfo->xmpp_domain)
2379 return OC_STACK_INVALID_PARAM;
2381 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2382 gRASetInfo = (result == OC_STACK_OK)? true : false;
2388 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2392 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2395 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2397 OC_UNUSED(serverFlags);
2398 OC_UNUSED(clientFlags);
2400 OIC_LOG(DEBUG, TAG, "call OCInit1");
2401 return OCInit2(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS, OC_DEFAULT_ADAPTER);
2404 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2405 OCTransportAdapter transportType)
2407 if(stackState == OC_STACK_INITIALIZED)
2409 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2410 OCStop() between them are ignored.");
2414 #ifndef ROUTING_GATEWAY
2415 if (OC_GATEWAY == mode)
2417 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2418 return OC_STACK_INVALID_PARAM;
2425 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2426 return OC_STACK_ERROR;
2430 OCStackResult result = OC_STACK_ERROR;
2431 OIC_LOG(INFO, TAG, "Entering OCInit");
2434 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2435 || (mode == OC_GATEWAY)))
2437 OIC_LOG(ERROR, TAG, "Invalid mode");
2438 return OC_STACK_ERROR;
2442 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2444 caglobals.client = true;
2446 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2448 caglobals.server = true;
2451 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2452 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2454 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2456 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2457 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2459 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2462 defaultDeviceHandler = NULL;
2463 defaultDeviceHandlerCallbackParameter = NULL;
2465 result = InitializeScheduleResourceList();
2466 VERIFY_SUCCESS(result, OC_STACK_OK);
2468 result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2469 VERIFY_SUCCESS(result, OC_STACK_OK);
2471 result = CAResultToOCResult(OCSelectNetwork(transportType));
2472 VERIFY_SUCCESS(result, OC_STACK_OK);
2474 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2475 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2476 VERIFY_SUCCESS(result, OC_STACK_OK);
2478 switch (myStackMode)
2481 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2482 result = CAResultToOCResult(CAStartDiscoveryServer());
2483 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2486 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2487 result = CAResultToOCResult(CAStartListeningServer());
2488 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2490 case OC_CLIENT_SERVER:
2492 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2493 result = CAResultToOCResult(CAStartListeningServer());
2494 if(result == OC_STACK_OK)
2496 result = CAResultToOCResult(CAStartDiscoveryServer());
2500 VERIFY_SUCCESS(result, OC_STACK_OK);
2503 CARegisterKeepAliveHandler(OCHandleKeepAliveConnCB);
2506 #ifdef WITH_PRESENCE
2507 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2508 #endif // WITH_PRESENCE
2510 //Update Stack state to initialized
2511 stackState = OC_STACK_INITIALIZED;
2513 // Initialize resource
2514 if(myStackMode != OC_CLIENT)
2516 result = initResources();
2519 // Initialize the SRM Policy Engine
2520 if(result == OC_STACK_OK)
2522 result = SRMInitPolicyEngine();
2523 // TODO after BeachHead delivery: consolidate into single SRMInit()
2525 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2526 RMSetStackMode(mode);
2527 #ifdef ROUTING_GATEWAY
2528 if (OC_GATEWAY == myStackMode)
2530 result = RMInitialize();
2536 if (result == OC_STACK_OK)
2538 result = OCInitializeKeepAlive(myStackMode);
2542 InitializeObserverList();
2545 if(result != OC_STACK_OK)
2547 OIC_LOG(ERROR, TAG, "Stack initialization error");
2548 TerminateScheduleResourceList();
2549 deleteAllResources();
2551 stackState = OC_STACK_UNINITIALIZED;
2556 OCStackResult OCStop()
2558 OIC_LOG(INFO, TAG, "Entering OCStop");
2560 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2562 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2565 else if (stackState != OC_STACK_INITIALIZED)
2567 OIC_LOG(INFO, TAG, "Stack not initialized");
2568 return OC_STACK_ERROR;
2571 // unset cautil config
2572 CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2573 CAUtilSetBTConfigure(configs);
2575 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2577 CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2578 OCDefaultConnectionStateChangedHandler);
2580 #ifdef WITH_PRESENCE
2581 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2582 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2583 presenceResource.presenceTTL = 0;
2584 presenceState = OC_PRESENCE_UNINITIALIZED;
2585 #endif // WITH_PRESENCE
2587 #ifdef ROUTING_GATEWAY
2588 if (OC_GATEWAY == myStackMode)
2595 OCTerminateKeepAlive(myStackMode);
2598 TerminateScheduleResourceList();
2599 // Remove all observers
2600 DeleteObserverList();
2601 // Free memory dynamically allocated for resources
2602 deleteAllResources();
2603 // Remove all the client callbacks
2604 DeleteClientCBList();
2605 // Terminate connectivity-abstraction layer.
2608 // De-init the SRM Policy Engine
2609 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2610 SRMDeInitPolicyEngine();
2612 // Destroy Observer List Mutex
2613 TerminateObserverList();
2615 stackState = OC_STACK_UNINITIALIZED;
2619 OCStackResult OCStartMulticastServer()
2621 if(stackState != OC_STACK_INITIALIZED)
2623 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2624 return OC_STACK_ERROR;
2626 CAResult_t ret = CAStartListeningServer();
2627 if (CA_STATUS_OK != ret)
2629 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2630 return OC_STACK_ERROR;
2635 OCStackResult OCStopMulticastServer()
2637 CAResult_t ret = CAStopListeningServer();
2638 if (CA_STATUS_OK != ret)
2640 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2641 return OC_STACK_ERROR;
2646 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2651 return CA_MSG_CONFIRM;
2656 return CA_MSG_NONCONFIRM;
2660 OCStackResult ParseRequestUri(const char *fullUri,
2661 OCTransportAdapter adapter,
2662 OCTransportFlags flags,
2663 OCDevAddr **devAddr,
2665 char **resourceType)
2667 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2669 OCStackResult result = OC_STACK_OK;
2670 OCDevAddr *da = NULL;
2674 // provide defaults for all returned values
2681 *resourceUri = NULL;
2685 *resourceType = NULL;
2688 // delimit url prefix, if any
2689 const char *start = fullUri;
2690 char *slash2 = strstr(start, "//");
2695 char *slash = strchr(start, '/');
2698 return OC_STACK_INVALID_URI;
2701 // process url scheme
2702 size_t prefixLen = slash2 - fullUri;
2706 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2707 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2713 // TODO: this logic should come in with unit tests exercising the various strings
2714 // processs url prefix, if any
2715 size_t urlLen = slash - start;
2719 if (urlLen && devAddr)
2720 { // construct OCDevAddr
2721 if (start[0] == '[')
2723 char *close = strchr(++start, ']');
2724 if (!close || close > slash)
2726 return OC_STACK_INVALID_URI;
2729 if (close[1] == ':')
2736 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2740 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2742 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2746 char *dot = strchr(start, '.');
2747 if (dot && dot < slash)
2749 colon = strchr(start, ':');
2750 end = (colon && colon < slash) ? colon : slash;
2755 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2759 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2761 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2769 if (len >= sizeof(da->addr))
2771 return OC_STACK_INVALID_URI;
2773 // collect port, if any
2774 if (colon && colon < slash)
2776 for (colon++; colon < slash; colon++)
2779 if (c < '0' || c > '9')
2781 return OC_STACK_INVALID_URI;
2783 port = 10 * port + c - '0';
2788 if (len >= sizeof(da->addr))
2790 return OC_STACK_INVALID_URI;
2793 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2796 return OC_STACK_NO_MEMORY;
2799 // Decode address per RFC 6874.
2800 result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2801 if (result != OC_STACK_OK)
2808 da->adapter = adapter;
2810 if (!strncmp(fullUri, "coaps", 5))
2812 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2817 // process resource uri, if any
2819 { // request uri and query
2820 size_t ulen = strlen(slash); // resource uri length
2821 size_t tlen = 0; // resource type length
2824 static const char strPresence[] = "/oic/ad?rt=";
2825 static const size_t lenPresence = sizeof(strPresence) - 1;
2826 if (!strncmp(slash, strPresence, lenPresence))
2828 type = slash + lenPresence;
2829 tlen = ulen - lenPresence;
2834 *resourceUri = (char *)OICMalloc(ulen + 1);
2837 result = OC_STACK_NO_MEMORY;
2840 OICStrcpy(*resourceUri, (ulen + 1), slash);
2843 if (type && resourceType)
2845 *resourceType = (char *)OICMalloc(tlen + 1);
2848 result = OC_STACK_NO_MEMORY;
2852 OICStrcpy(*resourceType, (tlen+1), type);
2859 // free all returned values
2866 OICFree(*resourceUri);
2870 OICFree(*resourceType);
2875 #ifdef WITH_PRESENCE
2876 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2880 char uri[CA_MAX_URI_LENGTH];
2882 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2884 *requestUri = OICStrdup(uri);
2887 return OC_STACK_NO_MEMORY;
2892 #endif // WITH_PRESENCE
2895 * Discover or Perform requests on a specified resource
2897 OCStackResult OCDoResource(OCDoHandle *handle,
2899 const char *requestUri,
2900 const OCDevAddr *destination,
2902 OCConnectivityType connectivityType,
2903 OCQualityOfService qos,
2904 OCCallbackData *cbData,
2905 OCHeaderOption *options,
2908 OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
2909 connectivityType, qos, cbData, options, numOptions);
2911 // This is the owner of the payload object, so we free it
2912 OCPayloadDestroy(payload);
2917 * Discover or Perform requests on a specified resource
2919 OCStackResult OCDoRequest(OCDoHandle *handle,
2921 const char *requestUri,
2922 const OCDevAddr *destination,
2924 OCConnectivityType connectivityType,
2925 OCQualityOfService qos,
2926 OCCallbackData *cbData,
2927 OCHeaderOption *options,
2930 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2931 OIC_TRACE_BEGIN(%s:OCDoRequest, TAG);
2933 // Validate input parameters
2934 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2935 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2937 OCStackResult result = OC_STACK_ERROR;
2938 CAResult_t caResult;
2939 CAToken_t token = NULL;
2940 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2941 ClientCB *clientCB = NULL;
2942 OCDoHandle resHandle = NULL;
2943 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2944 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2946 OCTransportAdapter adapter;
2947 OCTransportFlags flags;
2948 // the request contents are put here
2949 CARequestInfo_t requestInfo = {.method = CA_GET};
2950 // requestUri will be parsed into the following three variables
2951 OCDevAddr *devAddr = NULL;
2952 char *resourceUri = NULL;
2953 char *resourceType = NULL;
2956 * Support original behavior with address on resourceUri argument.
2958 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2959 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2963 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2964 if (result != OC_STACK_OK)
2966 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2970 else if (!checkProxyUri(options, numOptions))
2972 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2979 case OC_REST_OBSERVE:
2980 case OC_REST_OBSERVE_ALL:
2981 requestInfo.method = CA_GET;
2984 requestInfo.method = CA_PUT;
2987 requestInfo.method = CA_POST;
2989 case OC_REST_DELETE:
2990 requestInfo.method = CA_DELETE;
2992 case OC_REST_DISCOVER:
2993 #ifdef WITH_PRESENCE
2994 case OC_REST_PRESENCE:
2996 if (destination || devAddr)
2998 requestInfo.isMulticast = false;
3002 tmpDevAddr.adapter = adapter;
3003 tmpDevAddr.flags = flags;
3004 destination = &tmpDevAddr;
3005 requestInfo.isMulticast = true;
3008 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
3009 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
3010 // replacing method type with GET.
3011 requestInfo.method = CA_GET;
3014 result = OC_STACK_INVALID_METHOD;
3018 if (!devAddr && !destination)
3020 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
3021 result = OC_STACK_INVALID_PARAM;
3025 /* If not original behavior, use destination argument */
3026 if (destination && !devAddr)
3028 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
3031 result = OC_STACK_NO_MEMORY;
3034 OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
3035 *devAddr = *destination;
3040 OIC_LOG_V(INFO_PRIVATE, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
3041 if (!requestInfo.isMulticast)
3043 OIC_LOG_V(DEBUG, TAG, "remoteAddr of devAddr : [%s]:[%d]",
3044 devAddr->addr, devAddr->port);
3048 resHandle = GenerateInvocationHandle();
3051 result = OC_STACK_NO_MEMORY;
3055 caResult = CAGenerateToken(&token, tokenLength);
3056 if (caResult != CA_STATUS_OK)
3058 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3059 result= OC_STACK_ERROR;
3063 // fill in request data
3064 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3065 requestInfo.info.token = token;
3066 requestInfo.info.tokenLength = tokenLength;
3068 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3070 result = CreateObserveHeaderOption (&(requestInfo.info.options),
3071 options, numOptions, OC_OBSERVE_REGISTER);
3072 if (result != OC_STACK_OK)
3076 requestInfo.info.numOptions = numOptions + 1;
3080 requestInfo.info.numOptions = numOptions;
3081 requestInfo.info.options =
3082 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3083 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3084 numOptions * sizeof(CAHeaderOption_t));
3087 CopyDevAddrToEndpoint(devAddr, &endpoint);
3092 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3095 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3098 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3102 requestInfo.info.payload = NULL;
3103 requestInfo.info.payloadSize = 0;
3104 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3107 // prepare for response
3108 #ifdef WITH_PRESENCE
3109 if (method == OC_REST_PRESENCE)
3111 char *presenceUri = NULL;
3112 result = OCPreparePresence(&endpoint, &presenceUri,
3113 requestInfo.isMulticast);
3114 if (OC_STACK_OK != result)
3119 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3120 // Presence notification will form a canonical uri to
3121 // look for callbacks into the application.
3124 OICFree(resourceUri);
3126 resourceUri = presenceUri;
3130 // update resourceUri onto requestInfo after check presence uri
3131 requestInfo.info.resourceUri = resourceUri;
3133 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3134 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3135 method, devAddr, resourceUri, resourceType, ttl);
3136 if (OC_STACK_OK != result)
3141 cbData = NULL; // Client CB list entry now owns it
3142 token = NULL; // Client CB list entry now owns it
3143 devAddr = NULL; // Client CB list entry now owns it
3144 resourceUri = NULL; // Client CB list entry now owns it
3145 resourceType = NULL; // Client CB list entry now owns it
3147 #ifdef WITH_PRESENCE
3148 if (method == OC_REST_PRESENCE)
3150 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3154 *handle = resHandle;
3156 #ifdef WITH_PROCESS_EVENT
3157 OCSendProcessEventSignal();
3158 #endif // WITH_PROCESS_EVENT
3165 result = OCSendRequest(&endpoint, &requestInfo);
3166 if (OC_STACK_OK != result)
3173 *handle = resHandle;
3177 if (result != OC_STACK_OK)
3179 OIC_LOG(ERROR, TAG, "OCDoResource error");
3180 if (NULL != cbData && NULL != cbData->cd)
3182 cbData->cd(cbData->context);
3184 FindAndDeleteClientCB(clientCB);
3185 CADestroyToken(token);
3193 OICFree(requestInfo.info.payload);
3195 OICFree(resourceUri);
3196 OICFree(resourceType);
3197 OICFree(requestInfo.info.options);
3202 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3206 * This ftn is implemented one of two ways in the case of observation:
3208 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3209 * Remove the callback associated on client side.
3210 * When the next notification comes in from server,
3211 * reply with RESET message to server.
3212 * Keep in mind that the server will react to RESET only
3213 * if the last notification was sent as CON
3215 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3216 * and it is associated with an observe request
3217 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3218 * Send CON Observe request to server with
3219 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3220 * Remove the callback associated on client side.
3222 OCStackResult ret = OC_STACK_OK;
3223 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3224 CARequestInfo_t requestInfo = {.method = CA_GET};
3228 return OC_STACK_INVALID_PARAM;
3231 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3234 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3235 return OC_STACK_ERROR;
3238 switch (clientCB->method)
3240 case OC_REST_OBSERVE:
3241 case OC_REST_OBSERVE_ALL:
3243 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3245 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3247 if (((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS) ||
3248 ((endpoint.adapter & CA_ADAPTER_TCP) && OC_LOW_QOS_WITH_TCP == qos))
3250 OIC_LOG_V(INFO, TAG, "the %s observe callback is removed", clientCB->requestUri);
3251 FindAndDeleteClientCB(clientCB);
3255 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3257 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3258 requestInfo.info.token = clientCB->token;
3259 requestInfo.info.tokenLength = clientCB->tokenLength;
3261 if (CreateObserveHeaderOption (&(requestInfo.info.options),
3262 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3264 return OC_STACK_ERROR;
3266 requestInfo.info.numOptions = numOptions + 1;
3267 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3270 ret = OCSendRequest(&endpoint, &requestInfo);
3272 if (requestInfo.info.options)
3274 OICFree (requestInfo.info.options);
3276 if (requestInfo.info.resourceUri)
3278 OICFree (requestInfo.info.resourceUri);
3283 case OC_REST_DISCOVER:
3284 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3285 clientCB->requestUri);
3286 FindAndDeleteClientCB(clientCB);
3289 #ifdef WITH_PRESENCE
3290 case OC_REST_PRESENCE:
3291 FindAndDeleteClientCB(clientCB);
3297 case OC_REST_DELETE:
3298 OIC_LOG_V(INFO, TAG, "Cancelling request callback for resource %s",
3299 clientCB->requestUri);
3300 FindAndDeleteClientCB(clientCB);
3304 ret = OC_STACK_INVALID_METHOD;
3312 * @brief Register Persistent storage callback.
3313 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3315 * OC_STACK_OK - No errors; Success
3316 * OC_STACK_INVALID_PARAM - Invalid parameter
3318 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3320 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3321 if(!persistentStorageHandler)
3323 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3324 return OC_STACK_INVALID_PARAM;
3328 if( !persistentStorageHandler->open ||
3329 !persistentStorageHandler->close ||
3330 !persistentStorageHandler->read ||
3331 !persistentStorageHandler->unlink ||
3332 !persistentStorageHandler->write)
3334 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3335 return OC_STACK_INVALID_PARAM;
3338 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3341 #ifdef WITH_PRESENCE
3343 #ifdef WITH_PROCESS_EVENT
3344 OCStackResult OCProcessPresence(uint32_t *nextEventTime)
3345 #else // WITH_PROCESS_EVENT
3346 OCStackResult OCProcessPresence(void)
3347 #endif // !WITH_PROCESS_EVENT
3349 OCStackResult result = OC_STACK_OK;
3351 // the following line floods the log with messages that are irrelevant
3352 // to most purposes. Uncomment as needed.
3353 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3354 ClientCB* cbNode = NULL;
3355 ClientCB* tempcbNode = NULL;
3356 OCClientResponse clientResponse;
3357 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3359 LL_FOREACH_SAFE(cbList, cbNode, tempcbNode)
3361 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3366 uint32_t now = GetTicks(0);
3367 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3368 cbNode->presence->TTLlevel);
3369 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3371 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3376 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3378 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3379 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3381 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3383 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3385 clientResponse.sequenceNumber = 0;
3386 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3387 clientResponse.devAddr = *cbNode->devAddr;
3388 FixUpClientResponse(&clientResponse);
3389 clientResponse.payload = NULL;
3391 // Increment the TTLLevel (going to a next state), so we don't keep
3392 // sending presence notification to client.
3393 cbNode->presence->TTLlevel++;
3394 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3395 cbNode->presence->TTLlevel);
3397 OIC_LOG(INFO, TAG, "Before calling into application address space for presence timeout");
3398 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3399 OIC_LOG(INFO, TAG, "After calling into application address space for presence timeout");
3401 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3403 FindAndDeleteClientCB(cbNode);
3408 uint32_t timeout = cbNode->presence->timeOut[cbNode->presence->TTLlevel];
3411 #ifdef WITH_PROCESS_EVENT
3412 if (nextEventTime && (timeout - now) < *nextEventTime)
3414 *nextEventTime = timeout - now;
3416 #endif // WITH_PROCESS_EVENT
3420 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3421 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3422 CARequestInfo_t requestInfo = {.method = CA_GET};
3424 OIC_LOG(DEBUG, TAG, "time to test server presence");
3426 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3428 requestData.type = CA_MSG_NONCONFIRM;
3429 requestData.token = cbNode->token;
3430 requestData.tokenLength = cbNode->tokenLength;
3431 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3432 requestInfo.method = CA_GET;
3433 requestInfo.info = requestData;
3435 result = OCSendRequest(&endpoint, &requestInfo);
3436 if (OC_STACK_OK != result)
3441 cbNode->presence->TTLlevel++;
3442 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3445 if (result != OC_STACK_OK)
3447 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3452 #endif // WITH_PRESENCE
3454 #ifdef WITH_PROCESS_EVENT
3455 OCStackResult OCProcess(void)
3457 uint32_t nextEventTime;
3458 return OCProcessEvent(&nextEventTime);
3461 OCStackResult OCProcessEvent(uint32_t *nextEventTime)
3463 if (stackState == OC_STACK_UNINITIALIZED)
3465 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3466 return OC_STACK_ERROR;
3469 *nextEventTime = UINT32_MAX;
3471 #ifdef WITH_PRESENCE
3472 OCProcessPresence(nextEventTime);
3473 OIC_LOG_V(INFO, TAG, "OCProcessPresence next event time : %u", *nextEventTime);
3475 CAHandleRequestResponse();
3478 #ifdef ROUTING_GATEWAY
3479 RMProcess(nextEventTime);
3483 OCProcessKeepAlive(nextEventTime);
3484 OIC_LOG_V(INFO, TAG, "OCProcessKeepAlive next event time : %u", *nextEventTime);
3489 void OCRegisterProcessEvent(oc_event event)
3491 g_ocProcessEvent = event;
3492 CARegisterProcessEvent(event);
3495 void OCSendProcessEventSignal(void)
3497 if (g_ocProcessEvent)
3499 oc_event_signal(g_ocProcessEvent);
3502 #else // WITH_PROCESS_EVENT
3504 OCStackResult OCProcess()
3506 if (stackState == OC_STACK_UNINITIALIZED)
3508 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3509 return OC_STACK_ERROR;
3511 #ifdef WITH_PRESENCE
3512 OCProcessPresence();
3514 CAHandleRequestResponse();
3516 #ifdef ROUTING_GATEWAY
3521 OCProcessKeepAlive();
3525 #endif // !WITH_PROCESS_EVENT
3527 #ifdef WITH_PRESENCE
3528 OCStackResult OCStartPresence(const uint32_t ttl)
3530 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3531 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3532 OCChangeResourceProperty(
3533 &(((OCResource *)presenceResource.handle)->resourceProperties),
3536 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3538 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3539 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3543 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3544 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3548 presenceResource.presenceTTL = ttl;
3551 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3554 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3556 presenceState = OC_PRESENCE_INITIALIZED;
3558 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3560 CAToken_t caToken = NULL;
3561 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3562 if (caResult != CA_STATUS_OK)
3564 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3565 CADestroyToken(caToken);
3566 return OC_STACK_ERROR;
3569 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3570 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3571 CADestroyToken(caToken);
3574 // Each time OCStartPresence is called
3575 // a different random 32-bit integer number is used
3576 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3578 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3579 OC_PRESENCE_TRIGGER_CREATE);
3582 OCStackResult OCStopPresence()
3584 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3585 OCStackResult result = OC_STACK_ERROR;
3587 if(presenceResource.handle)
3589 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3591 // make resource inactive
3592 result = OCChangeResourceProperty(
3593 &(((OCResource *) presenceResource.handle)->resourceProperties),
3597 if(result != OC_STACK_OK)
3600 "Changing the presence resource properties to ACTIVE not successful");
3604 return SendStopNotification();
3608 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3609 void* callbackParameter)
3611 defaultDeviceHandler = entityHandler;
3612 defaultDeviceHandlerCallbackParameter = callbackParameter;
3617 OCStackResult OCCreateResource(OCResourceHandle *handle,
3618 const char *resourceTypeName,
3619 const char *resourceInterfaceName,
3620 const char *uri, OCEntityHandler entityHandler,
3621 void* callbackParam,
3622 uint8_t resourceProperties)
3625 OCResource *pointer = NULL;
3626 OCStackResult result = OC_STACK_ERROR;
3628 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3630 if(myStackMode == OC_CLIENT)
3632 return OC_STACK_INVALID_PARAM;
3634 // Validate parameters
3635 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3637 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3638 return OC_STACK_INVALID_URI;
3640 // Is it presented during resource discovery?
3641 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3643 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3644 return OC_STACK_INVALID_PARAM;
3647 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3649 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3653 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3655 // Make sure resourceProperties bitmask has allowed properties specified
3656 if (resourceProperties
3657 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3658 OC_EXPLICIT_DISCOVERABLE
3667 OIC_LOG(ERROR, TAG, "Invalid property");
3668 return OC_STACK_INVALID_PARAM;
3671 // If the headResource is NULL, then no resources have been created...
3672 pointer = headResource;
3675 // At least one resources is in the resource list, so we need to search for
3676 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3679 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3681 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3682 return OC_STACK_INVALID_PARAM;
3684 pointer = pointer->next;
3687 // Create the pointer and insert it into the resource list
3688 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3691 result = OC_STACK_NO_MEMORY;
3694 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3696 insertResource(pointer);
3699 pointer->uri = OICStrdup(uri);
3702 result = OC_STACK_NO_MEMORY;
3706 // Set properties. Set OC_ACTIVE
3707 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3710 // Add the resourcetype to the resource
3711 result = BindResourceTypeToResource(pointer, resourceTypeName);
3712 if (result != OC_STACK_OK)
3714 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3718 // Add the resourceinterface to the resource
3719 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3720 if (result != OC_STACK_OK)
3722 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3726 // If an entity handler has been passed, attach it to the newly created
3727 // resource. Otherwise, set the default entity handler.
3730 pointer->entityHandler = entityHandler;
3731 pointer->entityHandlerCallbackParam = callbackParam;
3735 pointer->entityHandler = defaultResourceEHandler;
3736 pointer->entityHandlerCallbackParam = NULL;
3739 // Initialize a pointer indicating child resources in case of collection
3740 pointer->rsrcChildResourcesHead = NULL;
3743 result = OC_STACK_OK;
3745 #ifdef WITH_PRESENCE
3746 if (presenceResource.handle)
3748 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3749 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3753 if (result != OC_STACK_OK)
3755 // Deep delete of resource and other dynamic elements that it contains
3756 deleteResource(pointer);
3761 OCStackResult OCBindResource(
3762 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3764 OCResource *resource = NULL;
3765 OCChildResource *tempChildResource = NULL;
3766 OCChildResource *newChildResource = NULL;
3768 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3770 // Validate parameters
3771 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3772 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3773 // Container cannot contain itself
3774 if (collectionHandle == resourceHandle)
3776 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3777 return OC_STACK_INVALID_PARAM;
3780 // Use the handle to find the resource in the resource linked list
3781 resource = findResource((OCResource *) collectionHandle);
3784 OIC_LOG(ERROR, TAG, "Collection handle not found");
3785 return OC_STACK_INVALID_PARAM;
3788 // Look for an open slot to add add the child resource.
3789 // If found, add it and return success
3791 tempChildResource = resource->rsrcChildResourcesHead;
3793 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3795 // TODO: what if one of child resource was deregistered without unbinding?
3796 tempChildResource = tempChildResource->next;
3799 // Do memory allocation for child resource
3800 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3801 if(!newChildResource)
3803 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3804 return OC_STACK_ERROR;
3807 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3808 newChildResource->next = NULL;
3810 if(!resource->rsrcChildResourcesHead)
3812 resource->rsrcChildResourcesHead = newChildResource;
3815 tempChildResource->next = newChildResource;
3818 OIC_LOG(INFO, TAG, "resource bound");
3820 #ifdef WITH_PRESENCE
3821 if (presenceResource.handle)
3823 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3824 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3825 OC_PRESENCE_TRIGGER_CHANGE);
3832 OCStackResult OCUnBindResource(
3833 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3835 OCResource *resource = NULL;
3836 OCChildResource *tempChildResource = NULL;
3837 OCChildResource *tempLastChildResource = NULL;
3839 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3841 // Validate parameters
3842 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3843 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3844 // Container cannot contain itself
3845 if (collectionHandle == resourceHandle)
3847 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3848 return OC_STACK_INVALID_PARAM;
3851 // Use the handle to find the resource in the resource linked list
3852 resource = findResource((OCResource *) collectionHandle);
3855 OIC_LOG(ERROR, TAG, "Collection handle not found");
3856 return OC_STACK_INVALID_PARAM;
3859 // Look for an open slot to add add the child resource.
3860 // If found, add it and return success
3861 if(!resource->rsrcChildResourcesHead)
3863 OIC_LOG(INFO, TAG, "resource not found in collection");
3865 // Unable to add resourceHandle, so return error
3866 return OC_STACK_ERROR;
3870 tempChildResource = resource->rsrcChildResourcesHead;
3872 while (tempChildResource)
3874 if(tempChildResource->rsrcResource == resourceHandle)
3876 // if resource going to be unbinded is the head one.
3877 if( tempChildResource == resource->rsrcChildResourcesHead )
3879 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3880 OICFree(resource->rsrcChildResourcesHead);
3881 resource->rsrcChildResourcesHead = temp;
3886 OCChildResource *temp = tempChildResource->next;
3887 OICFree(tempChildResource);
3888 if (tempLastChildResource)
3890 tempLastChildResource->next = temp;
3895 OIC_LOG(INFO, TAG, "resource unbound");
3897 // Send notification when resource is unbounded successfully.
3898 #ifdef WITH_PRESENCE
3899 if (presenceResource.handle)
3901 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3902 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3903 OC_PRESENCE_TRIGGER_CHANGE);
3906 tempChildResource = NULL;
3907 tempLastChildResource = NULL;
3913 tempLastChildResource = tempChildResource;
3914 tempChildResource = tempChildResource->next;
3917 OIC_LOG(INFO, TAG, "resource not found in collection");
3919 tempChildResource = NULL;
3920 tempLastChildResource = NULL;
3922 // Unable to add resourceHandle, so return error
3923 return OC_STACK_ERROR;
3926 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3928 if (!resourceItemName)
3932 // Per RFC 6690 only registered values must follow the first rule below.
3933 // At this point in time the only values registered begin with "core", and
3934 // all other values are specified as opaque strings where multiple values
3935 // are separated by a space.
3936 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3938 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3940 if (resourceItemName[index] != '.'
3941 && resourceItemName[index] != '-'
3942 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3943 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3951 for (size_t index = 0; resourceItemName[index]; ++index)
3953 if (resourceItemName[index] == ' '
3954 || resourceItemName[index] == '\t'
3955 || resourceItemName[index] == '\r'
3956 || resourceItemName[index] == '\n')
3966 OCStackResult BindResourceTypeToResource(OCResource* resource,
3967 const char *resourceTypeName)
3969 OCResourceType *pointer = NULL;
3971 OCStackResult result = OC_STACK_ERROR;
3973 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3975 if (!ValidateResourceTypeInterface(resourceTypeName))
3977 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3978 return OC_STACK_INVALID_PARAM;
3981 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3984 result = OC_STACK_NO_MEMORY;
3988 str = OICStrdup(resourceTypeName);
3991 result = OC_STACK_NO_MEMORY;
3994 pointer->resourcetypename = str;
3995 pointer->next = NULL;
3997 insertResourceType(resource, pointer);
3998 result = OC_STACK_OK;
4001 if (result != OC_STACK_OK)
4010 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
4011 const char *resourceInterfaceName)
4013 OCResourceInterface *pointer = NULL;
4015 OCStackResult result = OC_STACK_ERROR;
4017 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
4019 if (!ValidateResourceTypeInterface(resourceInterfaceName))
4021 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
4022 return OC_STACK_INVALID_PARAM;
4025 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
4027 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
4030 result = OC_STACK_NO_MEMORY;
4034 str = OICStrdup(resourceInterfaceName);
4037 result = OC_STACK_NO_MEMORY;
4040 pointer->name = str;
4042 // Bind the resourceinterface to the resource
4043 insertResourceInterface(resource, pointer);
4045 result = OC_STACK_OK;
4048 if (result != OC_STACK_OK)
4057 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
4058 const char *resourceTypeName)
4061 OCStackResult result = OC_STACK_ERROR;
4062 OCResource *resource = NULL;
4064 resource = findResource((OCResource *) handle);
4067 OIC_LOG(ERROR, TAG, "Resource not found");
4068 return OC_STACK_ERROR;
4071 result = BindResourceTypeToResource(resource, resourceTypeName);
4073 #ifdef WITH_PRESENCE
4074 if(presenceResource.handle)
4076 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4077 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4084 OCStackResult OCResetResourceTypes(OCResourceHandle handle,
4085 const char *newResourceType)
4087 OCStackResult result = OC_STACK_ERROR;
4088 OCResource *resource = NULL;
4090 resource = findResource((OCResource *) handle);
4093 OIC_LOG(ERROR, TAG, "Resource not found");
4094 return OC_STACK_ERROR;
4097 // Clear all bound resource types
4098 deleteResourceType(resource->rsrcType);
4099 resource->rsrcType = NULL;
4101 // Bind new resource type to resource
4102 result = BindResourceTypeToResource(resource, newResourceType);
4104 #ifdef WITH_PRESENCE
4105 if(presenceResource.handle)
4107 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4108 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4115 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
4116 const char *resourceInterfaceName)
4119 OCStackResult result = OC_STACK_ERROR;
4120 OCResource *resource = NULL;
4122 resource = findResource((OCResource *) handle);
4125 OIC_LOG(ERROR, TAG, "Resource not found");
4126 return OC_STACK_ERROR;
4129 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
4131 #ifdef WITH_PRESENCE
4132 if (presenceResource.handle)
4134 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4135 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4142 OCStackResult OCResetResourceInterfaces(OCResourceHandle handle,
4143 const char *newResourceInterface)
4145 OCStackResult result = OC_STACK_ERROR;
4146 OCResource *resource = NULL;
4148 resource = findResource((OCResource *) handle);
4151 OIC_LOG(ERROR, TAG, "Resource not found");
4152 return OC_STACK_ERROR;
4155 // Clear all bound interface
4156 deleteResourceInterface(resource->rsrcInterface);
4157 resource->rsrcInterface = NULL;
4159 // Bind new interface to resource
4160 result = BindResourceInterfaceToResource(resource, newResourceInterface);
4162 #ifdef WITH_PRESENCE
4163 if (presenceResource.handle)
4165 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4166 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4173 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
4175 OCResource *pointer = headResource;
4177 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
4181 *numResources = *numResources + 1;
4182 pointer = pointer->next;
4187 OCResourceHandle OCGetResourceHandle(uint8_t index)
4189 OCResource *pointer = headResource;
4191 for( uint8_t i = 0; i < index && pointer; ++i)
4193 pointer = pointer->next;
4195 return (OCResourceHandle) pointer;
4198 OCStackResult OCDeleteResource(OCResourceHandle handle)
4202 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4203 return OC_STACK_INVALID_PARAM;
4206 OCResource *resource = findResource((OCResource *) handle);
4207 if (resource == NULL)
4209 OIC_LOG(ERROR, TAG, "Resource not found");
4210 return OC_STACK_NO_RESOURCE;
4213 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4215 OIC_LOG(ERROR, TAG, "Error deleting resource");
4216 return OC_STACK_ERROR;
4222 const char *OCGetResourceUri(OCResourceHandle handle)
4224 OCResource *resource = NULL;
4226 resource = findResource((OCResource *) handle);
4229 return resource->uri;
4231 return (const char *) NULL;
4234 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4236 OCResource *resource = NULL;
4238 resource = findResource((OCResource *) handle);
4241 return resource->resourceProperties;
4243 return (OCResourceProperty)-1;
4246 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4247 uint8_t *numResourceTypes)
4249 OCResource *resource = NULL;
4250 OCResourceType *pointer = NULL;
4252 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4253 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4255 *numResourceTypes = 0;
4257 resource = findResource((OCResource *) handle);
4260 pointer = resource->rsrcType;
4263 *numResourceTypes = *numResourceTypes + 1;
4264 pointer = pointer->next;
4270 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4272 OCResourceType *resourceType = NULL;
4274 resourceType = findResourceTypeAtIndex(handle, index);
4277 return resourceType->resourcetypename;
4279 return (const char *) NULL;
4282 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4283 uint8_t *numResourceInterfaces)
4285 OCResourceInterface *pointer = NULL;
4286 OCResource *resource = NULL;
4288 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4289 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4291 *numResourceInterfaces = 0;
4292 resource = findResource((OCResource *) handle);
4295 pointer = resource->rsrcInterface;
4298 *numResourceInterfaces = *numResourceInterfaces + 1;
4299 pointer = pointer->next;
4305 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4307 OCResourceInterface *resourceInterface = NULL;
4309 resourceInterface = findResourceInterfaceAtIndex(handle, index);
4310 if (resourceInterface)
4312 return resourceInterface->name;
4314 return (const char *) NULL;
4317 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4320 OCResource *resource = NULL;
4321 OCChildResource *tempChildResource = NULL;
4324 resource = findResource((OCResource *) collectionHandle);
4330 tempChildResource = resource->rsrcChildResourcesHead;
4332 while(tempChildResource)
4336 return tempChildResource->rsrcResource;
4339 tempChildResource = tempChildResource->next;
4342 // In this case, the number of resource handles in the collection exceeds the index
4343 tempChildResource = NULL;
4347 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4348 OCEntityHandler entityHandler,
4349 void* callbackParam)
4351 OCResource *resource = NULL;
4353 // Validate parameters
4354 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4356 // Use the handle to find the resource in the resource linked list
4357 resource = findResource((OCResource *)handle);
4360 OIC_LOG(ERROR, TAG, "Resource not found");
4361 return OC_STACK_ERROR;
4365 resource->entityHandler = entityHandler;
4366 resource->entityHandlerCallbackParam = callbackParam;
4368 #ifdef WITH_PRESENCE
4369 if (presenceResource.handle)
4371 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4372 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4379 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4381 OCResource *resource = NULL;
4383 resource = findResource((OCResource *)handle);
4386 OIC_LOG(ERROR, TAG, "Resource not found");
4391 return resource->entityHandler;
4394 void incrementSequenceNumber(OCResource * resPtr)
4396 // Increment the sequence number
4397 resPtr->sequenceNum += 1;
4398 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4400 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4405 #ifdef WITH_PRESENCE
4406 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4407 OCPresenceTrigger trigger)
4409 OIC_LOG(INFO, TAG, "SendPresenceNotification");
4410 OCResource *resPtr = NULL;
4411 OCStackResult result = OC_STACK_ERROR;
4412 OCMethod method = OC_REST_PRESENCE;
4413 uint32_t maxAge = 0;
4414 resPtr = findResource((OCResource *) presenceResource.handle);
4417 return OC_STACK_NO_RESOURCE;
4420 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4422 maxAge = presenceResource.presenceTTL;
4424 result = SendAllObserverNotification(method, resPtr, maxAge,
4425 trigger, resourceType, OC_LOW_QOS);
4431 OCStackResult SendStopNotification()
4433 OIC_LOG(INFO, TAG, "SendStopNotification");
4434 OCResource *resPtr = NULL;
4435 OCStackResult result = OC_STACK_ERROR;
4436 OCMethod method = OC_REST_PRESENCE;
4437 resPtr = findResource((OCResource *) presenceResource.handle);
4440 return OC_STACK_NO_RESOURCE;
4443 // maxAge is 0. ResourceType is NULL.
4444 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4450 #endif // WITH_PRESENCE
4451 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4453 OCResource *resPtr = NULL;
4454 OCStackResult result = OC_STACK_ERROR;
4455 OCMethod method = OC_REST_NOMETHOD;
4456 uint32_t maxAge = 0;
4458 OIC_LOG(INFO, TAG, "Notifying all observers");
4459 #ifdef WITH_PRESENCE
4460 if(handle == presenceResource.handle)
4464 #endif // WITH_PRESENCE
4465 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4467 // Verify that the resource exists
4468 resPtr = findResource ((OCResource *) handle);
4471 return OC_STACK_NO_RESOURCE;
4475 //only increment in the case of regular observing (not presence)
4476 incrementSequenceNumber(resPtr);
4477 method = OC_REST_OBSERVE;
4478 maxAge = MAX_OBSERVE_AGE;
4479 #ifdef WITH_PRESENCE
4480 result = SendAllObserverNotification (method, resPtr, maxAge,
4481 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4483 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4490 OCNotifyListOfObservers (OCResourceHandle handle,
4491 OCObservationId *obsIdList,
4492 uint8_t numberOfIds,
4493 const OCRepPayload *payload,
4494 OCQualityOfService qos)
4496 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4498 OCResource *resPtr = NULL;
4499 //TODO: we should allow the server to define this
4500 uint32_t maxAge = MAX_OBSERVE_AGE;
4502 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4503 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4504 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4506 resPtr = findResource ((OCResource *) handle);
4507 if (NULL == resPtr || myStackMode == OC_CLIENT)
4509 return OC_STACK_NO_RESOURCE;
4513 incrementSequenceNumber(resPtr);
4515 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4516 payload, maxAge, qos));
4519 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4521 OIC_TRACE_BEGIN(%s:OCDoResponse, TAG);
4522 OCStackResult result = OC_STACK_ERROR;
4523 OCServerRequest *serverRequest = NULL;
4525 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4527 // Validate input parameters
4528 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4529 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4532 // Get pointer to request info
4533 serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
4536 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4537 result = serverRequest->ehResponseHandler(ehResponse);
4544 //#ifdef DIRECT_PAIRING
4545 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4547 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4548 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4550 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4554 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4557 const OCDPDev_t* OCGetDirectPairedDevices()
4559 return (const OCDPDev_t*)DPGetPairedDevices();
4562 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4563 OCDirectPairingCB resultCallback)
4565 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4566 if(NULL == peer || NULL == pinNumber)
4568 OIC_LOG(ERROR, TAG, "Invalid parameters");
4569 return OC_STACK_INVALID_PARAM;
4571 if (NULL == resultCallback)
4573 OIC_LOG(ERROR, TAG, "Invalid callback");
4574 return OC_STACK_INVALID_CALLBACK;
4577 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4578 pinNumber, (OCDirectPairingResultCB)resultCallback);
4580 //#endif // DIRECT_PAIRING
4582 //-----------------------------------------------------------------------------
4583 // Private internal function definitions
4584 //-----------------------------------------------------------------------------
4585 static OCDoHandle GenerateInvocationHandle()
4587 OCDoHandle handle = NULL;
4588 // Generate token here, it will be deleted when the transaction is deleted
4589 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4592 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4598 #ifdef WITH_PRESENCE
4599 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4600 OCResourceProperty resourceProperties, uint8_t enable)
4604 return OC_STACK_INVALID_PARAM;
4606 if (resourceProperties
4607 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4609 OIC_LOG(ERROR, TAG, "Invalid property");
4610 return OC_STACK_INVALID_PARAM;
4614 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4618 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4624 OCStackResult initResources()
4626 OCStackResult result = OC_STACK_OK;
4628 headResource = NULL;
4629 tailResource = NULL;
4630 // Init Virtual Resources
4631 #ifdef WITH_PRESENCE
4632 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4634 result = OCCreateResource(&presenceResource.handle,
4635 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4637 OC_RSRVD_PRESENCE_URI,
4641 //make resource inactive
4642 result = OCChangeResourceProperty(
4643 &(((OCResource *) presenceResource.handle)->resourceProperties),
4646 #ifndef WITH_ARDUINO
4647 if (result == OC_STACK_OK)
4649 result = SRMInitSecureResources();
4653 if(result == OC_STACK_OK)
4655 CreateResetProfile();
4656 result = OCCreateResource(&deviceResource,
4657 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4658 OC_RSRVD_INTERFACE_DEFAULT,
4659 OC_RSRVD_DEVICE_URI,
4663 if(result == OC_STACK_OK)
4665 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4666 OC_RSRVD_INTERFACE_READ);
4670 if(result == OC_STACK_OK)
4672 result = OCCreateResource(&platformResource,
4673 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4674 OC_RSRVD_INTERFACE_DEFAULT,
4675 OC_RSRVD_PLATFORM_URI,
4679 if(result == OC_STACK_OK)
4681 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4682 OC_RSRVD_INTERFACE_READ);
4689 void insertResource(OCResource *resource)
4693 headResource = resource;
4694 tailResource = resource;
4698 tailResource->next = resource;
4699 tailResource = resource;
4701 resource->next = NULL;
4704 OCResource *findResource(OCResource *resource)
4706 OCResource *pointer = headResource;
4710 if (pointer == resource)
4714 pointer = pointer->next;
4719 void deleteAllResources()
4721 OCResource *pointer = headResource;
4722 OCResource *temp = NULL;
4726 temp = pointer->next;
4727 #ifdef WITH_PRESENCE
4728 if (pointer != (OCResource *) presenceResource.handle)
4730 #endif // WITH_PRESENCE
4731 deleteResource(pointer);
4732 #ifdef WITH_PRESENCE
4734 #endif // WITH_PRESENCE
4737 memset(&platformResource, 0, sizeof(platformResource));
4738 memset(&deviceResource, 0, sizeof(deviceResource));
4740 memset(&brokerResource, 0, sizeof(brokerResource));
4743 SRMDeInitSecureResources();
4745 #ifdef WITH_PRESENCE
4746 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4747 // presence notification attributed to their deletion to be processed.
4748 deleteResource((OCResource *) presenceResource.handle);
4749 memset(&presenceResource, 0, sizeof(presenceResource));
4750 #endif // WITH_PRESENCE
4753 OCStackResult deleteResource(OCResource *resource)
4755 OCResource *prev = NULL;
4756 OCResource *temp = NULL;
4759 OIC_LOG(DEBUG,TAG,"resource is NULL");
4760 return OC_STACK_INVALID_PARAM;
4763 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4765 temp = headResource;
4768 if (temp == resource)
4770 // Invalidate all Resource Properties.
4771 resource->resourceProperties = (OCResourceProperty) 0;
4772 #ifdef WITH_PRESENCE
4773 if(resource != (OCResource *) presenceResource.handle)
4775 #endif // WITH_PRESENCE
4776 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4777 #ifdef WITH_PRESENCE
4780 if(presenceResource.handle)
4782 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4783 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4786 // Delete resource's all observers
4787 DeleteObserverUsingResource(resource);
4789 // Only resource in list.
4790 if (temp == headResource && temp == tailResource)
4792 headResource = NULL;
4793 tailResource = NULL;
4796 else if (temp == headResource)
4798 headResource = temp->next;
4801 else if (temp == tailResource && prev)
4803 tailResource = prev;
4804 tailResource->next = NULL;
4808 prev->next = temp->next;
4811 deleteResourceElements(temp);
4822 return OC_STACK_ERROR;
4825 void deleteResourceElements(OCResource *resource)
4834 OICFree(resource->uri);
4835 resource->uri = NULL;
4837 if (resource->rsrcType)
4839 deleteResourceType(resource->rsrcType);
4840 resource->rsrcType = NULL;
4842 if (resource->rsrcInterface)
4844 deleteResourceInterface(resource->rsrcInterface);
4845 resource->rsrcInterface = NULL;
4847 if (resource->rsrcChildResourcesHead)
4849 unbindChildResources(resource->rsrcChildResourcesHead);
4850 resource->rsrcChildResourcesHead = NULL;
4852 if (resource->rsrcAttributes)
4854 OCDeleteResourceAttributes(resource->rsrcAttributes);
4855 resource->rsrcAttributes = NULL;
4858 resource->entityHandler = NULL;
4862 void deleteResourceType(OCResourceType *resourceType)
4864 OCResourceType *next = NULL;
4866 for (OCResourceType *pointer = resourceType; pointer; pointer = next)
4868 next = pointer->next ? pointer->next : NULL;
4869 if (pointer->resourcetypename)
4871 OICFree(pointer->resourcetypename);
4872 pointer->resourcetypename = NULL;
4878 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4880 OCResourceInterface *next = NULL;
4881 for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
4883 next = pointer->next ? pointer->next : NULL;
4886 OICFree(pointer->name);
4887 pointer->name = NULL;
4893 void unbindChildResources(OCChildResource *head)
4895 OCChildResource *next = NULL;
4896 for (OCChildResource *current = head; current; current = next)
4898 next = current->next;
4903 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
4905 OCAttribute *next = NULL;
4906 for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
4908 next = pointer->next ? pointer->next : NULL;
4909 if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
4911 OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
4912 pointer->attrValue = NULL;
4914 else if (pointer->attrValue)
4916 OICFree(pointer->attrValue);
4917 pointer->attrValue = NULL;
4919 if (pointer->attrName)
4921 OICFree(pointer->attrName);
4922 pointer->attrName = NULL;
4928 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4930 OCResourceType *pointer = NULL;
4931 OCResourceType *previous = NULL;
4932 if (!resource || !resourceType)
4936 // resource type list is empty.
4937 else if (!resource->rsrcType)
4939 resource->rsrcType = resourceType;
4943 pointer = resource->rsrcType;
4947 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4949 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4950 OICFree(resourceType->resourcetypename);
4951 OICFree(resourceType);
4955 pointer = pointer->next;
4960 previous->next = resourceType;
4963 resourceType->next = NULL;
4965 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4968 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4970 OCResource *resource = NULL;
4971 OCResourceType *pointer = NULL;
4973 // Find the specified resource
4974 resource = findResource((OCResource *) handle);
4980 // Make sure a resource has a resourcetype
4981 if (!resource->rsrcType)
4986 // Iterate through the list
4987 pointer = resource->rsrcType;
4988 for(uint8_t i = 0; i< index && pointer; ++i)
4990 pointer = pointer->next;
4995 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4997 if(resourceTypeList && resourceTypeName)
4999 OCResourceType * rtPointer = resourceTypeList;
5000 while(resourceTypeName && rtPointer)
5002 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
5003 if(rtPointer->resourcetypename &&
5004 strcmp(resourceTypeName, (const char *)
5005 (rtPointer->resourcetypename)) == 0)
5009 rtPointer = rtPointer->next;
5017 * Insert a new interface into interface linked list only if not already present.
5018 * If alredy present, 2nd arg is free'd.
5019 * Default interface will always be first if present.
5021 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
5023 OCResourceInterface *pointer = NULL;
5024 OCResourceInterface *previous = NULL;
5026 newInterface->next = NULL;
5028 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
5030 if (!*firstInterface)
5032 // If first interface is not oic.if.baseline, by default add it as first interface type.
5033 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
5035 *firstInterface = newInterface;
5039 OCStackResult result = BindResourceInterfaceToResource(resource,
5040 OC_RSRVD_INTERFACE_DEFAULT);
5041 if (result != OC_STACK_OK)
5043 OICFree(newInterface->name);
5044 OICFree(newInterface);
5047 if (*firstInterface)
5049 (*firstInterface)->next = newInterface;
5053 // If once add oic.if.baseline, later too below code take care of freeing memory.
5054 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5056 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5058 OICFree(newInterface->name);
5059 OICFree(newInterface);
5062 // This code will not hit anymore, keeping
5065 newInterface->next = *firstInterface;
5066 *firstInterface = newInterface;
5071 pointer = *firstInterface;
5074 if (strcmp(newInterface->name, pointer->name) == 0)
5076 OICFree(newInterface->name);
5077 OICFree(newInterface);
5081 pointer = pointer->next;
5086 previous->next = newInterface;
5091 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
5094 OCResource *resource = NULL;
5095 OCResourceInterface *pointer = NULL;
5097 // Find the specified resource
5098 resource = findResource((OCResource *) handle);
5104 // Make sure a resource has a resourceinterface
5105 if (!resource->rsrcInterface)
5110 // Iterate through the list
5111 pointer = resource->rsrcInterface;
5113 for (uint8_t i = 0; i < index && pointer; ++i)
5115 pointer = pointer->next;
5121 * This function splits the uri using the '?' delimiter.
5122 * "uriWithoutQuery" is the block of characters between the beginning
5123 * till the delimiter or '\0' which ever comes first.
5124 * "query" is whatever is to the right of the delimiter if present.
5125 * No delimiter sets the query to NULL.
5126 * If either are present, they will be malloc'ed into the params 2, 3.
5127 * The first param, *uri is left untouched.
5129 * NOTE: This function does not account for whitespace at the end of the uri NOR
5130 * malformed uri's with '??'. Whitespace at the end will be assumed to be
5131 * part of the query.
5133 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
5137 return OC_STACK_INVALID_URI;
5139 if(!query || !uriWithoutQuery)
5141 return OC_STACK_INVALID_PARAM;
5145 *uriWithoutQuery = NULL;
5147 size_t uriWithoutQueryLen = 0;
5148 size_t queryLen = 0;
5149 size_t uriLen = strlen(uri);
5151 char *pointerToDelimiter = strstr(uri, "?");
5153 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
5154 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
5156 if (uriWithoutQueryLen)
5158 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
5159 if (!*uriWithoutQuery)
5163 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
5167 *query = (char *) OICCalloc(queryLen + 1, 1);
5170 OICFree(*uriWithoutQuery);
5171 *uriWithoutQuery = NULL;
5174 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5180 return OC_STACK_NO_MEMORY;
5183 const char* OCGetServerInstanceIDString(void)
5185 static char sidStr[UUID_STRING_SIZE];
5187 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5189 OIC_LOG(FATAL, TAG, "GetDoxmDeviceID failed!");
5193 if (OCConvertUuidToString(sid.id, sidStr) != RAND_UUID_OK)
5195 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5202 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5204 OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5205 CAResult_t retResult = CA_STATUS_FAILED;
5206 CAResult_t caResult = CA_STATUS_OK;
5208 CATransportAdapter_t connTypes[] = {
5210 CA_ADAPTER_RFCOMM_BTEDR,
5211 CA_ADAPTER_GATT_BTLE,
5214 ,CA_ADAPTER_REMOTE_ACCESS
5221 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5223 for(int i = 0; i < numConnTypes; i++)
5225 // If CA status is not initialized, CASelectNetwork() will not be called.
5226 if (caResult != CA_STATUS_NOT_INITIALIZED)
5228 if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5230 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5231 caResult = CASelectNetwork(connTypes[i]);
5232 if (caResult == CA_STATUS_OK)
5234 retResult = CA_STATUS_OK;
5239 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5244 if (retResult != CA_STATUS_OK)
5246 return caResult; // Returns error of appropriate transport that failed fatally.
5252 OCStackResult CAResultToOCResult(CAResult_t caResult)
5258 case CA_STATUS_INVALID_PARAM:
5259 return OC_STACK_INVALID_PARAM;
5260 case CA_ADAPTER_NOT_ENABLED:
5261 return OC_STACK_ADAPTER_NOT_ENABLED;
5262 case CA_SERVER_STARTED_ALREADY:
5264 case CA_SERVER_NOT_STARTED:
5265 return OC_STACK_ERROR;
5266 case CA_DESTINATION_NOT_REACHABLE:
5267 return OC_STACK_COMM_ERROR;
5268 case CA_SOCKET_OPERATION_FAILED:
5269 return OC_STACK_COMM_ERROR;
5270 case CA_SEND_FAILED:
5271 return OC_STACK_COMM_ERROR;
5272 case CA_RECEIVE_FAILED:
5273 return OC_STACK_COMM_ERROR;
5274 case CA_MEMORY_ALLOC_FAILED:
5275 return OC_STACK_NO_MEMORY;
5276 case CA_REQUEST_TIMEOUT:
5277 return OC_STACK_TIMEOUT;
5278 case CA_DESTINATION_DISCONNECTED:
5279 return OC_STACK_COMM_ERROR;
5280 case CA_STATUS_FAILED:
5281 return OC_STACK_ERROR;
5282 case CA_NOT_SUPPORTED:
5283 return OC_STACK_NOTIMPL;
5285 return OC_STACK_ERROR;
5289 bool OCResultToSuccess(OCStackResult ocResult)
5294 case OC_STACK_RESOURCE_CREATED:
5295 case OC_STACK_RESOURCE_DELETED:
5296 case OC_STACK_CONTINUE:
5297 case OC_STACK_RESOURCE_CHANGED:
5298 case OC_STACK_SLOW_RESOURCE:
5306 OCStackResult OCSetProxyURI(const char *uri)
5308 return CAResultToOCResult(CASetProxyUri(uri));
5312 #if defined(RD_CLIENT) || defined(RD_SERVER)
5313 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5315 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5317 OCResource *resource = NULL;
5319 resource = findResource((OCResource *) handle);
5322 OIC_LOG(ERROR, TAG, "Resource not found");
5323 return OC_STACK_ERROR;
5326 resource->ins = ins;
5332 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5333 const OCClientResponse *response)
5335 // Validate input parameters
5336 VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5337 VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5339 char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5342 return OC_STACK_NO_MEMORY;
5344 strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5346 if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5348 OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5350 char rdPubUri[MAX_URI_LENGTH] = { 0 };
5351 snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5352 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5354 if (strcmp(rdPubUri, targetUri) == 0)
5356 // Update resource unique id in stack.
5359 if (response->payload)
5361 OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5362 OCRepPayload **links = NULL;
5363 size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5364 if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5365 &links, dimensions))
5368 for (; i < dimensions[0]; i++)
5371 if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5373 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5375 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5377 OCBindResourceInsToResource(handle, ins);
5386 size_t count = calcDimTotal(dimensions);
5387 for (size_t k = 0; k < count; k++)
5389 OCRepPayloadDestroy(links[k]);
5397 else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5399 OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5401 uint8_t numResources = 0;
5402 OCGetNumberOfResources(&numResources);
5404 char *ins = strstr(targetUri, OC_RSRVD_INS);
5407 for (uint8_t i = 0; i < numResources; i++)
5409 OCResourceHandle resHandle = OCGetResourceHandle(i);
5412 OCBindResourceInsToResource(resHandle, 0);
5418 const char *token = "&";
5419 char *iterTokenPtr = NULL;
5420 char *start = strtok_r(targetUri, token, &iterTokenPtr);
5422 while (start != NULL)
5424 char *query = start;
5425 query = strstr(query, OC_RSRVD_INS);
5428 int64_t queryIns = atoi(query + 4);
5429 for (uint8_t i = 0; i < numResources; i++)
5431 OCResourceHandle resHandle = OCGetResourceHandle(i);
5435 OCGetResourceIns(resHandle, &resIns);
5436 if (queryIns && queryIns == resIns)
5438 OCBindResourceInsToResource(resHandle, 0);
5444 start = strtok_r(NULL, token, &iterTokenPtr);
5453 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5457 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5461 OCResource *pointer = headResource;
5465 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5467 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5470 pointer = pointer->next;
5475 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t *ins)
5477 OCResource *resource = NULL;
5479 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5480 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5482 resource = findResource((OCResource *) handle);
5485 *ins = resource->ins;
5488 return OC_STACK_ERROR;
5492 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5493 const void* optionData, size_t optionDataLength)
5497 OIC_LOG (INFO, TAG, "Header options are NULL");
5498 return OC_STACK_INVALID_PARAM;
5503 OIC_LOG (INFO, TAG, "optionData are NULL");
5504 return OC_STACK_INVALID_PARAM;
5509 OIC_LOG (INFO, TAG, "numOptions is NULL");
5510 return OC_STACK_INVALID_PARAM;
5513 if (*numOptions >= MAX_HEADER_OPTIONS)
5515 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5516 return OC_STACK_NO_MEMORY;
5519 ocHdrOpt += *numOptions;
5520 ocHdrOpt->protocolID = OC_COAP_ID;
5521 ocHdrOpt->optionID = optionID;
5522 ocHdrOpt->optionLength =
5523 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
5524 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5525 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5531 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5532 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5534 if (!ocHdrOpt || !numOptions)
5536 OIC_LOG (INFO, TAG, "No options present");
5542 OIC_LOG (INFO, TAG, "optionData are NULL");
5543 return OC_STACK_INVALID_PARAM;
5546 if (!receivedDataLength)
5548 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5549 return OC_STACK_INVALID_PARAM;
5552 for (uint8_t i = 0; i < numOptions; i++)
5554 if (ocHdrOpt[i].optionID == optionID)
5556 if (optionDataLength >= ocHdrOpt->optionLength)
5558 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5559 *receivedDataLength = ocHdrOpt->optionLength;
5564 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5565 return OC_STACK_ERROR;
5572 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5574 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5580 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5582 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5585 * If the client observes one or more resources over a reliable connection,
5586 * then the CoAP server (or intermediary in the role of the CoAP server)
5587 * MUST remove all entries associated with the client endpoint from the lists
5588 * of observers when the connection is either closed or times out.
5592 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5593 CopyEndpointToDevAddr(info, &devAddr);
5595 // remove observer list with remote device address.
5596 DeleteObserverUsingDevAddr(&devAddr);
5600 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5603 OCStackResult ret = OC_STACK_ERROR;
5605 ret = GetDoxmDeviceID(&oicUuid);
5606 if (OC_STACK_OK == ret)
5608 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5612 OIC_LOG(ERROR, TAG, "Device ID Get error");
5617 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5620 OCStackResult ret = OC_STACK_ERROR;
5622 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5623 for (int i = 0; i < UUID_LENGTH; i++)
5625 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5627 ret = SetDoxmDeviceID(&oicUuid);
5631 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5633 bool isDeviceOwned = true;
5634 OCStackResult ret = OC_STACK_ERROR;
5636 ret = GetDoxmIsOwned(&isDeviceOwned);
5637 if (OC_STACK_OK == ret)
5639 *isOwned = isDeviceOwned;
5643 OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5648 OCStackResult OCGetDeviceOperationalState(bool* isOp)
5652 *isOp = GetPstatIsop();
5656 return OC_STACK_ERROR;
5659 void OCClearCallBackList()
5661 DeleteClientCBList();
5664 void OCClearObserverlist()
5666 DeleteObserverList();
5669 int OCEncrypt(const unsigned char *pt, size_t pt_len,
5670 unsigned char **ct, size_t *ct_len)
5672 #ifndef __SECURE_PSI__
5673 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5676 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5678 return psiEncrypt(pt, pt_len, ct, ct_len);
5679 #endif // __SECURE_PSI__
5682 int OCDecrypt(const unsigned char *ct, size_t ct_len,
5683 unsigned char **pt, size_t *pt_len)
5685 #ifndef __SECURE_PSI__
5686 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5689 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5691 return psiDecrypt(ct, ct_len, pt, pt_len);
5692 #endif // __SECURE_PSI__
5695 OCStackResult OCSetKey(const unsigned char* key)
5697 #ifndef __SECURE_PSI__
5698 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5701 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5703 return psiSetKey(key);
5704 #endif // __SECURE_PSI__
5707 OCStackResult OCGetKey(unsigned char* key)
5709 #ifndef __SECURE_PSI__
5710 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5713 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5715 return psiGetKey(key);
5716 #endif // __SECURE_PSI__
5719 OCStackResult OCSetSecurePSI(const unsigned char *key, const OCPersistentStorage *psPlain,
5720 const OCPersistentStorage *psEnc, const OCPersistentStorage *psRescue)
5722 #ifndef __SECURE_PSI__
5723 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5726 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5728 return setSecurePSI(key, psPlain, psEnc, psRescue);
5729 #endif // __SECURE_PSI__
5732 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5733 static void OtmEventHandler(const char *addr, uint16_t port, const char *uuid, int event)
5735 if (g_otmEventHandler.cb)
5737 g_otmEventHandler.cb(g_otmEventHandler.ctx, addr, port, uuid, event);
5742 * It is already declared in srmutility.h.
5743 * We can't include the header file, because of "redefined VERIFY_NON_NULL"
5745 typedef void (*OicSecOtmEventHandler_t)(const char* addr, uint16_t port,
5746 const char* uuid, int event);
5747 void SetOtmEventHandler(OicSecOtmEventHandler_t otmEventHandler);
5750 OCStackResult OCSetOtmEventHandler(void *ctx, OCOtmEventHandler cb)
5752 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5753 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5755 g_otmEventHandler.cb = cb;
5756 g_otmEventHandler.ctx = ctx;
5758 if (g_otmEventHandler.cb)
5760 OIC_LOG(DEBUG, TAG, "SET OCOtmEventHandler");
5761 SetOtmEventHandler(OtmEventHandler);
5765 OIC_LOG(DEBUG, TAG, "UNSET OCOtmEventHandler");
5766 SetOtmEventHandler(NULL);
5769 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);