1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //-----------------------------------------------------------------------------
24 //-----------------------------------------------------------------------------
26 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
27 // causes header files to expose definitions
28 // corresponding to the POSIX.1-2001 base
29 // specification (excluding the XSI extension).
30 // For POSIX.1-2001 base specification,
31 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
32 #define _POSIX_C_SOURCE 200112L
33 #ifndef __STDC_FORMAT_MACROS
34 #define __STDC_FORMAT_MACROS
36 #ifndef __STDC_LIMIT_MACROS
37 #define __STDC_LIMIT_MACROS
39 #include "iotivity_config.h"
45 #include "ocstackinternal.h"
46 #include "ocresourcehandler.h"
47 #include "occlientcb.h"
48 #include "ocobserve.h"
50 #include "oic_malloc.h"
51 #include "oic_string.h"
54 #include "ocserverrequest.h"
55 #include "secureresourcemanager.h"
56 #include "psinterface.h"
58 #include "doxmresource.h"
60 #include "cainterface.h"
61 #include "ocpayload.h"
62 #include "ocpayloadcbor.h"
63 #include "cautilinterface.h"
64 #include "camessagehandler.h"
66 #include "pstatresource.h"
67 #include "srmutility.h"
69 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
70 #include "routingutility.h"
71 #ifdef ROUTING_GATEWAY
72 #include "routingmanager.h"
77 #include "oickeepaliveinternal.h"
80 //#ifdef DIRECT_PAIRING
81 #include "directpairing.h"
84 #ifdef HAVE_ARDUINO_TIME_H
87 #ifdef HAVE_SYS_TIME_H
90 #include <coap/coap.h>
92 #ifdef HAVE_ARPA_INET_H
93 #include <arpa/inet.h>
97 #define UINT32_MAX (0xFFFFFFFFUL)
100 //-----------------------------------------------------------------------------
102 //-----------------------------------------------------------------------------
105 OC_STACK_UNINITIALIZED = 0,
106 OC_STACK_INITIALIZED,
107 OC_STACK_UNINIT_IN_PROGRESS
113 OC_PRESENCE_UNINITIALIZED = 0,
114 OC_PRESENCE_INITIALIZED
118 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
121 OCOtmEventHandler cb;
123 } OCOtmEventHandler_t;
126 //-----------------------------------------------------------------------------
128 //-----------------------------------------------------------------------------
129 static OCStackState stackState = OC_STACK_UNINITIALIZED;
131 OCResource *headResource = NULL;
132 static OCResource *tailResource = NULL;
133 static OCResourceHandle platformResource = {0};
134 static OCResourceHandle deviceResource = {0};
136 static OCResourceHandle brokerResource = {0};
140 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
141 static PresenceResource presenceResource = {0};
142 static uint8_t PresenceTimeOutSize = 0;
143 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
146 static OCMode myStackMode;
148 //TODO: revisit this design
149 static bool gRASetInfo = false;
151 OCDeviceEntityHandler defaultDeviceHandler;
152 void* defaultDeviceHandlerCallbackParameter = NULL;
153 static const char COAP_TCP_SCHEME[] = "coap+tcp:";
154 static const char COAPS_TCP_SCHEME[] = "coaps+tcp:";
155 static const char CORESPEC[] = "core";
157 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
158 static OCOtmEventHandler_t g_otmEventHandler = {NULL, NULL};
161 #ifdef WITH_PROCESS_EVENT
162 static oc_event g_ocProcessEvent = NULL;
163 #endif // WITH_PROCESS_EVENT
165 //-----------------------------------------------------------------------------
167 //-----------------------------------------------------------------------------
168 #define TAG "OIC_RI_STACK"
169 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
170 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
171 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
172 TAG, #arg " is NULL"); return (retVal); } }
173 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
174 TAG, #arg " is NULL"); return; } }
175 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
178 //TODO: we should allow the server to define this
179 #define MAX_OBSERVE_AGE (0x2FFFFUL)
181 #define MILLISECONDS_PER_SECOND (1000)
183 //-----------------------------------------------------------------------------
184 // Private internal function prototypes
185 //-----------------------------------------------------------------------------
188 * Generate handle of OCDoResource invocation for callback management.
190 * @return Generated OCDoResource handle.
192 static OCDoHandle GenerateInvocationHandle();
195 * Initialize resource data structures, variables, etc.
197 * @return ::OC_STACK_OK on success, some other value upon failure.
199 static OCStackResult initResources();
202 * Add a resource to the end of the linked list of resources.
204 * @param resource Resource to be added
206 static void insertResource(OCResource *resource);
209 * Find a resource in the linked list of resources.
211 * @param resource Resource to be found.
212 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
215 static OCResource *findResource(OCResource *resource);
218 * Insert a resource type into a resource's resource type linked list.
219 * If resource type already exists, it will not be inserted and the
220 * resourceType will be free'd.
221 * resourceType->next should be null to avoid memory leaks.
222 * Function returns silently for null args.
224 * @param resource Resource where resource type is to be inserted.
225 * @param resourceType Resource type to be inserted.
227 static void insertResourceType(OCResource *resource,
228 OCResourceType *resourceType);
231 * Get a resource type at the specified index within a resource.
233 * @param handle Handle of resource.
234 * @param index Index of resource type.
236 * @return Pointer to resource type if found, NULL otherwise.
238 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
242 * Insert a resource interface into a resource's resource interface linked list.
243 * If resource interface already exists, it will not be inserted and the
244 * resourceInterface will be free'd.
245 * resourceInterface->next should be null to avoid memory leaks.
247 * @param resource Resource where resource interface is to be inserted.
248 * @param resourceInterface Resource interface to be inserted.
250 static void insertResourceInterface(OCResource *resource,
251 OCResourceInterface *resourceInterface);
254 * Get a resource interface at the specified index within a resource.
256 * @param handle Handle of resource.
257 * @param index Index of resource interface.
259 * @return Pointer to resource interface if found, NULL otherwise.
261 static OCResourceInterface *findResourceInterfaceAtIndex(
262 OCResourceHandle handle, uint8_t index);
265 * Delete all of the dynamically allocated elements that were created for the resource type.
267 * @param resourceType Specified resource type.
269 static void deleteResourceType(OCResourceType *resourceType);
272 * Delete all of the dynamically allocated elements that were created for the resource interface.
274 * @param resourceInterface Specified resource interface.
276 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
279 * Unbind all child resources.
281 * @param resourceChild Specified binded resource head is deleted from parent.
283 static void unbindChildResources(OCChildResource *resourceChild);
286 * Delete all of the dynamically allocated elements that were created for the resource.
288 * @param resource Specified resource.
290 static void deleteResourceElements(OCResource *resource);
293 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
296 * @param handle Handle of resource to be deleted.
298 * @return ::OC_STACK_OK on success, some other value upon failure.
300 static OCStackResult deleteResource(OCResource *resource);
303 * Delete all of the resources in the resource list.
305 static void deleteAllResources();
308 * Increment resource sequence number. Handles rollover.
310 * @param resPtr Pointer to resource.
312 static void incrementSequenceNumber(OCResource * resPtr);
315 * Attempts to initialize every network interface that the CA Layer might have compiled in.
317 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
318 * return something other than @ref CA_STATUS_OK, then this function fails.
319 * @param transportType OCTransportAdapter value to select.
320 * @return ::CA_STATUS_OK on success, some other value upon failure.
322 static CAResult_t OCSelectNetwork(OCTransportAdapter transportType);
325 * Convert CAResponseResult_t to OCStackResult.
327 * @param caCode CAResponseResult_t code.
328 * @return ::OC_STACK_OK on success, some other value upon failure.
330 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
333 * Convert OCTransportFlags_t to CATransportModifiers_t.
335 * @param ocConType OCTransportFlags_t input.
336 * @return CATransportFlags
338 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
341 * Convert CATransportFlags_t to OCTransportModifiers_t.
343 * @param caConType CATransportFlags_t input.
344 * @return OCTransportFlags
346 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
349 * Handle response from presence request.
351 * @param endPoint CA remote endpoint.
352 * @param responseInfo CA response info.
353 * @return ::OC_STACK_OK on success, some other value upon failure.
355 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
356 const CAResponseInfo_t *responseInfo);
359 * This function will be called back by CA layer when a response is received.
361 * @param endPoint CA remote endpoint.
362 * @param responseInfo CA response info.
364 static void HandleCAResponses(const CAEndpoint_t* endPoint,
365 const CAResponseInfo_t* responseInfo);
368 * This function will be called back by CA layer when a request is received.
370 * @param endPoint CA remote endpoint.
371 * @param requestInfo CA request info.
373 static void HandleCARequests(const CAEndpoint_t* endPoint,
374 const CARequestInfo_t* requestInfo);
377 * Extract query from a URI.
379 * @param uri Full URI with query.
380 * @param query Pointer to string that will contain query.
381 * @param newURI Pointer to string that will contain URI.
382 * @return ::OC_STACK_OK on success, some other value upon failure.
384 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
387 * Finds a resource type in an OCResourceType link-list.
389 * @param resourceTypeList The link-list to be searched through.
390 * @param resourceTypeName The key to search for.
392 * @return Resource type that matches the key (ie. resourceTypeName) or
393 * NULL if there is either an invalid parameter or this function was unable to find the key.
395 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
396 const char * resourceTypeName);
400 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
401 * TTL will be set to maxAge.
403 * @param cbNode Callback Node for which presence ttl is to be reset.
404 * @param maxAge New value of ttl in seconds.
406 * @return ::OC_STACK_OK on success, some other value upon failure.
408 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
412 * Ensure the accept header option is set appropriatly before sending the requests and routing
413 * header option is updated with destination.
415 * @param object CA remote endpoint.
416 * @param requestInfo CA request info.
418 * @return ::OC_STACK_OK on success, some other value upon failure.
420 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
423 * default adapter state change callback method
425 * @param adapter CA network adapter type.
426 * @param enabled current adapter state.
428 static void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled);
431 * default connection state change callback method
433 * @param info CAEndpoint which has address, port and etc.
434 * @param isConnected current connection state.
436 static void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected);
438 //-----------------------------------------------------------------------------
439 // Internal functions
440 //-----------------------------------------------------------------------------
442 bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
444 if (!options || 0 == numOptions)
446 OIC_LOG (INFO, TAG, "No options present");
450 for (uint8_t i = 0; i < numOptions; i++)
452 if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
454 OIC_LOG(DEBUG, TAG, "Proxy URI is present");
461 uint32_t GetTicks(uint32_t milliSeconds)
466 // Guard against overflow of uint32_t
467 if (milliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
468 COAP_TICKS_PER_SECOND)
470 return now + (milliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
478 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
480 VERIFY_NON_NULL_NR(in, FATAL);
481 VERIFY_NON_NULL_NR(out, FATAL);
483 out->adapter = (OCTransportAdapter)in->adapter;
484 out->flags = CAToOCTransportFlags(in->flags);
485 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
486 out->port = in->port;
487 out->ifindex = in->ifindex;
488 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
489 /* This assert is to prevent accidental mismatch between address size macros defined in
490 * RI and CA and cause crash here. */
491 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
492 "Address size mismatch between RI and CA");
493 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
497 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
499 VERIFY_NON_NULL_NR(in, FATAL);
500 VERIFY_NON_NULL_NR(out, FATAL);
502 out->adapter = (CATransportAdapter_t)in->adapter;
503 out->flags = OCToCATransportFlags(in->flags);
504 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
505 OICStrcpy(out->remoteId, sizeof(out->remoteId), in->remoteId);
506 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
507 /* This assert is to prevent accidental mismatch between address size macros defined in
508 * RI and CA and cause crash here. */
509 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
510 "Address size mismatch between RI and CA");
511 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
513 out->port = in->port;
514 out->ifindex = in->ifindex;
517 void FixUpClientResponse(OCClientResponse *cr)
519 VERIFY_NON_NULL_NR(cr, FATAL);
521 cr->addr = &cr->devAddr;
522 cr->connType = (OCConnectivityType)
523 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
526 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
528 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
529 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
530 OIC_TRACE_BEGIN(%s:OCSendRequest, TAG);
532 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
533 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
534 if (OC_STACK_OK != rmResult)
536 OIC_LOG(ERROR, TAG, "Add destination option failed");
542 // OC stack prefer CBOR encoded payloads.
543 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
544 CAResult_t result = CASendRequest(object, requestInfo);
545 if(CA_STATUS_OK != result)
547 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
549 return CAResultToOCResult(result);
555 //-----------------------------------------------------------------------------
556 // Internal API function
557 //-----------------------------------------------------------------------------
559 // This internal function is called to update the stack with the status of
560 // observers and communication failures
561 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
563 OCStackResult result = OC_STACK_ERROR;
564 ResourceObserver * observer = NULL;
565 OCEntityHandlerRequest ehRequest = {0};
569 case OC_OBSERVER_NOT_INTERESTED:
570 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
571 observer = GetObserverUsingToken(token, tokenLength);
574 result = FormOCEntityHandlerRequest(&ehRequest,
578 (OCResourceHandle)NULL,
579 NULL, PAYLOAD_TYPE_REPRESENTATION,
581 OC_OBSERVE_DEREGISTER,
584 if (result != OC_STACK_OK)
586 FreeObserver(observer);
590 if (observer->resource && observer->resource->entityHandler)
592 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
593 observer->resource->entityHandlerCallbackParam);
596 FreeObserver(observer);
599 result = DeleteObserverUsingToken(token, tokenLength);
600 if (result == OC_STACK_OK)
602 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
606 result = OC_STACK_OK;
607 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
611 case OC_OBSERVER_STILL_INTERESTED:
612 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
613 observer = GetObserverUsingToken(token, tokenLength);
616 observer->forceHighQos = 0;
617 observer->failedCommCount = 0;
618 result = OC_STACK_OK;
619 FreeObserver(observer);
623 result = OC_STACK_OBSERVER_NOT_FOUND;
627 case OC_OBSERVER_FAILED_COMM:
628 OIC_LOG(DEBUG, TAG, "observer is unreachable");
629 observer = GetObserverUsingToken (token, tokenLength);
632 if (observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
634 result = FormOCEntityHandlerRequest(&ehRequest,
638 (OCResourceHandle)NULL,
639 NULL, PAYLOAD_TYPE_REPRESENTATION,
641 OC_OBSERVE_DEREGISTER,
644 if (result != OC_STACK_OK)
646 FreeObserver(observer);
647 return OC_STACK_ERROR;
650 if (observer->resource && observer->resource->entityHandler)
652 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
653 observer->resource->entityHandlerCallbackParam);
656 result = DeleteObserverUsingToken(token, tokenLength);
657 if (result == OC_STACK_OK)
659 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
663 result = OC_STACK_OK;
664 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
669 observer->failedCommCount++;
670 observer->forceHighQos = 1;
671 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",
672 observer->failedCommCount);
673 result = OC_STACK_CONTINUE;
676 FreeObserver(observer);
680 OIC_LOG(ERROR, TAG, "Unknown status");
681 result = OC_STACK_ERROR;
687 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
689 OCStackResult ret = OC_STACK_ERROR;
693 ret = OC_STACK_RESOURCE_CREATED;
696 ret = OC_STACK_RESOURCE_DELETED;
699 ret = OC_STACK_RESOURCE_CHANGED;
706 ret = OC_STACK_INVALID_QUERY;
708 case CA_UNAUTHORIZED_REQ:
709 ret = OC_STACK_UNAUTHORIZED_REQ;
712 ret = OC_STACK_INVALID_OPTION;
715 ret = OC_STACK_NO_RESOURCE;
717 case CA_REQUEST_ENTITY_TOO_LARGE:
718 ret = OC_STACK_TOO_LARGE_REQ;
720 case CA_METHOD_NOT_ALLOWED:
721 ret = OC_STACK_METHOD_NOT_ALLOWED;
723 case CA_NOT_ACCEPTABLE:
724 ret = OC_STACK_NOT_ACCEPTABLE;
726 case CA_FORBIDDEN_REQ:
727 ret = OC_STACK_FORBIDDEN_REQ;
729 case CA_TOO_MANY_REQUESTS:
730 ret = OC_STACK_TOO_MANY_REQUESTS;
732 case CA_INTERNAL_SERVER_ERROR:
733 ret = OC_STACK_INTERNAL_SERVER_ERROR;
735 case CA_NOT_IMPLEMENTED:
736 ret = OC_STACK_NOT_IMPLEMENTED;
739 ret = OC_STACK_BAD_GATEWAY;
741 case CA_SERVICE_UNAVAILABLE:
742 ret = OC_STACK_SERVICE_UNAVAILABLE;
744 case CA_RETRANSMIT_TIMEOUT:
745 ret = OC_STACK_GATEWAY_TIMEOUT;
747 case CA_PROXY_NOT_SUPPORTED:
748 ret = OC_STACK_PROXY_NOT_SUPPORTED;
756 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
758 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
767 // This Response Code is like HTTP 204 "No Content" but only used in
768 // response to POST and PUT requests.
772 // This Response Code is like HTTP 200 "OK" but only used in response to
777 // This should not happen but,
778 // give it a value just in case but output an error
780 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
784 case OC_STACK_RESOURCE_CREATED:
787 case OC_STACK_RESOURCE_DELETED:
790 case OC_STACK_RESOURCE_CHANGED:
793 case OC_STACK_INVALID_QUERY:
796 case OC_STACK_INVALID_OPTION:
799 case OC_STACK_NO_RESOURCE:
802 case OC_STACK_COMM_ERROR:
803 ret = CA_RETRANSMIT_TIMEOUT;
805 case OC_STACK_METHOD_NOT_ALLOWED:
806 ret = CA_METHOD_NOT_ALLOWED;
808 case OC_STACK_NOT_ACCEPTABLE:
809 ret = CA_NOT_ACCEPTABLE;
811 case OC_STACK_UNAUTHORIZED_REQ:
812 ret = CA_UNAUTHORIZED_REQ;
814 case OC_STACK_FORBIDDEN_REQ:
815 ret = CA_FORBIDDEN_REQ;
817 case OC_STACK_TOO_MANY_REQUESTS:
818 ret = CA_TOO_MANY_REQUESTS;
820 case OC_STACK_INTERNAL_SERVER_ERROR:
821 ret = CA_INTERNAL_SERVER_ERROR;
823 case OC_STACK_NOT_IMPLEMENTED:
824 ret = CA_NOT_IMPLEMENTED;
826 case OC_STACK_BAD_GATEWAY:
827 ret = CA_BAD_GATEWAY;
829 case OC_STACK_SERVICE_UNAVAILABLE:
830 ret = CA_SERVICE_UNAVAILABLE;
832 case OC_STACK_GATEWAY_TIMEOUT:
833 ret = CA_RETRANSMIT_TIMEOUT;
835 case OC_STACK_PROXY_NOT_SUPPORTED:
836 ret = CA_PROXY_NOT_SUPPORTED;
844 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
846 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
848 // supply default behavior.
849 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
851 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
853 if ((caFlags & OC_MASK_SCOPE) == 0)
855 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
860 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
862 return (OCTransportFlags)caFlags;
866 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
868 uint32_t lowerBound = 0;
869 uint32_t higherBound = 0;
871 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
873 return OC_STACK_INVALID_PARAM;
876 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
878 cbNode->presence->TTL = maxAgeSeconds;
880 for (int index = 0; index < PresenceTimeOutSize; index++)
882 // Guard against overflow
883 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
886 lowerBound = GetTicks((PresenceTimeOut[index] *
887 cbNode->presence->TTL *
888 MILLISECONDS_PER_SECOND)/100);
892 lowerBound = GetTicks(UINT32_MAX);
895 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
898 higherBound = GetTicks((PresenceTimeOut[index + 1] *
899 cbNode->presence->TTL *
900 MILLISECONDS_PER_SECOND)/100);
904 higherBound = GetTicks(UINT32_MAX);
907 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
909 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
910 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
911 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
914 cbNode->presence->TTLlevel = 0;
916 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
920 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
922 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
924 return OC_RSRVD_TRIGGER_CREATE;
926 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
928 return OC_RSRVD_TRIGGER_CHANGE;
932 return OC_RSRVD_TRIGGER_DELETE;
936 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
940 return OC_PRESENCE_TRIGGER_CREATE;
942 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
944 return OC_PRESENCE_TRIGGER_CREATE;
946 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
948 return OC_PRESENCE_TRIGGER_CHANGE;
952 return OC_PRESENCE_TRIGGER_DELETE;
955 #endif // WITH_PRESENCE
957 OCStackResult OCEncodeAddressForRFC6874(char *outputAddress,
959 const char *inputAddress)
961 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
962 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
964 size_t inputLength = strnlen(inputAddress, outputSize);
966 // inputSize includes the null terminator
967 size_t inputSize = inputLength + 1;
969 if (inputSize > outputSize)
971 OIC_LOG_V(ERROR, TAG,
972 "OCEncodeAddressForRFC6874 failed: "
973 "outputSize (%zu) < inputSize (%zu)",
974 outputSize, inputSize);
976 return OC_STACK_ERROR;
979 char* percentChar = strchr(inputAddress, '%');
981 // If there is no '%' character, then no change is required to the string.
982 if (NULL == percentChar)
984 OICStrcpy(outputAddress, outputSize, inputAddress);
988 const char* addressPart = &inputAddress[0];
989 const char* scopeIdPart = percentChar + 1;
991 // Sanity check to make sure this string doesn't have more '%' characters
992 if (NULL != strchr(scopeIdPart, '%'))
994 return OC_STACK_ERROR;
997 // If no string follows the first '%', then the input was invalid.
998 if (scopeIdPart[0] == '\0')
1000 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
1001 return OC_STACK_ERROR;
1004 // Check to see if the string is already encoded
1005 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
1007 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Input string is already encoded");
1008 return OC_STACK_ERROR;
1011 // Fail if we don't have room for encoded string's two additional chars
1012 if (outputSize < (inputSize + 2))
1014 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: encoded output will not fit!");
1015 return OC_STACK_ERROR;
1018 // Restore the null terminator with an escaped '%' character, per RFC 6874
1019 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
1020 OICStrcat(outputAddress, outputSize, "%25");
1021 OICStrcat(outputAddress, outputSize, scopeIdPart);
1026 OCStackResult OCDecodeAddressForRFC6874(char *outputAddress,
1028 const char *inputAddress,
1031 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
1032 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
1036 end = inputAddress + strlen(inputAddress);
1038 size_t inputLength = end - inputAddress;
1040 const char *percent = strchr(inputAddress, '%');
1041 if (!percent || (percent > end))
1043 OICStrcpyPartial(outputAddress, outputSize, inputAddress, inputLength);
1047 if (percent[1] != '2' || percent[2] != '5')
1049 return OC_STACK_INVALID_URI;
1052 int addrlen = percent - inputAddress + 1;
1053 OICStrcpyPartial(outputAddress, outputSize, inputAddress, addrlen);
1054 OICStrcpyPartial(outputAddress + addrlen, outputSize - addrlen,
1055 percent + 3, end - percent - 3);
1061 #ifdef WITH_PRESENCE
1063 * The cononical presence allows constructed URIs to be string compared.
1065 * requestUri must be a char array of size CA_MAX_URI_LENGTH
1067 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
1068 char *presenceUri, bool isMulticast)
1070 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
1071 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1075 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1076 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1079 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1080 if (ep->adapter == CA_ADAPTER_IP)
1082 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1084 if ('\0' == ep->addr[0]) // multicast
1086 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1090 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1092 OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1093 sizeof(addressEncoded),
1096 if (OC_STACK_OK != result)
1101 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1102 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1107 if ('\0' == ep->addr[0]) // multicast
1109 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1110 ep->port = OC_MULTICAST_PORT;
1112 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1113 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1117 // might work for other adapters (untested, but better than nothing)
1118 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1119 OC_RSRVD_PRESENCE_URI);
1123 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1124 const CAResponseInfo_t *responseInfo)
1126 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1127 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1129 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1130 ClientCB * cbNode = NULL;
1131 char *resourceTypeName = NULL;
1132 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1133 OCStackResult result = OC_STACK_ERROR;
1134 uint32_t maxAge = 0;
1136 char presenceUri[CA_MAX_URI_LENGTH];
1138 int presenceSubscribe = 0;
1139 int multicastPresenceSubscribe = 0;
1141 if (responseInfo->result != CA_CONTENT)
1143 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1144 return OC_STACK_ERROR;
1147 response.payload = NULL;
1148 response.result = OC_STACK_OK;
1150 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1151 FixUpClientResponse(&response);
1153 if (responseInfo->info.payload)
1155 result = OCParsePayload(&response.payload,
1156 PAYLOAD_TYPE_PRESENCE,
1157 responseInfo->info.payload,
1158 responseInfo->info.payloadSize);
1160 if(result != OC_STACK_OK)
1162 OIC_LOG(ERROR, TAG, "Presence parse failed");
1165 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1167 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1168 result = OC_STACK_ERROR;
1171 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1172 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1173 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1176 // check for unicast presence
1177 uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1178 responseInfo->isMulticast);
1179 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1181 return OC_STACK_INVALID_URI;
1183 OIC_LOG(INFO, TAG, "check for unicast presence");
1184 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1187 presenceSubscribe = 1;
1191 // check for multicast presence
1192 OIC_LOG(INFO, TAG, "check for multicast presence");
1193 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1196 multicastPresenceSubscribe = 1;
1200 if (!presenceSubscribe && !multicastPresenceSubscribe)
1202 OIC_LOG(INFO, TAG, "Received a presence notification, "
1203 "but need to register presence callback, ignoring");
1207 if (presenceSubscribe)
1209 if(cbNode->sequenceNumber == response.sequenceNumber)
1211 OIC_LOG(INFO, TAG, "No presence change");
1212 ResetPresenceTTL(cbNode, maxAge);
1213 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1219 OIC_LOG(INFO, TAG, "Stopping presence");
1220 response.result = OC_STACK_PRESENCE_STOPPED;
1221 if(cbNode->presence)
1223 OICFree(cbNode->presence->timeOut);
1224 OICFree(cbNode->presence);
1225 cbNode->presence = NULL;
1230 if(!cbNode->presence)
1232 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1234 if(!(cbNode->presence))
1236 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1237 result = OC_STACK_NO_MEMORY;
1241 VERIFY_NON_NULL_V(cbNode->presence);
1242 cbNode->presence->timeOut = NULL;
1243 cbNode->presence->timeOut = (uint32_t *)
1244 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1245 if(!(cbNode->presence->timeOut)){
1247 "Could not allocate memory for cbNode->presence->timeOut");
1248 OICFree(cbNode->presence);
1249 cbNode->presence = NULL;
1250 result = OC_STACK_NO_MEMORY;
1255 ResetPresenceTTL(cbNode, maxAge);
1257 cbNode->sequenceNumber = response.sequenceNumber;
1262 // This is the multicast case
1263 OIC_LOG(INFO, TAG, "this is the multicast presence");
1266 OIC_LOG(INFO, TAG, "Stopping presence");
1267 response.result = OC_STACK_PRESENCE_STOPPED;
1271 // Ensure that a filter is actually applied.
1272 if (resourceTypeName && cbNode->filterResourceType)
1274 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1275 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1281 OIC_LOG(INFO, TAG, "Before calling into application address space for presence");
1282 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1283 OIC_LOG(INFO, TAG, "After calling into application address space for presence");
1285 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1287 FindAndDeleteClientCB(cbNode);
1291 OCPayloadDestroy(response.payload);
1294 #endif // WITH_PRESENCE
1296 OCStackResult HandleBatchResponse(char *requestUri, OCRepPayload **payload)
1298 if (requestUri && *payload)
1300 char *interfaceName = NULL;
1301 char *rtTypeName = NULL;
1302 char *uriQuery = NULL;
1303 char *uriWithoutQuery = NULL;
1304 if (OC_STACK_OK == getQueryFromUri(requestUri, &uriQuery, &uriWithoutQuery))
1306 if (OC_STACK_OK == ExtractFiltersFromQuery(uriQuery, &interfaceName, &rtTypeName))
1308 if (interfaceName && (0 == strcmp(OC_RSRVD_INTERFACE_BATCH, interfaceName)))
1310 char *uri = (*payload)->uri;
1311 if (uri && 0 != strcmp(uriWithoutQuery, uri))
1313 OCRepPayload *newPayload = OCRepPayloadCreate();
1316 OCRepPayloadSetUri(newPayload, uri);
1317 newPayload->next = *payload;
1318 *payload = newPayload;
1325 OICFree(interfaceName);
1326 OICFree(rtTypeName);
1328 OICFree(uriWithoutQuery);
1331 return OC_STACK_INVALID_PARAM;
1334 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1336 OIC_TRACE_MARK(%s:OCHandleResponse:%s, TAG, responseInfo->info.resourceUri);
1337 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1339 #ifdef WITH_PRESENCE
1340 if(responseInfo->info.resourceUri &&
1341 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1343 HandlePresenceResponse(endPoint, responseInfo);
1348 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1349 responseInfo->info.tokenLength, NULL, NULL);
1353 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1355 // check obs header option
1356 bool obsHeaderOpt = false;
1357 CAHeaderOption_t *options = responseInfo->info.options;
1358 for (uint8_t i = 0; i< responseInfo->info.numOptions; i++)
1360 if (options && options[i].protocolID == CA_COAP_ID &&
1361 options[i].optionID == COAP_OPTION_OBSERVE)
1363 obsHeaderOpt = true;
1368 if(responseInfo->result == CA_EMPTY)
1370 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1371 // We do not have a case for the client to receive a RESET
1372 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1374 //This is the case of receiving an ACK on a request to a slow resource!
1375 OIC_LOG(INFO, TAG, "This is a pure ACK");
1376 //TODO: should we inform the client
1377 // app that at least the request was received at the server?
1380 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1382 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1384 OCClientResponse response =
1385 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1386 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1387 FixUpClientResponse(&response);
1388 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1389 memcpy(response.identity.id, responseInfo->info.identity.id,
1390 sizeof (response.identity.id));
1391 response.identity.id_length = responseInfo->info.identity.id_length;
1393 response.result = CAResponseToOCStackResult(responseInfo->result);
1394 OIC_LOG(INFO, TAG, "Before calling into application address space for reTrans timeout");
1395 cbNode->callBack(cbNode->context,
1396 cbNode->handle, &response);
1397 OIC_LOG(INFO, TAG, "After calling into application address space for reTrans timeout");
1398 FindAndDeleteClientCB(cbNode);
1399 OICFree((void *)response.resourceUri);
1402 else if ((cbNode->method == OC_REST_OBSERVE || cbNode->method == OC_REST_OBSERVE_ALL)
1403 && (responseInfo->result == CA_CONTENT) && !obsHeaderOpt)
1405 OCClientResponse response =
1406 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1407 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1408 FixUpClientResponse(&response);
1409 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1410 memcpy(response.identity.id, responseInfo->info.identity.id,
1411 sizeof (response.identity.id));
1412 response.identity.id_length = responseInfo->info.identity.id_length;
1413 response.result = OC_STACK_UNAUTHORIZED_REQ;
1415 OIC_LOG(INFO, TAG, "Before calling into application address space for observe resp");
1416 cbNode->callBack(cbNode->context,
1419 OIC_LOG(INFO, TAG, "After calling into application address space for observe resp");
1421 FindAndDeleteClientCB(cbNode);
1422 OICFree(response.resourceUri);
1427 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1429 OCClientResponse response;
1430 memset(&response, 0, sizeof(OCClientResponse));
1431 response.devAddr.adapter = OC_DEFAULT_ADAPTER;
1433 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1434 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1435 FixUpClientResponse(&response);
1436 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1437 memcpy(response.identity.id, responseInfo->info.identity.id,
1438 sizeof (response.identity.id));
1439 response.identity.id_length = responseInfo->info.identity.id_length;
1441 response.result = CAResponseToOCStackResult(responseInfo->result);
1443 if(responseInfo->info.payload &&
1444 responseInfo->info.payloadSize)
1446 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1447 // check the security resource
1448 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1450 type = PAYLOAD_TYPE_SECURITY;
1452 else if (cbNode->method == OC_REST_DISCOVER)
1454 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1455 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1457 type = PAYLOAD_TYPE_DISCOVERY;
1460 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1462 type = PAYLOAD_TYPE_DISCOVERY;
1465 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1467 type = PAYLOAD_TYPE_REPRESENTATION;
1469 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1471 type = PAYLOAD_TYPE_REPRESENTATION;
1474 #ifdef ROUTING_GATEWAY
1475 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1477 type = PAYLOAD_TYPE_REPRESENTATION;
1480 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1482 type = PAYLOAD_TYPE_REPRESENTATION;
1485 else if (strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1487 type = PAYLOAD_TYPE_REPRESENTATION;
1492 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1493 cbNode->method, cbNode->requestUri);
1494 OICFree((void *)response.resourceUri);
1498 else if (cbNode->method == OC_REST_GET ||
1499 cbNode->method == OC_REST_PUT ||
1500 cbNode->method == OC_REST_POST ||
1501 cbNode->method == OC_REST_OBSERVE ||
1502 cbNode->method == OC_REST_OBSERVE_ALL ||
1503 cbNode->method == OC_REST_DELETE)
1505 if (cbNode->requestUri)
1507 if (0 == strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri))
1509 type = PAYLOAD_TYPE_REPRESENTATION;
1511 else if (0 == strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri))
1513 type = PAYLOAD_TYPE_REPRESENTATION;
1515 if (type == PAYLOAD_TYPE_INVALID)
1517 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1518 cbNode->method, cbNode->requestUri);
1519 type = PAYLOAD_TYPE_REPRESENTATION;
1524 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1525 type = PAYLOAD_TYPE_REPRESENTATION;
1530 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1531 cbNode->method, cbNode->requestUri);
1532 OICFree((void *)response.resourceUri);
1536 // In case of error, still want application to receive the error message.
1537 if (OCResultToSuccess(response.result) || PAYLOAD_TYPE_REPRESENTATION == type)
1539 if(OC_STACK_OK != OCParsePayload(&response.payload,
1541 responseInfo->info.payload,
1542 responseInfo->info.payloadSize))
1544 OIC_LOG(ERROR, TAG, "Error converting payload");
1545 OCPayloadDestroy(response.payload);
1546 OICFree((void *)response.resourceUri);
1552 OICFree((void *)response.resourceUri);
1553 response.resourceUri = OICStrdup(cbNode->requestUri);
1557 response.numRcvdVendorSpecificHeaderOptions = 0;
1558 if(responseInfo->info.numOptions > 0)
1561 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1562 if(responseInfo->info.options
1563 && responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1566 uint32_t observationOption;
1567 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1568 for (observationOption=0, i=0;
1569 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1573 (observationOption << 8) | optionData[i];
1575 response.sequenceNumber = observationOption;
1576 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1581 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1584 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1586 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1587 OCPayloadDestroy(response.payload);
1588 OICFree((void *)response.resourceUri);
1592 if (response.numRcvdVendorSpecificHeaderOptions > 0)
1594 response.rcvdVendorSpecificHeaderOptions =
1595 (OCHeaderOption *) OICCalloc(response.numRcvdVendorSpecificHeaderOptions, sizeof(OCHeaderOption));
1596 if (NULL == response.rcvdVendorSpecificHeaderOptions)
1598 OIC_LOG(ERROR, TAG, "Failed to allocate memory for vendor header options");
1599 OCPayloadDestroy(response.payload);
1600 OICFree((void *)response.resourceUri);
1604 memcpy(response.rcvdVendorSpecificHeaderOptions, responseInfo->info.options + start,
1605 response.numRcvdVendorSpecificHeaderOptions*sizeof(OCHeaderOption));
1609 if (cbNode->method == OC_REST_OBSERVE &&
1610 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1611 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1612 response.sequenceNumber <= cbNode->sequenceNumber)
1614 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1615 response.sequenceNumber);
1620 if (cbNode->requestUri)
1622 // if request uri is '/oic/rd', update ins value of resource.
1623 char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
1626 OCUpdateResourceInsWithResponse(cbNode->requestUri, &response);
1630 // set remoteID(device ID) into OCClientResponse callback parameter
1631 if (OC_REST_DISCOVER == cbNode->method)
1633 OIC_LOG(INFO, TAG, "cbNode method is OC_REST_DISCOVER");
1634 OCDiscoveryPayload *payload = (OCDiscoveryPayload*) response.payload;
1635 // Payload can be empty in case of error message.
1636 if (payload && payload->sid)
1638 OICStrcpy(response.devAddr.remoteId, sizeof(response.devAddr.remoteId),
1640 OIC_LOG_V(INFO_PRIVATE, TAG, "Device ID of response : %s",
1641 response.devAddr.remoteId);
1644 if(NULL == response.resourceUri)
1646 response.resourceUri = OICStrdup(cbNode->requestUri);
1650 if (cbNode->requestUri)
1652 OIC_LOG_V(INFO, TAG, "cbNode requestUri is %s", cbNode->requestUri);
1653 if (cbNode->method == OC_REST_POST &&
1654 strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1656 OCHandleKeepAliveResponse(endPoint, response.payload);
1660 if (response.payload && response.payload->type == PAYLOAD_TYPE_REPRESENTATION)
1662 OIC_LOG(INFO, TAG, "Handle batch response");
1663 HandleBatchResponse(cbNode->requestUri, (OCRepPayload **)&response.payload);
1666 OIC_LOG(INFO, TAG, "Before calling into application address space for handleResponse");
1667 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1670 OIC_LOG(INFO, TAG, "After calling into application address space for handleResponse");
1672 cbNode->sequenceNumber = response.sequenceNumber;
1674 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1676 FindAndDeleteClientCB(cbNode);
1680 // To keep discovery callbacks active.
1681 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1682 MILLISECONDS_PER_SECOND);
1686 //Need to send ACK when the response is CON
1687 if(responseInfo->info.type == CA_MSG_CONFIRM)
1689 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1691 OIC_LOG(INFO, TAG, "Received a confirmable message. Sending EMPTY");
1692 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1693 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1697 OICFree((void *)response.resourceUri);
1698 OCPayloadDestroy(response.payload);
1699 OICFree(response.rcvdVendorSpecificHeaderOptions);
1704 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1705 responseInfo->info.tokenLength);
1709 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1710 if(responseInfo->result == CA_EMPTY)
1712 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1713 if(responseInfo->info.type == CA_MSG_RESET)
1715 OIC_LOG(INFO, TAG, "This is a RESET");
1716 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1717 OC_OBSERVER_NOT_INTERESTED);
1719 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1721 OIC_LOG(INFO, TAG, "This is a pure ACK");
1722 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1723 OC_OBSERVER_STILL_INTERESTED);
1726 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1728 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1729 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1730 OC_OBSERVER_FAILED_COMM);
1733 FreeObserver(observer);
1737 if(!cbNode && !observer)
1739 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1740 || myStackMode == OC_GATEWAY)
1742 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1743 if(responseInfo->result == CA_EMPTY)
1745 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1749 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1751 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1752 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1753 CA_MSG_RESET, 0, NULL, NULL, 0, NULL,
1754 CA_RESPONSE_FOR_RES);
1759 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1760 || myStackMode == OC_GATEWAY)
1762 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1763 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1765 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1766 responseInfo->info.messageId);
1768 if (responseInfo->info.type == CA_MSG_RESET)
1770 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1771 responseInfo->info.messageId);
1779 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1781 VERIFY_NON_NULL_NR(endPoint, FATAL);
1782 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1784 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1785 OIC_TRACE_BEGIN(%s:HandleCAResponses, TAG);
1787 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1788 #ifdef ROUTING_GATEWAY
1789 bool needRIHandling = false;
1791 * Routing manager is going to update either of endpoint or response or both.
1792 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1793 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1796 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1798 if(ret != OC_STACK_OK || !needRIHandling)
1800 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1807 * Put source in sender endpoint so that the next packet from application can be routed to
1808 * proper destination and remove "RM" coap header option before passing request / response to
1809 * RI as this option will make no sense to either RI or application.
1811 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1812 (uint8_t *) &(responseInfo->info.numOptions),
1813 (CAEndpoint_t *) endPoint);
1816 OCHandleResponse(endPoint, responseInfo);
1818 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1822 * This function handles error response from CA
1823 * code shall be added to handle the errors
1825 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1827 VERIFY_NON_NULL_NR(endPoint, FATAL);
1828 VERIFY_NON_NULL_NR(errorInfo, FATAL);
1830 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1831 OIC_TRACE_BEGIN(%s:HandleCAErrorResponse, TAG);
1833 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1834 errorInfo->info.tokenLength, NULL, NULL);
1837 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1838 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1839 FixUpClientResponse(&response);
1840 response.resourceUri = errorInfo->info.resourceUri;
1841 memcpy(response.identity.id, errorInfo->info.identity.id,
1842 sizeof (response.identity.id));
1843 response.identity.id_length = errorInfo->info.identity.id_length;
1844 response.result = CAResultToOCResult(errorInfo->result);
1846 OIC_LOG(INFO, TAG, "Before calling into application address space for error response");
1847 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1848 OIC_LOG(INFO, TAG, "After calling into application address space for error response");
1850 FindAndDeleteClientCB(cbNode);
1853 ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1854 errorInfo->info.tokenLength);
1857 OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1858 OCStackResult result = CAResultToOCResult(errorInfo->result);
1859 if (OC_STACK_COMM_ERROR == result)
1861 OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1862 OC_OBSERVER_FAILED_COMM);
1866 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1868 if(NULL != observer)
1876 * This function sends out Direct Stack Responses. These are responses that are not coming
1877 * from the application entity handler. These responses have no payload and are usually ACKs,
1878 * RESETs or some error conditions that were caught by the stack.
1880 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1881 const CAResponseResult_t responseResult, const CAMessageType_t type,
1882 const uint8_t numOptions, const CAHeaderOption_t *options,
1883 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1884 CADataType_t dataType)
1886 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1888 if (endPoint->flags & CA_MULTICAST)
1890 OIC_LOG(ERROR, TAG, "It is unnecessary to respond to a multicast request");
1894 CAResponseInfo_t respInfo = { .result = responseResult };
1895 respInfo.info.messageId = coapID;
1896 respInfo.info.numOptions = numOptions;
1898 if (respInfo.info.numOptions)
1900 respInfo.info.options =
1901 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1902 memcpy (respInfo.info.options, options,
1903 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1907 respInfo.info.payload = NULL;
1908 respInfo.info.token = token;
1909 respInfo.info.tokenLength = tokenLength;
1910 respInfo.info.type = type;
1911 respInfo.info.resourceUri = OICStrdup (resourceUri);
1912 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1913 respInfo.info.dataType = dataType;
1915 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1916 // Add the destination to route option from the endpoint->routeData.
1917 bool doPost = false;
1918 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1919 if(OC_STACK_OK != result)
1921 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1922 OICFree (respInfo.info.resourceUri);
1923 OICFree (respInfo.info.options);
1928 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1929 CARequestInfo_t reqInfo = {.method = CA_POST };
1930 /* The following initialization is not done in a single initializer block as in
1931 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1932 * does not have designated initalizers. This is a work-around for now.
1934 reqInfo.info.type = CA_MSG_NONCONFIRM;
1935 reqInfo.info.messageId = coapID;
1936 reqInfo.info.tokenLength = tokenLength;
1937 reqInfo.info.token = token;
1938 reqInfo.info.numOptions = respInfo.info.numOptions;
1939 reqInfo.info.payload = NULL;
1940 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1941 if (reqInfo.info.numOptions)
1943 reqInfo.info.options =
1944 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1945 if (NULL == reqInfo.info.options)
1947 OIC_LOG(ERROR, TAG, "Calloc failed");
1948 OICFree (reqInfo.info.resourceUri);
1949 OICFree (respInfo.info.resourceUri);
1950 OICFree (respInfo.info.options);
1951 return OC_STACK_NO_MEMORY;
1953 memcpy (reqInfo.info.options, respInfo.info.options,
1954 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1957 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1958 OICFree (reqInfo.info.resourceUri);
1959 OICFree (reqInfo.info.options);
1960 OICFree (respInfo.info.resourceUri);
1961 OICFree (respInfo.info.options);
1962 if (CA_STATUS_OK != caResult)
1964 OIC_LOG(ERROR, TAG, "CASendRequest error");
1965 return CAResultToOCResult(caResult);
1971 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1973 // resourceUri in the info field is cloned in the CA layer and
1974 // thus ownership is still here.
1975 OICFree (respInfo.info.resourceUri);
1976 OICFree (respInfo.info.options);
1977 if(CA_STATUS_OK != caResult)
1979 OIC_LOG(ERROR, TAG, "CASendResponse error");
1980 return CAResultToOCResult(caResult);
1983 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1987 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1989 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1990 OCStackResult result = OC_STACK_ERROR;
1991 if(!protocolRequest)
1993 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1994 return OC_STACK_INVALID_PARAM;
1997 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1998 protocolRequest->tokenLength);
2001 OIC_LOG(INFO, TAG, "This is a new Server Request");
2002 result = AddServerRequest(&request, protocolRequest->coapID,
2003 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
2004 protocolRequest->numRcvdVendorSpecificHeaderOptions,
2005 protocolRequest->observationOption, protocolRequest->qos,
2006 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
2007 protocolRequest->payload, protocolRequest->requestToken,
2008 protocolRequest->tokenLength, protocolRequest->resourceUrl,
2009 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
2010 &protocolRequest->devAddr);
2011 if (OC_STACK_OK != result)
2013 OIC_LOG(ERROR, TAG, "Error adding server request");
2019 OIC_LOG(ERROR, TAG, "Out of Memory");
2020 return OC_STACK_NO_MEMORY;
2023 if(!protocolRequest->reqMorePacket)
2025 request->requestComplete = 1;
2028 OIC_LOG_V(WARNING, TAG, "Server request ID = [%u]", request->requestId);
2032 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
2033 return OC_STACK_DUPLICATE_REQUEST;
2036 if(request->requestComplete)
2038 OIC_LOG(INFO, TAG, "This Server Request is complete");
2039 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2040 OCResource *resource = NULL;
2041 result = DetermineResourceHandling (request, &resHandling, &resource);
2042 if (result == OC_STACK_OK)
2044 result = ProcessRequest(resHandling, resource, request);
2049 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2050 result = OC_STACK_CONTINUE;
2055 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2057 OIC_TRACE_MARK(%s:OCHandleRequests:%s, TAG, requestInfo->info.resourceUri);
2058 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2060 OCStackResult requestResult = OC_STACK_ERROR;
2062 if(myStackMode == OC_CLIENT)
2064 //TODO: should the client be responding to requests?
2068 OCServerProtocolRequest serverRequest = {0};
2070 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2072 char * uriWithoutQuery = NULL;
2073 char * query = NULL;
2075 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2077 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2079 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2082 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2083 OIC_LOG_V(INFO, TAG, "Query : %s", query);
2085 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2087 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2088 OICFree(uriWithoutQuery);
2092 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2093 OICFree(uriWithoutQuery);
2100 if(strlen(query) < MAX_QUERY_LENGTH)
2102 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2107 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2113 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2115 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2116 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2117 if (!serverRequest.payload)
2119 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2122 memcpy (serverRequest.payload, requestInfo->info.payload,
2123 requestInfo->info.payloadSize);
2127 serverRequest.reqTotalSize = 0;
2130 switch (requestInfo->method)
2133 serverRequest.method = OC_REST_GET;
2136 serverRequest.method = OC_REST_PUT;
2139 serverRequest.method = OC_REST_POST;
2142 serverRequest.method = OC_REST_DELETE;
2145 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2146 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2147 requestInfo->info.type, requestInfo->info.numOptions,
2148 requestInfo->info.options, requestInfo->info.token,
2149 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2151 OICFree(serverRequest.payload);
2155 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2156 requestInfo->info.tokenLength);
2158 serverRequest.tokenLength = requestInfo->info.tokenLength;
2159 if (serverRequest.tokenLength) {
2161 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2163 if (!serverRequest.requestToken)
2165 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2166 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2167 requestInfo->info.type, requestInfo->info.numOptions,
2168 requestInfo->info.options, requestInfo->info.token,
2169 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2171 OICFree(serverRequest.payload);
2174 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2177 switch (requestInfo->info.acceptFormat)
2179 case CA_FORMAT_APPLICATION_CBOR:
2180 serverRequest.acceptFormat = OC_FORMAT_CBOR;
2182 case CA_FORMAT_UNDEFINED:
2183 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2186 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2189 if (requestInfo->info.type == CA_MSG_CONFIRM)
2191 serverRequest.qos = OC_HIGH_QOS;
2195 serverRequest.qos = OC_LOW_QOS;
2197 // CA does not need the following field
2198 // Are we sure CA does not need them? how is it responding to multicast
2199 serverRequest.delayedResNeeded = 0;
2201 serverRequest.coapID = requestInfo->info.messageId;
2203 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2205 // copy vendor specific header options
2206 uint8_t tempNum = (requestInfo->info.numOptions);
2208 // Assume no observation requested and it is a pure GET.
2209 // If obs registration/de-registration requested it'll be fetched from the
2210 // options in GetObserveHeaderOption()
2211 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2213 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2214 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2217 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2218 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2219 requestInfo->info.type, requestInfo->info.numOptions,
2220 requestInfo->info.options, requestInfo->info.token,
2221 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2223 OICFree(serverRequest.payload);
2224 OICFree(serverRequest.requestToken);
2228 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2229 if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2231 serverRequest.rcvdVendorSpecificHeaderOptions = (OCHeaderOption*) OICCalloc(tempNum, sizeof(OCHeaderOption));
2232 if (NULL == serverRequest.rcvdVendorSpecificHeaderOptions)
2234 OIC_LOG(ERROR, TAG, "Failed to allocated memory to vnd header options!");
2235 OICFree(serverRequest.payload);
2236 OICFree(serverRequest.requestToken);
2240 memcpy (serverRequest.rcvdVendorSpecificHeaderOptions, requestInfo->info.options,
2241 sizeof(CAHeaderOption_t)*tempNum);
2244 requestResult = HandleStackRequests (&serverRequest);
2246 // Send ACK to client as precursor to slow response
2247 if (requestResult == OC_STACK_SLOW_RESOURCE)
2249 if (requestInfo->info.type == CA_MSG_CONFIRM)
2251 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2252 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2257 if (requestResult == OC_STACK_RESOURCE_ERROR
2258 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2260 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2263 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2265 if (requestResult == OC_STACK_RESOURCE_ERROR)
2267 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2269 else if (!OCResultToSuccess(requestResult))
2271 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2275 else if(!OCResultToSuccess(requestResult))
2277 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2279 // Delete observer node if it is OBSERVE failure from app
2280 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2282 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2285 CAResponseResult_t stackResponse =
2286 OCToCAStackResult(requestResult, serverRequest.method);
2288 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2289 requestInfo->info.type, requestInfo->info.numOptions,
2290 requestInfo->info.options, requestInfo->info.token,
2291 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2294 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2295 // The token is copied in there, and is thus still owned by this function.
2296 OICFree(serverRequest.payload);
2297 OICFree(serverRequest.requestToken);
2298 OICFree(serverRequest.rcvdVendorSpecificHeaderOptions);
2299 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2302 //This function will be called back by CA layer when a request is received
2303 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2305 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2306 OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2309 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2316 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2321 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2322 #ifdef ROUTING_GATEWAY
2323 bool needRIHandling = false;
2324 bool isEmptyMsg = false;
2326 * Routing manager is going to update either of endpoint or request or both.
2327 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2328 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2329 * destination. It can also remove "RM" coap header option before passing request / response to
2330 * RI as this option will make no sense to either RI or application.
2332 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2333 &needRIHandling, &isEmptyMsg);
2334 if(OC_STACK_OK != ret || !needRIHandling)
2336 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2343 * Put source in sender endpoint so that the next packet from application can be routed to
2344 * proper destination and remove RM header option.
2346 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2347 (uint8_t *) &(requestInfo->info.numOptions),
2348 (CAEndpoint_t *) endPoint);
2350 #ifdef ROUTING_GATEWAY
2354 * In Gateways, the MSGType in route option is used to check if the actual
2355 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2356 * EMPTY response is sent in the form of POST request which need to be changed
2357 * to a EMPTY response by RM. This translation is done in this part of the code.
2359 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2360 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2361 .info.messageId = requestInfo->info.messageId,
2362 .info.type = CA_MSG_ACKNOWLEDGE};
2363 OCHandleResponse(endPoint, &respInfo);
2369 // Normal handling of the packet
2370 OCHandleRequests(endPoint, requestInfo);
2372 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2376 //-----------------------------------------------------------------------------
2378 //-----------------------------------------------------------------------------
2380 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2383 !raInfo->username ||
2384 !raInfo->hostname ||
2385 !raInfo->xmpp_domain)
2388 return OC_STACK_INVALID_PARAM;
2390 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2391 gRASetInfo = (result == OC_STACK_OK)? true : false;
2397 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2401 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2404 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2406 OC_UNUSED(serverFlags);
2407 OC_UNUSED(clientFlags);
2409 OIC_LOG(DEBUG, TAG, "call OCInit1");
2410 return OCInit2(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS, OC_DEFAULT_ADAPTER);
2413 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2414 OCTransportAdapter transportType)
2416 if(stackState == OC_STACK_INITIALIZED)
2418 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2419 OCStop() between them are ignored.");
2423 #ifndef ROUTING_GATEWAY
2424 if (OC_GATEWAY == mode)
2426 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2427 return OC_STACK_INVALID_PARAM;
2434 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2435 return OC_STACK_ERROR;
2439 OCStackResult result = OC_STACK_ERROR;
2440 OIC_LOG(INFO, TAG, "Entering OCInit");
2443 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2444 || (mode == OC_GATEWAY)))
2446 OIC_LOG(ERROR, TAG, "Invalid mode");
2447 return OC_STACK_ERROR;
2451 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2453 caglobals.client = true;
2455 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2457 caglobals.server = true;
2460 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2461 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2463 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2465 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2466 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2468 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2471 defaultDeviceHandler = NULL;
2472 defaultDeviceHandlerCallbackParameter = NULL;
2474 result = InitializeScheduleResourceList();
2475 VERIFY_SUCCESS(result, OC_STACK_OK);
2477 result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2478 VERIFY_SUCCESS(result, OC_STACK_OK);
2480 result = CAResultToOCResult(OCSelectNetwork(transportType));
2481 VERIFY_SUCCESS(result, OC_STACK_OK);
2483 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2484 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2485 VERIFY_SUCCESS(result, OC_STACK_OK);
2487 switch (myStackMode)
2490 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2491 result = CAResultToOCResult(CAStartDiscoveryServer());
2492 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2495 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2496 result = CAResultToOCResult(CAStartListeningServer());
2497 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2499 case OC_CLIENT_SERVER:
2501 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2502 result = CAResultToOCResult(CAStartListeningServer());
2503 if(result == OC_STACK_OK)
2505 result = CAResultToOCResult(CAStartDiscoveryServer());
2509 VERIFY_SUCCESS(result, OC_STACK_OK);
2512 CARegisterKeepAliveHandler(OCHandleKeepAliveConnCB);
2515 #ifdef WITH_PRESENCE
2516 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2517 #endif // WITH_PRESENCE
2519 //Update Stack state to initialized
2520 stackState = OC_STACK_INITIALIZED;
2522 // Initialize resource
2523 if(myStackMode != OC_CLIENT)
2525 result = initResources();
2528 // Initialize the SRM Policy Engine
2529 if(result == OC_STACK_OK)
2531 result = SRMInitPolicyEngine();
2532 // TODO after BeachHead delivery: consolidate into single SRMInit()
2534 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2535 RMSetStackMode(mode);
2536 #ifdef ROUTING_GATEWAY
2537 if (OC_GATEWAY == myStackMode)
2539 result = RMInitialize();
2545 if (result == OC_STACK_OK)
2547 result = OCInitializeKeepAlive(myStackMode);
2551 InitializeObserverList();
2554 if(result != OC_STACK_OK)
2556 OIC_LOG(ERROR, TAG, "Stack initialization error");
2557 TerminateScheduleResourceList();
2558 deleteAllResources();
2560 stackState = OC_STACK_UNINITIALIZED;
2565 OCStackResult OCStop()
2567 OIC_LOG(INFO, TAG, "Entering OCStop");
2569 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2571 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2574 else if (stackState != OC_STACK_INITIALIZED)
2576 OIC_LOG(INFO, TAG, "Stack not initialized");
2577 return OC_STACK_ERROR;
2580 // unset cautil config
2581 CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2582 CAUtilSetBTConfigure(configs);
2584 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2586 CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2587 OCDefaultConnectionStateChangedHandler);
2589 #ifdef WITH_PRESENCE
2590 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2591 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2592 presenceResource.presenceTTL = 0;
2593 presenceState = OC_PRESENCE_UNINITIALIZED;
2594 #endif // WITH_PRESENCE
2596 #ifdef ROUTING_GATEWAY
2597 if (OC_GATEWAY == myStackMode)
2604 OCTerminateKeepAlive(myStackMode);
2607 TerminateScheduleResourceList();
2608 // Remove all observers
2609 DeleteObserverList();
2610 // Free memory dynamically allocated for resources
2611 deleteAllResources();
2612 // Remove all the client callbacks
2613 DeleteClientCBList();
2614 // Terminate connectivity-abstraction layer.
2617 // De-init the SRM Policy Engine
2618 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2619 SRMDeInitPolicyEngine();
2621 // Destroy Observer List Mutex
2622 TerminateObserverList();
2624 stackState = OC_STACK_UNINITIALIZED;
2628 OCStackResult OCStartMulticastServer()
2630 if(stackState != OC_STACK_INITIALIZED)
2632 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2633 return OC_STACK_ERROR;
2635 CAResult_t ret = CAStartListeningServer();
2636 if (CA_STATUS_OK != ret)
2638 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2639 return OC_STACK_ERROR;
2644 OCStackResult OCStopMulticastServer()
2646 CAResult_t ret = CAStopListeningServer();
2647 if (CA_STATUS_OK != ret)
2649 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2650 return OC_STACK_ERROR;
2655 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2660 return CA_MSG_CONFIRM;
2665 return CA_MSG_NONCONFIRM;
2669 OCStackResult ParseRequestUri(const char *fullUri,
2670 OCTransportAdapter adapter,
2671 OCTransportFlags flags,
2672 OCDevAddr **devAddr,
2674 char **resourceType)
2676 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2678 OCStackResult result = OC_STACK_OK;
2679 OCDevAddr *da = NULL;
2683 // provide defaults for all returned values
2690 *resourceUri = NULL;
2694 *resourceType = NULL;
2697 // delimit url prefix, if any
2698 const char *start = fullUri;
2699 char *slash2 = strstr(start, "//");
2704 char *slash = strchr(start, '/');
2707 return OC_STACK_INVALID_URI;
2710 // process url scheme
2711 size_t prefixLen = slash2 - fullUri;
2715 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2716 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2722 // TODO: this logic should come in with unit tests exercising the various strings
2723 // processs url prefix, if any
2724 size_t urlLen = slash - start;
2728 if (urlLen && devAddr)
2729 { // construct OCDevAddr
2730 if (start[0] == '[')
2732 char *close = strchr(++start, ']');
2733 if (!close || close > slash)
2735 return OC_STACK_INVALID_URI;
2738 if (close[1] == ':')
2745 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2749 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2751 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2755 char *dot = strchr(start, '.');
2756 if (dot && dot < slash)
2758 colon = strchr(start, ':');
2759 end = (colon && colon < slash) ? colon : slash;
2764 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2768 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2770 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2778 if (len >= sizeof(da->addr))
2780 return OC_STACK_INVALID_URI;
2782 // collect port, if any
2783 if (colon && colon < slash)
2785 for (colon++; colon < slash; colon++)
2788 if (c < '0' || c > '9')
2790 return OC_STACK_INVALID_URI;
2792 port = 10 * port + c - '0';
2797 if (len >= sizeof(da->addr))
2799 return OC_STACK_INVALID_URI;
2802 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2805 return OC_STACK_NO_MEMORY;
2808 // Decode address per RFC 6874.
2809 result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2810 if (result != OC_STACK_OK)
2817 da->adapter = adapter;
2819 if (!strncmp(fullUri, "coaps", 5))
2821 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2826 // process resource uri, if any
2828 { // request uri and query
2829 size_t ulen = strlen(slash); // resource uri length
2830 size_t tlen = 0; // resource type length
2833 static const char strPresence[] = "/oic/ad?rt=";
2834 static const size_t lenPresence = sizeof(strPresence) - 1;
2835 if (!strncmp(slash, strPresence, lenPresence))
2837 type = slash + lenPresence;
2838 tlen = ulen - lenPresence;
2843 *resourceUri = (char *)OICMalloc(ulen + 1);
2846 result = OC_STACK_NO_MEMORY;
2849 OICStrcpy(*resourceUri, (ulen + 1), slash);
2852 if (type && resourceType)
2854 *resourceType = (char *)OICMalloc(tlen + 1);
2857 result = OC_STACK_NO_MEMORY;
2861 OICStrcpy(*resourceType, (tlen+1), type);
2868 // free all returned values
2875 OICFree(*resourceUri);
2879 OICFree(*resourceType);
2884 #ifdef WITH_PRESENCE
2885 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2889 char uri[CA_MAX_URI_LENGTH];
2891 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2893 *requestUri = OICStrdup(uri);
2896 return OC_STACK_NO_MEMORY;
2901 #endif // WITH_PRESENCE
2904 * Discover or Perform requests on a specified resource
2906 OCStackResult OCDoResource(OCDoHandle *handle,
2908 const char *requestUri,
2909 const OCDevAddr *destination,
2911 OCConnectivityType connectivityType,
2912 OCQualityOfService qos,
2913 OCCallbackData *cbData,
2914 OCHeaderOption *options,
2917 OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
2918 connectivityType, qos, cbData, options, numOptions);
2920 // This is the owner of the payload object, so we free it
2921 OCPayloadDestroy(payload);
2926 * Discover or Perform requests on a specified resource
2928 OCStackResult OCDoRequest(OCDoHandle *handle,
2930 const char *requestUri,
2931 const OCDevAddr *destination,
2933 OCConnectivityType connectivityType,
2934 OCQualityOfService qos,
2935 OCCallbackData *cbData,
2936 OCHeaderOption *options,
2939 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2940 OIC_TRACE_BEGIN(%s:OCDoRequest, TAG);
2942 // Validate input parameters
2943 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2944 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2946 OCStackResult result = OC_STACK_ERROR;
2947 CAResult_t caResult;
2948 CAToken_t token = NULL;
2949 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2950 ClientCB *clientCB = NULL;
2951 OCDoHandle resHandle = NULL;
2952 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2953 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2955 OCTransportAdapter adapter;
2956 OCTransportFlags flags;
2957 // the request contents are put here
2958 CARequestInfo_t requestInfo = {.method = CA_GET};
2959 // requestUri will be parsed into the following three variables
2960 OCDevAddr *devAddr = NULL;
2961 char *resourceUri = NULL;
2962 char *resourceType = NULL;
2965 * Support original behavior with address on resourceUri argument.
2967 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2968 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2972 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2973 if (result != OC_STACK_OK)
2975 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2979 else if (!checkProxyUri(options, numOptions))
2981 result = OC_STACK_INVALID_URI;
2982 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2989 case OC_REST_OBSERVE:
2990 case OC_REST_OBSERVE_ALL:
2991 requestInfo.method = CA_GET;
2994 requestInfo.method = CA_PUT;
2997 requestInfo.method = CA_POST;
2999 case OC_REST_DELETE:
3000 requestInfo.method = CA_DELETE;
3002 case OC_REST_DISCOVER:
3003 #ifdef WITH_PRESENCE
3004 case OC_REST_PRESENCE:
3006 if (destination || devAddr)
3008 requestInfo.isMulticast = false;
3012 tmpDevAddr.adapter = adapter;
3013 tmpDevAddr.flags = flags;
3014 destination = &tmpDevAddr;
3015 requestInfo.isMulticast = true;
3018 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
3019 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
3020 // replacing method type with GET.
3021 requestInfo.method = CA_GET;
3024 result = OC_STACK_INVALID_METHOD;
3028 if (!devAddr && !destination)
3030 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
3031 result = OC_STACK_INVALID_PARAM;
3035 /* If not original behavior, use destination argument */
3036 if (destination && !devAddr)
3038 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
3041 result = OC_STACK_NO_MEMORY;
3044 OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
3045 *devAddr = *destination;
3050 OIC_LOG_V(INFO_PRIVATE, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
3051 if (!requestInfo.isMulticast)
3053 OIC_LOG_V(DEBUG, TAG, "remoteAddr of devAddr : [%s]:[%d]",
3054 devAddr->addr, devAddr->port);
3058 resHandle = GenerateInvocationHandle();
3061 result = OC_STACK_NO_MEMORY;
3065 caResult = CAGenerateToken(&token, tokenLength);
3066 if (caResult != CA_STATUS_OK)
3068 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3069 result = CAResultToOCResult(caResult);
3073 // fill in request data
3074 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3075 requestInfo.info.token = token;
3076 requestInfo.info.tokenLength = tokenLength;
3078 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3080 result = CreateObserveHeaderOption (&(requestInfo.info.options),
3081 options, numOptions, OC_OBSERVE_REGISTER);
3082 if (result != OC_STACK_OK)
3086 requestInfo.info.numOptions = numOptions + 1;
3090 requestInfo.info.numOptions = numOptions;
3091 requestInfo.info.options =
3092 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3093 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3094 numOptions * sizeof(CAHeaderOption_t));
3097 CopyDevAddrToEndpoint(devAddr, &endpoint);
3102 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3105 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3108 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3112 requestInfo.info.payload = NULL;
3113 requestInfo.info.payloadSize = 0;
3114 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3117 // prepare for response
3118 #ifdef WITH_PRESENCE
3119 if (method == OC_REST_PRESENCE)
3121 char *presenceUri = NULL;
3122 result = OCPreparePresence(&endpoint, &presenceUri,
3123 requestInfo.isMulticast);
3124 if (OC_STACK_OK != result)
3129 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3130 // Presence notification will form a canonical uri to
3131 // look for callbacks into the application.
3134 OICFree(resourceUri);
3136 resourceUri = presenceUri;
3140 // update resourceUri onto requestInfo after check presence uri
3141 requestInfo.info.resourceUri = resourceUri;
3143 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3144 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3145 method, devAddr, resourceUri, resourceType, ttl);
3146 if (OC_STACK_OK != result)
3151 cbData = NULL; // Client CB list entry now owns it
3152 token = NULL; // Client CB list entry now owns it
3153 devAddr = NULL; // Client CB list entry now owns it
3154 resourceUri = NULL; // Client CB list entry now owns it
3155 resourceType = NULL; // Client CB list entry now owns it
3157 #ifdef WITH_PRESENCE
3158 if (method == OC_REST_PRESENCE)
3160 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3164 *handle = resHandle;
3166 #ifdef WITH_PROCESS_EVENT
3167 OCSendProcessEventSignal();
3168 #endif // WITH_PROCESS_EVENT
3175 result = OCSendRequest(&endpoint, &requestInfo);
3176 if (OC_STACK_OK != result)
3183 *handle = resHandle;
3187 if (result != OC_STACK_OK)
3189 OIC_LOG(ERROR, TAG, "OCDoResource error");
3190 if (NULL != cbData && NULL != cbData->cd)
3192 cbData->cd(cbData->context);
3194 if (!clientCB) // token and resHandle associated with clientCB
3196 CADestroyToken(token);
3201 FindAndDeleteClientCB(clientCB);
3209 OICFree(requestInfo.info.payload);
3211 OICFree(resourceUri);
3212 OICFree(resourceType);
3213 OICFree(requestInfo.info.options);
3218 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3222 * This ftn is implemented one of two ways in the case of observation:
3224 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3225 * Remove the callback associated on client side.
3226 * When the next notification comes in from server,
3227 * reply with RESET message to server.
3228 * Keep in mind that the server will react to RESET only
3229 * if the last notification was sent as CON
3231 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3232 * and it is associated with an observe request
3233 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3234 * Send CON Observe request to server with
3235 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3236 * Remove the callback associated on client side.
3238 OCStackResult ret = OC_STACK_OK;
3239 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3240 CARequestInfo_t requestInfo = {.method = CA_GET};
3244 return OC_STACK_INVALID_PARAM;
3247 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3250 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3251 return OC_STACK_ERROR;
3254 switch (clientCB->method)
3256 case OC_REST_OBSERVE:
3257 case OC_REST_OBSERVE_ALL:
3259 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3261 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3263 if (((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS) ||
3264 ((endpoint.adapter & CA_ADAPTER_TCP) && OC_LOW_QOS_WITH_TCP == qos))
3266 OIC_LOG_V(INFO, TAG, "the %s observe callback is removed", clientCB->requestUri);
3267 FindAndDeleteClientCB(clientCB);
3271 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3273 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3274 requestInfo.info.token = clientCB->token;
3275 requestInfo.info.tokenLength = clientCB->tokenLength;
3277 if (CreateObserveHeaderOption (&(requestInfo.info.options),
3278 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3280 return OC_STACK_ERROR;
3282 requestInfo.info.numOptions = numOptions + 1;
3283 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3286 ret = OCSendRequest(&endpoint, &requestInfo);
3288 if (requestInfo.info.options)
3290 OICFree (requestInfo.info.options);
3292 if (requestInfo.info.resourceUri)
3294 OICFree (requestInfo.info.resourceUri);
3299 case OC_REST_DISCOVER:
3300 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3301 clientCB->requestUri);
3302 FindAndDeleteClientCB(clientCB);
3305 #ifdef WITH_PRESENCE
3306 case OC_REST_PRESENCE:
3307 FindAndDeleteClientCB(clientCB);
3313 case OC_REST_DELETE:
3314 OIC_LOG_V(INFO, TAG, "Cancelling request callback for resource %s",
3315 clientCB->requestUri);
3316 FindAndDeleteClientCB(clientCB);
3320 ret = OC_STACK_INVALID_METHOD;
3328 * @brief Register Persistent storage callback.
3329 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3331 * OC_STACK_OK - No errors; Success
3332 * OC_STACK_INVALID_PARAM - Invalid parameter
3334 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3336 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3337 if(!persistentStorageHandler)
3339 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3340 return OC_STACK_INVALID_PARAM;
3344 if( !persistentStorageHandler->open ||
3345 !persistentStorageHandler->close ||
3346 !persistentStorageHandler->read ||
3347 !persistentStorageHandler->unlink ||
3348 !persistentStorageHandler->write)
3350 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3351 return OC_STACK_INVALID_PARAM;
3354 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3357 #ifdef WITH_PRESENCE
3359 #ifdef WITH_PROCESS_EVENT
3360 OCStackResult OCProcessPresence(uint32_t *nextEventTime)
3361 #else // WITH_PROCESS_EVENT
3362 OCStackResult OCProcessPresence(void)
3363 #endif // !WITH_PROCESS_EVENT
3365 OCStackResult result = OC_STACK_OK;
3367 // the following line floods the log with messages that are irrelevant
3368 // to most purposes. Uncomment as needed.
3369 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3370 ClientCB* cbNode = NULL;
3371 ClientCB* tempcbNode = NULL;
3372 OCClientResponse clientResponse;
3373 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3375 LL_FOREACH_SAFE(cbList, cbNode, tempcbNode)
3377 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3382 uint32_t now = GetTicks(0);
3383 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3384 cbNode->presence->TTLlevel);
3385 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3387 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3392 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3394 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3395 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3397 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3399 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3401 clientResponse.sequenceNumber = 0;
3402 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3403 clientResponse.devAddr = *cbNode->devAddr;
3404 FixUpClientResponse(&clientResponse);
3405 clientResponse.payload = NULL;
3407 // Increment the TTLLevel (going to a next state), so we don't keep
3408 // sending presence notification to client.
3409 cbNode->presence->TTLlevel++;
3410 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3411 cbNode->presence->TTLlevel);
3413 OIC_LOG(INFO, TAG, "Before calling into application address space for presence timeout");
3414 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3415 OIC_LOG(INFO, TAG, "After calling into application address space for presence timeout");
3417 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3419 FindAndDeleteClientCB(cbNode);
3424 uint32_t timeout = cbNode->presence->timeOut[cbNode->presence->TTLlevel];
3427 #ifdef WITH_PROCESS_EVENT
3428 if (nextEventTime && (timeout - now) < *nextEventTime)
3430 *nextEventTime = timeout - now;
3432 #endif // WITH_PROCESS_EVENT
3436 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3437 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3438 CARequestInfo_t requestInfo = {.method = CA_GET};
3440 OIC_LOG(DEBUG, TAG, "time to test server presence");
3442 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3444 requestData.type = CA_MSG_NONCONFIRM;
3445 requestData.token = cbNode->token;
3446 requestData.tokenLength = cbNode->tokenLength;
3447 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3448 requestInfo.method = CA_GET;
3449 requestInfo.info = requestData;
3451 result = OCSendRequest(&endpoint, &requestInfo);
3452 if (OC_STACK_OK != result)
3457 cbNode->presence->TTLlevel++;
3458 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3461 if (result != OC_STACK_OK)
3463 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3468 #endif // WITH_PRESENCE
3470 #ifdef WITH_PROCESS_EVENT
3471 OCStackResult OCProcess(void)
3473 uint32_t nextEventTime;
3474 return OCProcessEvent(&nextEventTime);
3477 OCStackResult OCProcessEvent(uint32_t *nextEventTime)
3479 if (stackState == OC_STACK_UNINITIALIZED)
3481 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3482 return OC_STACK_ERROR;
3485 *nextEventTime = UINT32_MAX;
3487 #ifdef WITH_PRESENCE
3488 OCProcessPresence(nextEventTime);
3489 OIC_LOG_V(INFO, TAG, "OCProcessPresence next event time : %u", *nextEventTime);
3491 CAHandleRequestResponse();
3494 #ifdef ROUTING_GATEWAY
3495 RMProcess(nextEventTime);
3499 OCProcessKeepAlive(nextEventTime);
3500 OIC_LOG_V(INFO, TAG, "OCProcessKeepAlive next event time : %u", *nextEventTime);
3505 void OCRegisterProcessEvent(oc_event event)
3507 g_ocProcessEvent = event;
3508 CARegisterProcessEvent(event);
3511 void OCSendProcessEventSignal(void)
3513 if (g_ocProcessEvent)
3515 oc_event_signal(g_ocProcessEvent);
3518 #else // WITH_PROCESS_EVENT
3520 OCStackResult OCProcess()
3522 if (stackState == OC_STACK_UNINITIALIZED)
3524 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3525 return OC_STACK_ERROR;
3527 #ifdef WITH_PRESENCE
3528 OCProcessPresence();
3530 CAHandleRequestResponse();
3532 #ifdef ROUTING_GATEWAY
3537 OCProcessKeepAlive();
3541 #endif // !WITH_PROCESS_EVENT
3543 #ifdef WITH_PRESENCE
3544 OCStackResult OCStartPresence(const uint32_t ttl)
3546 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3547 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3548 OCChangeResourceProperty(
3549 &(((OCResource *)presenceResource.handle)->resourceProperties),
3552 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3554 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3555 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3559 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3560 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3564 presenceResource.presenceTTL = ttl;
3567 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3570 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3572 presenceState = OC_PRESENCE_INITIALIZED;
3574 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3576 CAToken_t caToken = NULL;
3577 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3578 if (caResult != CA_STATUS_OK)
3580 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3581 CADestroyToken(caToken);
3582 return OC_STACK_ERROR;
3585 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3586 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3587 CADestroyToken(caToken);
3590 // Each time OCStartPresence is called
3591 // a different random 32-bit integer number is used
3592 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3594 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3595 OC_PRESENCE_TRIGGER_CREATE);
3598 OCStackResult OCStopPresence()
3600 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3601 OCStackResult result = OC_STACK_ERROR;
3603 if(presenceResource.handle)
3605 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3607 // make resource inactive
3608 result = OCChangeResourceProperty(
3609 &(((OCResource *) presenceResource.handle)->resourceProperties),
3613 if(result != OC_STACK_OK)
3616 "Changing the presence resource properties to ACTIVE not successful");
3620 return SendStopNotification();
3624 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3625 void* callbackParameter)
3627 defaultDeviceHandler = entityHandler;
3628 defaultDeviceHandlerCallbackParameter = callbackParameter;
3633 OCStackResult OCCreateResource(OCResourceHandle *handle,
3634 const char *resourceTypeName,
3635 const char *resourceInterfaceName,
3636 const char *uri, OCEntityHandler entityHandler,
3637 void* callbackParam,
3638 uint8_t resourceProperties)
3641 OCResource *pointer = NULL;
3642 OCStackResult result = OC_STACK_ERROR;
3644 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3646 if(myStackMode == OC_CLIENT)
3648 return OC_STACK_INVALID_PARAM;
3650 // Validate parameters
3651 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3653 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3654 return OC_STACK_INVALID_URI;
3656 // Is it presented during resource discovery?
3657 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3659 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3660 return OC_STACK_INVALID_PARAM;
3663 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3665 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3669 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3671 // Make sure resourceProperties bitmask has allowed properties specified
3672 if (resourceProperties
3673 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3674 OC_EXPLICIT_DISCOVERABLE
3683 OIC_LOG(ERROR, TAG, "Invalid property");
3684 return OC_STACK_INVALID_PARAM;
3687 // If the headResource is NULL, then no resources have been created...
3688 pointer = headResource;
3691 // At least one resources is in the resource list, so we need to search for
3692 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3695 if (pointer->uri && strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3697 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3698 return OC_STACK_INVALID_PARAM;
3700 pointer = pointer->next;
3703 // Create the pointer and insert it into the resource list
3704 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3707 result = OC_STACK_NO_MEMORY;
3710 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3712 insertResource(pointer);
3715 pointer->uri = OICStrdup(uri);
3718 result = OC_STACK_NO_MEMORY;
3722 // Set properties. Set OC_ACTIVE
3723 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3726 // Add the resourcetype to the resource
3727 result = BindResourceTypeToResource(pointer, resourceTypeName);
3728 if (result != OC_STACK_OK)
3730 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3734 // Add the resourceinterface to the resource
3735 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3736 if (result != OC_STACK_OK)
3738 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3742 // If an entity handler has been passed, attach it to the newly created
3743 // resource. Otherwise, set the default entity handler.
3746 pointer->entityHandler = entityHandler;
3747 pointer->entityHandlerCallbackParam = callbackParam;
3751 pointer->entityHandler = defaultResourceEHandler;
3752 pointer->entityHandlerCallbackParam = NULL;
3755 // Initialize a pointer indicating child resources in case of collection
3756 pointer->rsrcChildResourcesHead = NULL;
3759 result = OC_STACK_OK;
3761 #ifdef WITH_PRESENCE
3762 if (presenceResource.handle)
3764 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3765 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3769 if (result != OC_STACK_OK)
3771 // Deep delete of resource and other dynamic elements that it contains
3772 deleteResource(pointer);
3777 OCStackResult OCBindResource(
3778 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3780 OCResource *resource = NULL;
3781 OCChildResource *tempChildResource = NULL;
3782 OCChildResource *newChildResource = NULL;
3784 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3786 // Validate parameters
3787 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3788 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3789 // Container cannot contain itself
3790 if (collectionHandle == resourceHandle)
3792 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3793 return OC_STACK_INVALID_PARAM;
3796 // Use the handle to find the resource in the resource linked list
3797 resource = findResource((OCResource *) collectionHandle);
3800 OIC_LOG(ERROR, TAG, "Collection handle not found");
3801 return OC_STACK_INVALID_PARAM;
3804 // Look for an open slot to add add the child resource.
3805 // If found, add it and return success
3807 tempChildResource = resource->rsrcChildResourcesHead;
3809 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3811 // TODO: what if one of child resource was deregistered without unbinding?
3812 tempChildResource = tempChildResource->next;
3815 // Do memory allocation for child resource
3816 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3817 if(!newChildResource)
3819 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3820 return OC_STACK_ERROR;
3823 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3824 newChildResource->next = NULL;
3826 if(!resource->rsrcChildResourcesHead)
3828 resource->rsrcChildResourcesHead = newChildResource;
3831 tempChildResource->next = newChildResource;
3834 OIC_LOG(INFO, TAG, "resource bound");
3836 #ifdef WITH_PRESENCE
3837 if (presenceResource.handle)
3839 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3840 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3841 OC_PRESENCE_TRIGGER_CHANGE);
3848 OCStackResult OCUnBindResource(
3849 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3851 OCResource *resource = NULL;
3852 OCChildResource *tempChildResource = NULL;
3853 OCChildResource *tempLastChildResource = NULL;
3855 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3857 // Validate parameters
3858 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3859 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3860 // Container cannot contain itself
3861 if (collectionHandle == resourceHandle)
3863 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3864 return OC_STACK_INVALID_PARAM;
3867 // Use the handle to find the resource in the resource linked list
3868 resource = findResource((OCResource *) collectionHandle);
3871 OIC_LOG(ERROR, TAG, "Collection handle not found");
3872 return OC_STACK_INVALID_PARAM;
3875 // Look for an open slot to add add the child resource.
3876 // If found, add it and return success
3877 if(!resource->rsrcChildResourcesHead)
3879 OIC_LOG(INFO, TAG, "resource not found in collection");
3881 // Unable to add resourceHandle, so return error
3882 return OC_STACK_ERROR;
3886 tempChildResource = resource->rsrcChildResourcesHead;
3888 while (tempChildResource)
3890 if(tempChildResource->rsrcResource == resourceHandle)
3892 // if resource going to be unbinded is the head one.
3893 if( tempChildResource == resource->rsrcChildResourcesHead )
3895 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3896 OICFree(resource->rsrcChildResourcesHead);
3897 resource->rsrcChildResourcesHead = temp;
3902 OCChildResource *temp = tempChildResource->next;
3903 OICFree(tempChildResource);
3904 if (tempLastChildResource)
3906 tempLastChildResource->next = temp;
3911 OIC_LOG(INFO, TAG, "resource unbound");
3913 // Send notification when resource is unbounded successfully.
3914 #ifdef WITH_PRESENCE
3915 if (presenceResource.handle)
3917 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3918 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3919 OC_PRESENCE_TRIGGER_CHANGE);
3922 tempChildResource = NULL;
3923 tempLastChildResource = NULL;
3929 tempLastChildResource = tempChildResource;
3930 tempChildResource = tempChildResource->next;
3933 OIC_LOG(INFO, TAG, "resource not found in collection");
3935 tempChildResource = NULL;
3936 tempLastChildResource = NULL;
3938 // Unable to add resourceHandle, so return error
3939 return OC_STACK_ERROR;
3942 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3944 if (!resourceItemName)
3948 // Per RFC 6690 only registered values must follow the first rule below.
3949 // At this point in time the only values registered begin with "core", and
3950 // all other values are specified as opaque strings where multiple values
3951 // are separated by a space.
3952 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3954 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3956 if (resourceItemName[index] != '.'
3957 && resourceItemName[index] != '-'
3958 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3959 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3967 for (size_t index = 0; resourceItemName[index]; ++index)
3969 if (resourceItemName[index] == ' '
3970 || resourceItemName[index] == '\t'
3971 || resourceItemName[index] == '\r'
3972 || resourceItemName[index] == '\n')
3982 OCStackResult BindResourceTypeToResource(OCResource* resource,
3983 const char *resourceTypeName)
3985 OCResourceType *pointer = NULL;
3987 OCStackResult result = OC_STACK_ERROR;
3989 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3991 if (!ValidateResourceTypeInterface(resourceTypeName))
3993 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3994 return OC_STACK_INVALID_PARAM;
3997 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
4000 result = OC_STACK_NO_MEMORY;
4004 str = OICStrdup(resourceTypeName);
4007 result = OC_STACK_NO_MEMORY;
4010 pointer->resourcetypename = str;
4011 pointer->next = NULL;
4013 insertResourceType(resource, pointer);
4014 result = OC_STACK_OK;
4017 if (result != OC_STACK_OK)
4026 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
4027 const char *resourceInterfaceName)
4029 OCResourceInterface *pointer = NULL;
4031 OCStackResult result = OC_STACK_ERROR;
4033 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
4035 if (!ValidateResourceTypeInterface(resourceInterfaceName))
4037 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
4038 return OC_STACK_INVALID_PARAM;
4041 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
4043 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
4046 result = OC_STACK_NO_MEMORY;
4050 str = OICStrdup(resourceInterfaceName);
4053 result = OC_STACK_NO_MEMORY;
4056 pointer->name = str;
4058 // Bind the resourceinterface to the resource
4059 insertResourceInterface(resource, pointer);
4061 result = OC_STACK_OK;
4064 if (result != OC_STACK_OK)
4073 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
4074 const char *resourceTypeName)
4077 OCStackResult result = OC_STACK_ERROR;
4078 OCResource *resource = NULL;
4080 resource = findResource((OCResource *) handle);
4083 OIC_LOG(ERROR, TAG, "Resource not found");
4084 return OC_STACK_ERROR;
4087 result = BindResourceTypeToResource(resource, resourceTypeName);
4089 #ifdef WITH_PRESENCE
4090 if(presenceResource.handle)
4092 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4093 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4100 OCStackResult OCResetResourceTypes(OCResourceHandle handle,
4101 const char *newResourceType)
4103 OCStackResult result = OC_STACK_ERROR;
4104 OCResource *resource = NULL;
4106 resource = findResource((OCResource *) handle);
4109 OIC_LOG(ERROR, TAG, "Resource not found");
4110 return OC_STACK_ERROR;
4113 // Clear all bound resource types
4114 deleteResourceType(resource->rsrcType);
4115 resource->rsrcType = NULL;
4117 // Bind new resource type to resource
4118 result = BindResourceTypeToResource(resource, newResourceType);
4120 #ifdef WITH_PRESENCE
4121 if(presenceResource.handle)
4123 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4124 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4131 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
4132 const char *resourceInterfaceName)
4135 OCStackResult result = OC_STACK_ERROR;
4136 OCResource *resource = NULL;
4138 resource = findResource((OCResource *) handle);
4141 OIC_LOG(ERROR, TAG, "Resource not found");
4142 return OC_STACK_ERROR;
4145 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
4147 #ifdef WITH_PRESENCE
4148 if (presenceResource.handle)
4150 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4151 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4158 OCStackResult OCResetResourceInterfaces(OCResourceHandle handle,
4159 const char *newResourceInterface)
4161 OCStackResult result = OC_STACK_ERROR;
4162 OCResource *resource = NULL;
4164 resource = findResource((OCResource *) handle);
4167 OIC_LOG(ERROR, TAG, "Resource not found");
4168 return OC_STACK_ERROR;
4171 // Clear all bound interface
4172 deleteResourceInterface(resource->rsrcInterface);
4173 resource->rsrcInterface = NULL;
4175 // Bind new interface to resource
4176 result = BindResourceInterfaceToResource(resource, newResourceInterface);
4178 #ifdef WITH_PRESENCE
4179 if (presenceResource.handle)
4181 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4182 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4189 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
4191 OCResource *pointer = headResource;
4193 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
4197 *numResources = *numResources + 1;
4198 pointer = pointer->next;
4203 OCResourceHandle OCGetResourceHandle(uint8_t index)
4205 OCResource *pointer = headResource;
4207 for( uint8_t i = 0; i < index && pointer; ++i)
4209 pointer = pointer->next;
4211 return (OCResourceHandle) pointer;
4214 OCStackResult OCDeleteResource(OCResourceHandle handle)
4218 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4219 return OC_STACK_INVALID_PARAM;
4222 OCResource *resource = findResource((OCResource *) handle);
4223 if (resource == NULL)
4225 OIC_LOG(ERROR, TAG, "Resource not found");
4226 return OC_STACK_NO_RESOURCE;
4229 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4231 OIC_LOG(ERROR, TAG, "Error deleting resource");
4232 return OC_STACK_ERROR;
4238 const char *OCGetResourceUri(OCResourceHandle handle)
4240 OCResource *resource = NULL;
4242 resource = findResource((OCResource *) handle);
4245 return resource->uri;
4247 return (const char *) NULL;
4250 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4252 OCResource *resource = NULL;
4254 resource = findResource((OCResource *) handle);
4257 return resource->resourceProperties;
4259 return (OCResourceProperty)-1;
4262 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4263 uint8_t *numResourceTypes)
4265 OCResource *resource = NULL;
4266 OCResourceType *pointer = NULL;
4268 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4269 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4271 *numResourceTypes = 0;
4273 resource = findResource((OCResource *) handle);
4276 pointer = resource->rsrcType;
4279 *numResourceTypes = *numResourceTypes + 1;
4280 pointer = pointer->next;
4286 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4288 OCResourceType *resourceType = NULL;
4290 resourceType = findResourceTypeAtIndex(handle, index);
4293 return resourceType->resourcetypename;
4295 return (const char *) NULL;
4298 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4299 uint8_t *numResourceInterfaces)
4301 OCResourceInterface *pointer = NULL;
4302 OCResource *resource = NULL;
4304 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4305 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4307 *numResourceInterfaces = 0;
4308 resource = findResource((OCResource *) handle);
4311 pointer = resource->rsrcInterface;
4314 *numResourceInterfaces = *numResourceInterfaces + 1;
4315 pointer = pointer->next;
4321 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4323 OCResourceInterface *resourceInterface = NULL;
4325 resourceInterface = findResourceInterfaceAtIndex(handle, index);
4326 if (resourceInterface)
4328 return resourceInterface->name;
4330 return (const char *) NULL;
4333 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4336 OCResource *resource = NULL;
4337 OCChildResource *tempChildResource = NULL;
4340 resource = findResource((OCResource *) collectionHandle);
4346 tempChildResource = resource->rsrcChildResourcesHead;
4348 while(tempChildResource)
4352 return tempChildResource->rsrcResource;
4355 tempChildResource = tempChildResource->next;
4358 // In this case, the number of resource handles in the collection exceeds the index
4359 tempChildResource = NULL;
4363 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4364 OCEntityHandler entityHandler,
4365 void* callbackParam)
4367 OCResource *resource = NULL;
4369 // Validate parameters
4370 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4372 // Use the handle to find the resource in the resource linked list
4373 resource = findResource((OCResource *)handle);
4376 OIC_LOG(ERROR, TAG, "Resource not found");
4377 return OC_STACK_ERROR;
4381 resource->entityHandler = entityHandler;
4382 resource->entityHandlerCallbackParam = callbackParam;
4384 #ifdef WITH_PRESENCE
4385 if (presenceResource.handle)
4387 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4388 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4395 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4397 OCResource *resource = NULL;
4399 resource = findResource((OCResource *)handle);
4402 OIC_LOG(ERROR, TAG, "Resource not found");
4407 return resource->entityHandler;
4410 void incrementSequenceNumber(OCResource * resPtr)
4412 // Increment the sequence number
4413 resPtr->sequenceNum += 1;
4414 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4416 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4421 #ifdef WITH_PRESENCE
4422 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4423 OCPresenceTrigger trigger)
4425 OIC_LOG(INFO, TAG, "SendPresenceNotification");
4426 OCResource *resPtr = NULL;
4427 OCStackResult result = OC_STACK_ERROR;
4428 OCMethod method = OC_REST_PRESENCE;
4429 uint32_t maxAge = 0;
4430 resPtr = findResource((OCResource *) presenceResource.handle);
4433 return OC_STACK_NO_RESOURCE;
4436 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4438 maxAge = presenceResource.presenceTTL;
4440 result = SendAllObserverNotification(method, resPtr, maxAge,
4441 trigger, resourceType, OC_LOW_QOS);
4447 OCStackResult SendStopNotification()
4449 OIC_LOG(INFO, TAG, "SendStopNotification");
4450 OCResource *resPtr = NULL;
4451 OCStackResult result = OC_STACK_ERROR;
4452 OCMethod method = OC_REST_PRESENCE;
4453 resPtr = findResource((OCResource *) presenceResource.handle);
4456 return OC_STACK_NO_RESOURCE;
4459 // maxAge is 0. ResourceType is NULL.
4460 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4466 #endif // WITH_PRESENCE
4467 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4469 OCResource *resPtr = NULL;
4470 OCStackResult result = OC_STACK_ERROR;
4471 OCMethod method = OC_REST_NOMETHOD;
4472 uint32_t maxAge = 0;
4474 OIC_LOG(INFO, TAG, "Notifying all observers");
4475 #ifdef WITH_PRESENCE
4476 if(handle == presenceResource.handle)
4480 #endif // WITH_PRESENCE
4481 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4483 // Verify that the resource exists
4484 resPtr = findResource ((OCResource *) handle);
4487 return OC_STACK_NO_RESOURCE;
4491 //only increment in the case of regular observing (not presence)
4492 incrementSequenceNumber(resPtr);
4493 method = OC_REST_OBSERVE;
4494 maxAge = MAX_OBSERVE_AGE;
4495 #ifdef WITH_PRESENCE
4496 result = SendAllObserverNotification (method, resPtr, maxAge,
4497 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4499 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4506 OCNotifyListOfObservers (OCResourceHandle handle,
4507 OCObservationId *obsIdList,
4508 uint8_t numberOfIds,
4509 const OCRepPayload *payload,
4510 OCQualityOfService qos)
4512 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4514 OCResource *resPtr = NULL;
4515 //TODO: we should allow the server to define this
4516 uint32_t maxAge = MAX_OBSERVE_AGE;
4518 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4519 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4520 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4522 resPtr = findResource ((OCResource *) handle);
4523 if (NULL == resPtr || myStackMode == OC_CLIENT)
4525 return OC_STACK_NO_RESOURCE;
4529 incrementSequenceNumber(resPtr);
4531 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4532 payload, maxAge, qos));
4535 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4537 OIC_TRACE_BEGIN(%s:OCDoResponse, TAG);
4538 OCStackResult result = OC_STACK_ERROR;
4539 OCServerRequest *serverRequest = NULL;
4541 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4543 // Validate input parameters
4544 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4545 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4548 // Get pointer to request info
4549 serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
4552 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4553 result = serverRequest->ehResponseHandler(ehResponse);
4560 //#ifdef DIRECT_PAIRING
4561 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4563 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4564 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4566 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4570 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4573 const OCDPDev_t* OCGetDirectPairedDevices()
4575 return (const OCDPDev_t*)DPGetPairedDevices();
4578 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4579 OCDirectPairingCB resultCallback)
4581 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4582 if(NULL == peer || NULL == pinNumber)
4584 OIC_LOG(ERROR, TAG, "Invalid parameters");
4585 return OC_STACK_INVALID_PARAM;
4587 if (NULL == resultCallback)
4589 OIC_LOG(ERROR, TAG, "Invalid callback");
4590 return OC_STACK_INVALID_CALLBACK;
4593 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4594 pinNumber, (OCDirectPairingResultCB)resultCallback);
4596 //#endif // DIRECT_PAIRING
4598 //-----------------------------------------------------------------------------
4599 // Private internal function definitions
4600 //-----------------------------------------------------------------------------
4601 static OCDoHandle GenerateInvocationHandle()
4603 OCDoHandle handle = NULL;
4604 // Generate token here, it will be deleted when the transaction is deleted
4605 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4608 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4614 #ifdef WITH_PRESENCE
4615 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4616 OCResourceProperty resourceProperties, uint8_t enable)
4620 return OC_STACK_INVALID_PARAM;
4622 if (resourceProperties
4623 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4625 OIC_LOG(ERROR, TAG, "Invalid property");
4626 return OC_STACK_INVALID_PARAM;
4630 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4634 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4640 OCStackResult initResources()
4642 OCStackResult result = OC_STACK_OK;
4644 headResource = NULL;
4645 tailResource = NULL;
4646 // Init Virtual Resources
4647 #ifdef WITH_PRESENCE
4648 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4650 result = OCCreateResource(&presenceResource.handle,
4651 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4653 OC_RSRVD_PRESENCE_URI,
4657 //make resource inactive
4658 result = OCChangeResourceProperty(
4659 &(((OCResource *) presenceResource.handle)->resourceProperties),
4662 #ifndef WITH_ARDUINO
4663 if (result == OC_STACK_OK)
4665 result = SRMInitSecureResources();
4669 //check SVR DB Validity
4670 OCStackResult validRes = CheckSVRDBValidity();
4672 if( OC_STACK_INCONSISTENT_DB == validRes)
4674 OIC_LOG_V(ERROR, TAG,"%s - SVR DB is not valid!",__func__);
4677 if(result == OC_STACK_OK)
4679 CreateResetProfile();
4680 result = OCCreateResource(&deviceResource,
4681 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4682 OC_RSRVD_INTERFACE_DEFAULT,
4683 OC_RSRVD_DEVICE_URI,
4687 if(result == OC_STACK_OK)
4689 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4690 OC_RSRVD_INTERFACE_READ);
4694 if(result == OC_STACK_OK)
4696 result = OCCreateResource(&platformResource,
4697 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4698 OC_RSRVD_INTERFACE_DEFAULT,
4699 OC_RSRVD_PLATFORM_URI,
4703 if(result == OC_STACK_OK)
4705 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4706 OC_RSRVD_INTERFACE_READ);
4713 void insertResource(OCResource *resource)
4717 headResource = resource;
4718 tailResource = resource;
4722 tailResource->next = resource;
4723 tailResource = resource;
4725 resource->next = NULL;
4728 OCResource *findResource(OCResource *resource)
4730 OCResource *pointer = headResource;
4734 if (pointer == resource)
4738 pointer = pointer->next;
4743 void deleteAllResources()
4745 OCResource *pointer = headResource;
4746 OCResource *temp = NULL;
4750 temp = pointer->next;
4751 #ifdef WITH_PRESENCE
4752 if (pointer != (OCResource *) presenceResource.handle)
4754 #endif // WITH_PRESENCE
4755 deleteResource(pointer);
4756 #ifdef WITH_PRESENCE
4758 #endif // WITH_PRESENCE
4761 memset(&platformResource, 0, sizeof(platformResource));
4762 memset(&deviceResource, 0, sizeof(deviceResource));
4764 memset(&brokerResource, 0, sizeof(brokerResource));
4767 SRMDeInitSecureResources();
4769 #ifdef WITH_PRESENCE
4770 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4771 // presence notification attributed to their deletion to be processed.
4772 deleteResource((OCResource *) presenceResource.handle);
4773 memset(&presenceResource, 0, sizeof(presenceResource));
4774 #endif // WITH_PRESENCE
4777 OCStackResult deleteResource(OCResource *resource)
4779 OCResource *prev = NULL;
4780 OCResource *temp = NULL;
4783 OIC_LOG(DEBUG,TAG,"resource is NULL");
4784 return OC_STACK_INVALID_PARAM;
4787 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4789 temp = headResource;
4792 if (temp == resource)
4794 // Invalidate all Resource Properties.
4795 resource->resourceProperties = (OCResourceProperty) 0;
4796 #ifdef WITH_PRESENCE
4797 if(resource != (OCResource *) presenceResource.handle)
4799 #endif // WITH_PRESENCE
4800 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4801 #ifdef WITH_PRESENCE
4804 if(presenceResource.handle)
4806 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4807 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4810 // Delete resource's all observers
4811 DeleteObserverUsingResource(resource);
4813 // Only resource in list.
4814 if (temp == headResource && temp == tailResource)
4816 headResource = NULL;
4817 tailResource = NULL;
4820 else if (temp == headResource)
4822 headResource = temp->next;
4825 else if (temp == tailResource && prev)
4827 tailResource = prev;
4828 tailResource->next = NULL;
4832 prev->next = temp->next;
4835 deleteResourceElements(temp);
4846 return OC_STACK_ERROR;
4849 void deleteResourceElements(OCResource *resource)
4858 OICFree(resource->uri);
4859 resource->uri = NULL;
4861 if (resource->rsrcType)
4863 deleteResourceType(resource->rsrcType);
4864 resource->rsrcType = NULL;
4866 if (resource->rsrcInterface)
4868 deleteResourceInterface(resource->rsrcInterface);
4869 resource->rsrcInterface = NULL;
4871 if (resource->rsrcChildResourcesHead)
4873 unbindChildResources(resource->rsrcChildResourcesHead);
4874 resource->rsrcChildResourcesHead = NULL;
4876 if (resource->rsrcAttributes)
4878 OCDeleteResourceAttributes(resource->rsrcAttributes);
4879 resource->rsrcAttributes = NULL;
4882 resource->entityHandler = NULL;
4886 void deleteResourceType(OCResourceType *resourceType)
4888 OCResourceType *next = NULL;
4890 for (OCResourceType *pointer = resourceType; pointer; pointer = next)
4892 next = pointer->next ? pointer->next : NULL;
4893 if (pointer->resourcetypename)
4895 OICFree(pointer->resourcetypename);
4896 pointer->resourcetypename = NULL;
4902 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4904 OCResourceInterface *next = NULL;
4905 for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
4907 next = pointer->next ? pointer->next : NULL;
4910 OICFree(pointer->name);
4911 pointer->name = NULL;
4917 void unbindChildResources(OCChildResource *head)
4919 OCChildResource *next = NULL;
4920 for (OCChildResource *current = head; current; current = next)
4922 next = current->next;
4927 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
4929 OCAttribute *next = NULL;
4930 for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
4932 next = pointer->next ? pointer->next : NULL;
4933 if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
4935 OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
4936 pointer->attrValue = NULL;
4938 else if (pointer->attrValue)
4940 OICFree(pointer->attrValue);
4941 pointer->attrValue = NULL;
4943 if (pointer->attrName)
4945 OICFree(pointer->attrName);
4946 pointer->attrName = NULL;
4952 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4954 OCResourceType *pointer = NULL;
4955 OCResourceType *previous = NULL;
4956 if (!resource || !resourceType)
4960 // resource type list is empty.
4961 else if (!resource->rsrcType)
4963 resource->rsrcType = resourceType;
4967 pointer = resource->rsrcType;
4971 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4973 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4974 OICFree(resourceType->resourcetypename);
4975 OICFree(resourceType);
4979 pointer = pointer->next;
4984 previous->next = resourceType;
4987 resourceType->next = NULL;
4989 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4992 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4994 OCResource *resource = NULL;
4995 OCResourceType *pointer = NULL;
4997 // Find the specified resource
4998 resource = findResource((OCResource *) handle);
5004 // Make sure a resource has a resourcetype
5005 if (!resource->rsrcType)
5010 // Iterate through the list
5011 pointer = resource->rsrcType;
5012 for(uint8_t i = 0; i< index && pointer; ++i)
5014 pointer = pointer->next;
5019 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
5021 if(resourceTypeList && resourceTypeName)
5023 OCResourceType * rtPointer = resourceTypeList;
5024 while(resourceTypeName && rtPointer)
5026 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
5027 if(rtPointer->resourcetypename &&
5028 strcmp(resourceTypeName, (const char *)
5029 (rtPointer->resourcetypename)) == 0)
5033 rtPointer = rtPointer->next;
5041 * Insert a new interface into interface linked list only if not already present.
5042 * If alredy present, 2nd arg is free'd.
5043 * Default interface will always be first if present.
5045 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
5047 OCResourceInterface *pointer = NULL;
5048 OCResourceInterface *previous = NULL;
5050 newInterface->next = NULL;
5052 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
5054 if (!*firstInterface)
5056 // If first interface is not oic.if.baseline, by default add it as first interface type.
5057 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
5059 *firstInterface = newInterface;
5063 OCStackResult result = BindResourceInterfaceToResource(resource,
5064 OC_RSRVD_INTERFACE_DEFAULT);
5065 if (result != OC_STACK_OK)
5067 OICFree(newInterface->name);
5068 OICFree(newInterface);
5071 if (*firstInterface)
5073 (*firstInterface)->next = newInterface;
5077 // If once add oic.if.baseline, later too below code take care of freeing memory.
5078 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5080 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5082 OICFree(newInterface->name);
5083 OICFree(newInterface);
5086 // This code will not hit anymore, keeping
5089 newInterface->next = *firstInterface;
5090 *firstInterface = newInterface;
5095 pointer = *firstInterface;
5098 if (strcmp(newInterface->name, pointer->name) == 0)
5100 OICFree(newInterface->name);
5101 OICFree(newInterface);
5105 pointer = pointer->next;
5110 previous->next = newInterface;
5115 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
5118 OCResource *resource = NULL;
5119 OCResourceInterface *pointer = NULL;
5121 // Find the specified resource
5122 resource = findResource((OCResource *) handle);
5128 // Make sure a resource has a resourceinterface
5129 if (!resource->rsrcInterface)
5134 // Iterate through the list
5135 pointer = resource->rsrcInterface;
5137 for (uint8_t i = 0; i < index && pointer; ++i)
5139 pointer = pointer->next;
5145 * This function splits the uri using the '?' delimiter.
5146 * "uriWithoutQuery" is the block of characters between the beginning
5147 * till the delimiter or '\0' which ever comes first.
5148 * "query" is whatever is to the right of the delimiter if present.
5149 * No delimiter sets the query to NULL.
5150 * If either are present, they will be malloc'ed into the params 2, 3.
5151 * The first param, *uri is left untouched.
5153 * NOTE: This function does not account for whitespace at the end of the uri NOR
5154 * malformed uri's with '??'. Whitespace at the end will be assumed to be
5155 * part of the query.
5157 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
5161 return OC_STACK_INVALID_URI;
5163 if(!query || !uriWithoutQuery)
5165 return OC_STACK_INVALID_PARAM;
5169 *uriWithoutQuery = NULL;
5171 size_t uriWithoutQueryLen = 0;
5172 size_t queryLen = 0;
5173 size_t uriLen = strlen(uri);
5175 char *pointerToDelimiter = strstr(uri, "?");
5177 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
5178 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
5180 if (uriWithoutQueryLen)
5182 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
5183 if (!*uriWithoutQuery)
5187 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
5191 *query = (char *) OICCalloc(queryLen + 1, 1);
5194 OICFree(*uriWithoutQuery);
5195 *uriWithoutQuery = NULL;
5198 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5204 return OC_STACK_NO_MEMORY;
5207 const char* OCGetServerInstanceIDString(void)
5209 static char sidStr[UUID_STRING_SIZE];
5211 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5213 OIC_LOG(FATAL, TAG, "GetDoxmDeviceID failed!");
5217 if (OCConvertUuidToString(sid.id, sidStr) != RAND_UUID_OK)
5219 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5226 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5228 OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5229 CAResult_t retResult = CA_STATUS_FAILED;
5230 CAResult_t caResult = CA_STATUS_OK;
5232 CATransportAdapter_t connTypes[] = {
5234 CA_ADAPTER_RFCOMM_BTEDR,
5235 CA_ADAPTER_GATT_BTLE,
5238 ,CA_ADAPTER_REMOTE_ACCESS
5245 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5247 for(int i = 0; i < numConnTypes; i++)
5249 // If CA status is not initialized, CASelectNetwork() will not be called.
5250 if (caResult != CA_STATUS_NOT_INITIALIZED)
5252 if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5254 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5255 caResult = CASelectNetwork(connTypes[i]);
5256 if (caResult == CA_STATUS_OK)
5258 retResult = CA_STATUS_OK;
5263 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5268 if (retResult != CA_STATUS_OK)
5270 return caResult; // Returns error of appropriate transport that failed fatally.
5276 OCStackResult CAResultToOCResult(CAResult_t caResult)
5282 case CA_STATUS_INVALID_PARAM:
5283 return OC_STACK_INVALID_PARAM;
5284 case CA_ADAPTER_NOT_ENABLED:
5285 return OC_STACK_ADAPTER_NOT_ENABLED;
5286 case CA_SERVER_STARTED_ALREADY:
5288 case CA_SERVER_NOT_STARTED:
5289 return OC_STACK_ERROR;
5290 case CA_DESTINATION_NOT_REACHABLE:
5291 return OC_STACK_COMM_ERROR;
5292 case CA_SOCKET_OPERATION_FAILED:
5293 return OC_STACK_COMM_ERROR;
5294 case CA_SEND_FAILED:
5295 return OC_STACK_COMM_ERROR;
5296 case CA_RECEIVE_FAILED:
5297 return OC_STACK_COMM_ERROR;
5298 case CA_MEMORY_ALLOC_FAILED:
5299 return OC_STACK_NO_MEMORY;
5300 case CA_REQUEST_TIMEOUT:
5301 return OC_STACK_TIMEOUT;
5302 case CA_DESTINATION_DISCONNECTED:
5303 return OC_STACK_COMM_ERROR;
5304 case CA_STATUS_FAILED:
5305 return OC_STACK_ERROR;
5306 case CA_NOT_SUPPORTED:
5307 return OC_STACK_NOTIMPL;
5309 return OC_STACK_ERROR;
5313 bool OCResultToSuccess(OCStackResult ocResult)
5318 case OC_STACK_RESOURCE_CREATED:
5319 case OC_STACK_RESOURCE_DELETED:
5320 case OC_STACK_CONTINUE:
5321 case OC_STACK_RESOURCE_CHANGED:
5322 case OC_STACK_SLOW_RESOURCE:
5330 OCStackResult OCSetProxyURI(const char *uri)
5332 return CAResultToOCResult(CASetProxyUri(uri));
5336 #if defined(RD_CLIENT) || defined(RD_SERVER)
5337 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5339 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5341 OCResource *resource = NULL;
5343 resource = findResource((OCResource *) handle);
5346 OIC_LOG(ERROR, TAG, "Resource not found");
5347 return OC_STACK_ERROR;
5350 resource->ins = ins;
5356 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5357 const OCClientResponse *response)
5359 // Validate input parameters
5360 VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5361 VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5363 char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5366 return OC_STACK_NO_MEMORY;
5368 strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5370 if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5372 OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5374 char rdPubUri[MAX_URI_LENGTH] = { 0 };
5375 snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5376 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5378 if (strcmp(rdPubUri, targetUri) == 0)
5380 // Update resource unique id in stack.
5381 if (response->payload)
5383 OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5384 OCRepPayload **links = NULL;
5385 size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5386 if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5387 &links, dimensions))
5390 for (; i < dimensions[0]; i++)
5393 if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5395 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5397 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5399 OCBindResourceInsToResource(handle, ins);
5408 size_t count = calcDimTotal(dimensions);
5409 for (size_t k = 0; k < count; k++)
5411 OCRepPayloadDestroy(links[k]);
5418 else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5420 OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5422 uint8_t numResources = 0;
5423 OCGetNumberOfResources(&numResources);
5425 char *ins = strstr(targetUri, OC_RSRVD_INS);
5428 for (uint8_t i = 0; i < numResources; i++)
5430 OCResourceHandle resHandle = OCGetResourceHandle(i);
5433 OCBindResourceInsToResource(resHandle, 0);
5439 const char *token = "&";
5440 char *iterTokenPtr = NULL;
5441 char *start = strtok_r(targetUri, token, &iterTokenPtr);
5443 while (start != NULL)
5445 char *query = start;
5446 query = strstr(query, OC_RSRVD_INS);
5449 int64_t queryIns = atoi(query + 4);
5450 for (uint8_t i = 0; i < numResources; i++)
5452 OCResourceHandle resHandle = OCGetResourceHandle(i);
5456 OCGetResourceIns(resHandle, &resIns);
5457 if (queryIns && queryIns == resIns)
5459 OCBindResourceInsToResource(resHandle, 0);
5465 start = strtok_r(NULL, token, &iterTokenPtr);
5474 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5478 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5482 OCResource *pointer = headResource;
5486 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5488 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5491 pointer = pointer->next;
5496 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t *ins)
5498 OCResource *resource = NULL;
5500 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5501 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5503 resource = findResource((OCResource *) handle);
5506 *ins = resource->ins;
5509 return OC_STACK_ERROR;
5513 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5514 const void* optionData, size_t optionDataLength)
5518 OIC_LOG (INFO, TAG, "Header options are NULL");
5519 return OC_STACK_INVALID_PARAM;
5524 OIC_LOG (INFO, TAG, "optionData are NULL");
5525 return OC_STACK_INVALID_PARAM;
5530 OIC_LOG (INFO, TAG, "numOptions is NULL");
5531 return OC_STACK_INVALID_PARAM;
5534 if (*numOptions >= MAX_HEADER_OPTIONS)
5536 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5537 return OC_STACK_NO_MEMORY;
5540 ocHdrOpt += *numOptions;
5541 ocHdrOpt->protocolID = OC_COAP_ID;
5542 ocHdrOpt->optionID = optionID;
5543 ocHdrOpt->optionLength =
5544 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
5545 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5546 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5552 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5553 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5555 if (!ocHdrOpt || !numOptions)
5557 OIC_LOG (INFO, TAG, "No options present");
5563 OIC_LOG (INFO, TAG, "optionData are NULL");
5564 return OC_STACK_INVALID_PARAM;
5567 if (!receivedDataLength)
5569 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5570 return OC_STACK_INVALID_PARAM;
5573 for (uint8_t i = 0; i < numOptions; i++)
5575 if (ocHdrOpt[i].optionID == optionID)
5577 if (optionDataLength >= ocHdrOpt->optionLength)
5579 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5580 *receivedDataLength = ocHdrOpt->optionLength;
5585 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5586 return OC_STACK_ERROR;
5593 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5595 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5601 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5603 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5606 * If the client observes one or more resources over a reliable connection,
5607 * then the CoAP server (or intermediary in the role of the CoAP server)
5608 * MUST remove all entries associated with the client endpoint from the lists
5609 * of observers when the connection is either closed or times out.
5613 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5614 CopyEndpointToDevAddr(info, &devAddr);
5616 // remove observer list with remote device address.
5617 DeleteObserverUsingDevAddr(&devAddr);
5621 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5624 OCStackResult ret = OC_STACK_ERROR;
5626 ret = GetDoxmDeviceID(&oicUuid);
5627 if (OC_STACK_OK == ret)
5629 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5633 OIC_LOG(ERROR, TAG, "Device ID Get error");
5638 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5641 OCStackResult ret = OC_STACK_ERROR;
5643 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5644 for (int i = 0; i < UUID_LENGTH; i++)
5646 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5648 ret = SetDoxmDeviceID(&oicUuid);
5652 OCStackResult OCSetDeviceIdResetPF(const OCUUIdentity *deviceId)
5655 OCStackResult ret = OC_STACK_ERROR;
5657 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5658 char *strUuid = NULL;
5659 if (OC_STACK_OK == ConvertUuidToStr(&oicUuid, &strUuid))
5661 OIC_LOG_V(INFO, TAG, "%s: deviceId : %s" ,__func__, strUuid);
5666 OIC_LOG(DEBUG, TAG, "Can't convert deviceId to string");
5668 ret = SetDoxmDeviceIDResetPF(&oicUuid);
5672 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5674 bool isDeviceOwned = true;
5675 OCStackResult ret = OC_STACK_ERROR;
5677 ret = GetDoxmIsOwned(&isDeviceOwned);
5678 if (OC_STACK_OK == ret)
5680 *isOwned = isDeviceOwned;
5684 OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5689 OCStackResult OCGetDeviceOperationalState(bool* isOp)
5693 *isOp = GetPstatIsop();
5697 return OC_STACK_ERROR;
5700 void OCClearCallBackList()
5702 DeleteClientCBList();
5705 void OCClearObserverlist()
5707 DeleteObserverList();
5710 int OCEncrypt(const unsigned char *pt, size_t pt_len,
5711 unsigned char **ct, size_t *ct_len)
5713 #ifndef __SECURE_PSI__
5714 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5717 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5719 return psiEncrypt(pt, pt_len, ct, ct_len);
5720 #endif // __SECURE_PSI__
5723 int OCDecrypt(const unsigned char *ct, size_t ct_len,
5724 unsigned char **pt, size_t *pt_len)
5726 #ifndef __SECURE_PSI__
5727 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5730 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5732 return psiDecrypt(ct, ct_len, pt, pt_len);
5733 #endif // __SECURE_PSI__
5736 OCStackResult OCSetKey(const unsigned char* key)
5738 #ifndef __SECURE_PSI__
5739 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5742 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5744 return psiSetKey(key);
5745 #endif // __SECURE_PSI__
5748 OCStackResult OCGetKey(unsigned char* key)
5750 #ifndef __SECURE_PSI__
5751 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5754 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5756 return psiGetKey(key);
5757 #endif // __SECURE_PSI__
5760 OCStackResult OCSetSecurePSI(const unsigned char *key, const OCPersistentStorage *psPlain,
5761 const OCPersistentStorage *psEnc, const OCPersistentStorage *psRescue)
5763 #ifndef __SECURE_PSI__
5764 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5767 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5769 return setSecurePSI(key, psPlain, psEnc, psRescue);
5770 #endif // __SECURE_PSI__
5773 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5774 static void OtmEventHandler(const char *addr, uint16_t port, const char *uuid, int event)
5776 if (g_otmEventHandler.cb)
5778 g_otmEventHandler.cb(g_otmEventHandler.ctx, addr, port, uuid, event);
5783 * It is already declared in srmutility.h.
5784 * We can't include the header file, because of "redefined VERIFY_NON_NULL"
5786 typedef void (*OicSecOtmEventHandler_t)(const char* addr, uint16_t port,
5787 const char* uuid, int event);
5788 void SetOtmEventHandler(OicSecOtmEventHandler_t otmEventHandler);
5791 OCStackResult OCSetOtmEventHandler(void *ctx, OCOtmEventHandler cb)
5793 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5794 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5796 g_otmEventHandler.cb = cb;
5797 g_otmEventHandler.ctx = ctx;
5799 if (g_otmEventHandler.cb)
5801 OIC_LOG(DEBUG, TAG, "SET OCOtmEventHandler");
5802 SetOtmEventHandler(OtmEventHandler);
5806 OIC_LOG(DEBUG, TAG, "UNSET OCOtmEventHandler");
5807 SetOtmEventHandler(NULL);
5810 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);