1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //-----------------------------------------------------------------------------
24 //-----------------------------------------------------------------------------
26 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
27 // causes header files to expose definitions
28 // corresponding to the POSIX.1-2001 base
29 // specification (excluding the XSI extension).
30 // For POSIX.1-2001 base specification,
31 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
32 #define _POSIX_C_SOURCE 200112L
33 #ifndef __STDC_FORMAT_MACROS
34 #define __STDC_FORMAT_MACROS
36 #ifndef __STDC_LIMIT_MACROS
37 #define __STDC_LIMIT_MACROS
39 #include "iotivity_config.h"
45 #include "ocstackinternal.h"
46 #include "ocresourcehandler.h"
47 #include "occlientcb.h"
48 #include "ocobserve.h"
50 #include "oic_malloc.h"
51 #include "oic_string.h"
54 #include "ocserverrequest.h"
55 #include "secureresourcemanager.h"
56 #include "psinterface.h"
58 #include "doxmresource.h"
60 #include "cainterface.h"
61 #include "ocpayload.h"
62 #include "ocpayloadcbor.h"
63 #include "cautilinterface.h"
66 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
67 #include "routingutility.h"
68 #ifdef ROUTING_GATEWAY
69 #include "routingmanager.h"
74 #include "oickeepaliveinternal.h"
77 //#ifdef DIRECT_PAIRING
78 #include "directpairing.h"
81 #ifdef HAVE_ARDUINO_TIME_H
84 #ifdef HAVE_SYS_TIME_H
87 #include <coap/coap.h>
89 #ifdef HAVE_ARPA_INET_H
90 #include <arpa/inet.h>
94 #define UINT32_MAX (0xFFFFFFFFUL)
97 //-----------------------------------------------------------------------------
99 //-----------------------------------------------------------------------------
102 OC_STACK_UNINITIALIZED = 0,
103 OC_STACK_INITIALIZED,
104 OC_STACK_UNINIT_IN_PROGRESS
110 OC_PRESENCE_UNINITIALIZED = 0,
111 OC_PRESENCE_INITIALIZED
115 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
118 OCOtmEventHandler cb;
120 } OCOtmEventHandler_t;
123 //-----------------------------------------------------------------------------
125 //-----------------------------------------------------------------------------
126 static OCStackState stackState = OC_STACK_UNINITIALIZED;
128 OCResource *headResource = NULL;
129 static OCResource *tailResource = NULL;
130 static OCResourceHandle platformResource = {0};
131 static OCResourceHandle deviceResource = {0};
133 static OCResourceHandle brokerResource = {0};
137 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
138 static PresenceResource presenceResource = {0};
139 static uint8_t PresenceTimeOutSize = 0;
140 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
143 static OCMode myStackMode;
145 //TODO: revisit this design
146 static bool gRASetInfo = false;
148 OCDeviceEntityHandler defaultDeviceHandler;
149 void* defaultDeviceHandlerCallbackParameter = NULL;
150 static const char COAP_TCP_SCHEME[] = "coap+tcp:";
151 static const char COAPS_TCP_SCHEME[] = "coaps+tcp:";
152 static const char CORESPEC[] = "core";
154 CAAdapterStateChangedCB g_adapterHandler = NULL;
155 CAConnectionStateChangedCB g_connectionHandler = NULL;
157 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
158 static OCOtmEventHandler_t g_otmEventHandler = {NULL, NULL};
161 //-----------------------------------------------------------------------------
163 //-----------------------------------------------------------------------------
164 #define TAG "OIC_RI_STACK"
165 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
166 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
167 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
168 TAG, #arg " is NULL"); return (retVal); } }
169 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
170 TAG, #arg " is NULL"); return; } }
171 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
174 //TODO: we should allow the server to define this
175 #define MAX_OBSERVE_AGE (0x2FFFFUL)
177 #define MILLISECONDS_PER_SECOND (1000)
179 //-----------------------------------------------------------------------------
180 // Private internal function prototypes
181 //-----------------------------------------------------------------------------
184 * Generate handle of OCDoResource invocation for callback management.
186 * @return Generated OCDoResource handle.
188 static OCDoHandle GenerateInvocationHandle();
191 * Initialize resource data structures, variables, etc.
193 * @return ::OC_STACK_OK on success, some other value upon failure.
195 static OCStackResult initResources();
198 * Add a resource to the end of the linked list of resources.
200 * @param resource Resource to be added
202 static void insertResource(OCResource *resource);
205 * Find a resource in the linked list of resources.
207 * @param resource Resource to be found.
208 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
211 static OCResource *findResource(OCResource *resource);
214 * Insert a resource type into a resource's resource type linked list.
215 * If resource type already exists, it will not be inserted and the
216 * resourceType will be free'd.
217 * resourceType->next should be null to avoid memory leaks.
218 * Function returns silently for null args.
220 * @param resource Resource where resource type is to be inserted.
221 * @param resourceType Resource type to be inserted.
223 static void insertResourceType(OCResource *resource,
224 OCResourceType *resourceType);
227 * Get a resource type at the specified index within a resource.
229 * @param handle Handle of resource.
230 * @param index Index of resource type.
232 * @return Pointer to resource type if found, NULL otherwise.
234 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
238 * Insert a resource interface into a resource's resource interface linked list.
239 * If resource interface already exists, it will not be inserted and the
240 * resourceInterface will be free'd.
241 * resourceInterface->next should be null to avoid memory leaks.
243 * @param resource Resource where resource interface is to be inserted.
244 * @param resourceInterface Resource interface to be inserted.
246 static void insertResourceInterface(OCResource *resource,
247 OCResourceInterface *resourceInterface);
250 * Get a resource interface at the specified index within a resource.
252 * @param handle Handle of resource.
253 * @param index Index of resource interface.
255 * @return Pointer to resource interface if found, NULL otherwise.
257 static OCResourceInterface *findResourceInterfaceAtIndex(
258 OCResourceHandle handle, uint8_t index);
261 * Delete all of the dynamically allocated elements that were created for the resource type.
263 * @param resourceType Specified resource type.
265 static void deleteResourceType(OCResourceType *resourceType);
268 * Delete all of the dynamically allocated elements that were created for the resource interface.
270 * @param resourceInterface Specified resource interface.
272 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
275 * Delete all child resources.
277 * @param resourceChild Specified binded resource is deleted from parent.
279 static void deleteResourceChild(OCChildResource *resourceChild);
282 * Delete all of the dynamically allocated elements that were created for the resource.
284 * @param resource Specified resource.
286 static void deleteResourceElements(OCResource *resource);
289 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
292 * @param handle Handle of resource to be deleted.
294 * @return ::OC_STACK_OK on success, some other value upon failure.
296 static OCStackResult deleteResource(OCResource *resource);
299 * Delete all of the resources in the resource list.
301 static void deleteAllResources();
304 * Increment resource sequence number. Handles rollover.
306 * @param resPtr Pointer to resource.
308 static void incrementSequenceNumber(OCResource * resPtr);
311 * Attempts to initialize every network interface that the CA Layer might have compiled in.
313 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
314 * return something other than @ref CA_STATUS_OK, then this function fails.
315 * @param transportType OCTransportAdapter value to select.
316 * @return ::CA_STATUS_OK on success, some other value upon failure.
318 static CAResult_t OCSelectNetwork(OCTransportAdapter transportType);
321 * Convert CAResponseResult_t to OCStackResult.
323 * @param caCode CAResponseResult_t code.
324 * @return ::OC_STACK_OK on success, some other value upon failure.
326 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
329 * Convert OCTransportFlags_t to CATransportModifiers_t.
331 * @param ocConType OCTransportFlags_t input.
332 * @return CATransportFlags
334 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
337 * Convert CATransportFlags_t to OCTransportModifiers_t.
339 * @param caConType CATransportFlags_t input.
340 * @return OCTransportFlags
342 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
345 * Handle response from presence request.
347 * @param endPoint CA remote endpoint.
348 * @param responseInfo CA response info.
349 * @return ::OC_STACK_OK on success, some other value upon failure.
351 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
352 const CAResponseInfo_t *responseInfo);
355 * This function will be called back by CA layer when a response is received.
357 * @param endPoint CA remote endpoint.
358 * @param responseInfo CA response info.
360 static void HandleCAResponses(const CAEndpoint_t* endPoint,
361 const CAResponseInfo_t* responseInfo);
364 * This function will be called back by CA layer when a request is received.
366 * @param endPoint CA remote endpoint.
367 * @param requestInfo CA request info.
369 static void HandleCARequests(const CAEndpoint_t* endPoint,
370 const CARequestInfo_t* requestInfo);
373 * Extract query from a URI.
375 * @param uri Full URI with query.
376 * @param query Pointer to string that will contain query.
377 * @param newURI Pointer to string that will contain URI.
378 * @return ::OC_STACK_OK on success, some other value upon failure.
380 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
383 * Finds a resource type in an OCResourceType link-list.
385 * @param resourceTypeList The link-list to be searched through.
386 * @param resourceTypeName The key to search for.
388 * @return Resource type that matches the key (ie. resourceTypeName) or
389 * NULL if there is either an invalid parameter or this function was unable to find the key.
391 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
392 const char * resourceTypeName);
396 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
397 * TTL will be set to maxAge.
399 * @param cbNode Callback Node for which presence ttl is to be reset.
400 * @param maxAge New value of ttl in seconds.
402 * @return ::OC_STACK_OK on success, some other value upon failure.
404 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
408 * Ensure the accept header option is set appropriatly before sending the requests and routing
409 * header option is updated with destination.
411 * @param object CA remote endpoint.
412 * @param requestInfo CA request info.
414 * @return ::OC_STACK_OK on success, some other value upon failure.
416 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
419 * default adapter state change callback method
421 * @param adapter CA network adapter type.
422 * @param enabled current adapter state.
424 static void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled);
427 * default connection state change callback method
429 * @param info CAEndpoint which has address, port and etc.
430 * @param isConnected current connection state.
432 static void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected);
435 * Register network monitoring callback.
436 * Network status changes are delivered these callback.
437 * @param adapterHandler Adapter state monitoring callback.
438 * @param connectionHandler Connection state monitoring callback.
440 static void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
441 CAConnectionStateChangedCB connectionHandler);
443 //-----------------------------------------------------------------------------
444 // Internal functions
445 //-----------------------------------------------------------------------------
447 bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
449 if (!options || 0 == numOptions)
451 OIC_LOG (INFO, TAG, "No options present");
455 for (uint8_t i = 0; i < numOptions; i++)
457 if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
459 OIC_LOG(DEBUG, TAG, "Proxy URI is present");
466 uint32_t GetTicks(uint32_t milliSeconds)
471 // Guard against overflow of uint32_t
472 if (milliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
473 COAP_TICKS_PER_SECOND)
475 return now + (milliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
483 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
485 VERIFY_NON_NULL_NR(in, FATAL);
486 VERIFY_NON_NULL_NR(out, FATAL);
488 out->adapter = (OCTransportAdapter)in->adapter;
489 out->flags = CAToOCTransportFlags(in->flags);
490 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
491 out->port = in->port;
492 out->ifindex = in->ifindex;
493 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
494 /* This assert is to prevent accidental mismatch between address size macros defined in
495 * RI and CA and cause crash here. */
496 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
497 "Address size mismatch between RI and CA");
498 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
502 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
504 VERIFY_NON_NULL_NR(in, FATAL);
505 VERIFY_NON_NULL_NR(out, FATAL);
507 out->adapter = (CATransportAdapter_t)in->adapter;
508 out->flags = OCToCATransportFlags(in->flags);
509 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
510 OICStrcpy(out->remoteId, sizeof(out->remoteId), in->remoteId);
511 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
512 /* This assert is to prevent accidental mismatch between address size macros defined in
513 * RI and CA and cause crash here. */
514 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
515 "Address size mismatch between RI and CA");
516 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
518 out->port = in->port;
519 out->ifindex = in->ifindex;
522 void FixUpClientResponse(OCClientResponse *cr)
524 VERIFY_NON_NULL_NR(cr, FATAL);
526 cr->addr = &cr->devAddr;
527 cr->connType = (OCConnectivityType)
528 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
531 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
533 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
534 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
535 OIC_TRACE_BEGIN(%s:OCSendRequest, TAG);
537 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
538 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
539 if (OC_STACK_OK != rmResult)
541 OIC_LOG(ERROR, TAG, "Add destination option failed");
547 // OC stack prefer CBOR encoded payloads.
548 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
549 CAResult_t result = CASendRequest(object, requestInfo);
550 if(CA_STATUS_OK != result)
552 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
554 return CAResultToOCResult(result);
560 //-----------------------------------------------------------------------------
561 // Internal API function
562 //-----------------------------------------------------------------------------
564 // This internal function is called to update the stack with the status of
565 // observers and communication failures
566 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
568 OCStackResult result = OC_STACK_ERROR;
569 ResourceObserver * observer = NULL;
570 OCEntityHandlerRequest ehRequest = {0};
574 case OC_OBSERVER_NOT_INTERESTED:
575 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
576 observer = GetObserverUsingToken(token, tokenLength);
579 result = FormOCEntityHandlerRequest(&ehRequest,
583 (OCResourceHandle)NULL,
584 NULL, PAYLOAD_TYPE_REPRESENTATION,
586 OC_OBSERVE_DEREGISTER,
589 if (result != OC_STACK_OK)
591 FreeObserver(observer);
595 if (observer->resource && observer->resource->entityHandler)
597 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
598 observer->resource->entityHandlerCallbackParam);
601 FreeObserver(observer);
604 result = DeleteObserverUsingToken(token, tokenLength);
605 if (result == OC_STACK_OK)
607 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
611 result = OC_STACK_OK;
612 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
616 case OC_OBSERVER_STILL_INTERESTED:
617 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
618 observer = GetObserverUsingToken(token, tokenLength);
621 observer->forceHighQos = 0;
622 observer->failedCommCount = 0;
623 result = OC_STACK_OK;
624 FreeObserver(observer);
628 result = OC_STACK_OBSERVER_NOT_FOUND;
632 case OC_OBSERVER_FAILED_COMM:
633 OIC_LOG(DEBUG, TAG, "observer is unreachable");
634 observer = GetObserverUsingToken (token, tokenLength);
637 if (observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
639 result = FormOCEntityHandlerRequest(&ehRequest,
643 (OCResourceHandle)NULL,
644 NULL, PAYLOAD_TYPE_REPRESENTATION,
646 OC_OBSERVE_DEREGISTER,
649 if (result != OC_STACK_OK)
651 FreeObserver(observer);
652 return OC_STACK_ERROR;
655 if (observer->resource && observer->resource->entityHandler)
657 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
658 observer->resource->entityHandlerCallbackParam);
661 result = DeleteObserverUsingToken(token, tokenLength);
662 if (result == OC_STACK_OK)
664 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
668 result = OC_STACK_OK;
669 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
674 observer->failedCommCount++;
675 observer->forceHighQos = 1;
676 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",
677 observer->failedCommCount);
678 result = OC_STACK_CONTINUE;
681 FreeObserver(observer);
685 OIC_LOG(ERROR, TAG, "Unknown status");
686 result = OC_STACK_ERROR;
692 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
694 OCStackResult ret = OC_STACK_ERROR;
698 ret = OC_STACK_RESOURCE_CREATED;
701 ret = OC_STACK_RESOURCE_DELETED;
704 ret = OC_STACK_RESOURCE_CHANGED;
711 ret = OC_STACK_INVALID_QUERY;
713 case CA_UNAUTHORIZED_REQ:
714 ret = OC_STACK_UNAUTHORIZED_REQ;
717 ret = OC_STACK_INVALID_OPTION;
720 ret = OC_STACK_NO_RESOURCE;
722 case CA_REQUEST_ENTITY_TOO_LARGE:
723 ret = OC_STACK_TOO_LARGE_REQ;
725 case CA_METHOD_NOT_ALLOWED:
726 ret = OC_STACK_METHOD_NOT_ALLOWED;
728 case CA_NOT_ACCEPTABLE:
729 ret = OC_STACK_NOT_ACCEPTABLE;
731 case CA_FORBIDDEN_REQ:
732 ret = OC_STACK_FORBIDDEN_REQ;
734 case CA_INTERNAL_SERVER_ERROR:
735 ret = OC_STACK_INTERNAL_SERVER_ERROR;
737 case CA_NOT_IMPLEMENTED:
738 ret = OC_STACK_NOT_IMPLEMENTED;
741 ret = OC_STACK_BAD_GATEWAY;
743 case CA_SERVICE_UNAVAILABLE:
744 ret = OC_STACK_SERVICE_UNAVAILABLE;
746 case CA_RETRANSMIT_TIMEOUT:
747 ret = OC_STACK_GATEWAY_TIMEOUT;
749 case CA_PROXY_NOT_SUPPORTED:
750 ret = OC_STACK_PROXY_NOT_SUPPORTED;
758 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
760 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
769 // This Response Code is like HTTP 204 "No Content" but only used in
770 // response to POST and PUT requests.
774 // This Response Code is like HTTP 200 "OK" but only used in response to
779 // This should not happen but,
780 // give it a value just in case but output an error
782 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
786 case OC_STACK_RESOURCE_CREATED:
789 case OC_STACK_RESOURCE_DELETED:
792 case OC_STACK_RESOURCE_CHANGED:
795 case OC_STACK_INVALID_QUERY:
798 case OC_STACK_INVALID_OPTION:
801 case OC_STACK_NO_RESOURCE:
804 case OC_STACK_COMM_ERROR:
805 ret = CA_RETRANSMIT_TIMEOUT;
807 case OC_STACK_METHOD_NOT_ALLOWED:
808 ret = CA_METHOD_NOT_ALLOWED;
810 case OC_STACK_NOT_ACCEPTABLE:
811 ret = CA_NOT_ACCEPTABLE;
813 case OC_STACK_UNAUTHORIZED_REQ:
814 ret = CA_UNAUTHORIZED_REQ;
816 case OC_STACK_FORBIDDEN_REQ:
817 ret = CA_FORBIDDEN_REQ;
819 case OC_STACK_INTERNAL_SERVER_ERROR:
820 ret = CA_INTERNAL_SERVER_ERROR;
822 case OC_STACK_NOT_IMPLEMENTED:
823 ret = CA_NOT_IMPLEMENTED;
825 case OC_STACK_BAD_GATEWAY:
826 ret = CA_BAD_GATEWAY;
828 case OC_STACK_SERVICE_UNAVAILABLE:
829 ret = CA_SERVICE_UNAVAILABLE;
831 case OC_STACK_GATEWAY_TIMEOUT:
832 ret = CA_RETRANSMIT_TIMEOUT;
834 case OC_STACK_PROXY_NOT_SUPPORTED:
835 ret = CA_PROXY_NOT_SUPPORTED;
843 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
845 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
847 // supply default behavior.
848 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
850 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
852 if ((caFlags & OC_MASK_SCOPE) == 0)
854 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
859 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
861 return (OCTransportFlags)caFlags;
865 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
867 uint32_t lowerBound = 0;
868 uint32_t higherBound = 0;
870 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
872 return OC_STACK_INVALID_PARAM;
875 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
877 cbNode->presence->TTL = maxAgeSeconds;
879 for (int index = 0; index < PresenceTimeOutSize; index++)
881 // Guard against overflow
882 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
885 lowerBound = GetTicks((PresenceTimeOut[index] *
886 cbNode->presence->TTL *
887 MILLISECONDS_PER_SECOND)/100);
891 lowerBound = GetTicks(UINT32_MAX);
894 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
897 higherBound = GetTicks((PresenceTimeOut[index + 1] *
898 cbNode->presence->TTL *
899 MILLISECONDS_PER_SECOND)/100);
903 higherBound = GetTicks(UINT32_MAX);
906 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
908 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
909 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
910 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
913 cbNode->presence->TTLlevel = 0;
915 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
919 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
921 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
923 return OC_RSRVD_TRIGGER_CREATE;
925 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
927 return OC_RSRVD_TRIGGER_CHANGE;
931 return OC_RSRVD_TRIGGER_DELETE;
935 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
939 return OC_PRESENCE_TRIGGER_CREATE;
941 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
943 return OC_PRESENCE_TRIGGER_CREATE;
945 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
947 return OC_PRESENCE_TRIGGER_CHANGE;
951 return OC_PRESENCE_TRIGGER_DELETE;
954 #endif // WITH_PRESENCE
956 OCStackResult OCEncodeAddressForRFC6874(char *outputAddress,
958 const char *inputAddress)
960 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
961 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
963 size_t inputLength = strnlen(inputAddress, outputSize);
965 // inputSize includes the null terminator
966 size_t inputSize = inputLength + 1;
968 if (inputSize > outputSize)
970 OIC_LOG_V(ERROR, TAG,
971 "OCEncodeAddressForRFC6874 failed: "
972 "outputSize (%zu) < inputSize (%zu)",
973 outputSize, inputSize);
975 return OC_STACK_ERROR;
978 char* percentChar = strchr(inputAddress, '%');
980 // If there is no '%' character, then no change is required to the string.
981 if (NULL == percentChar)
983 OICStrcpy(outputAddress, outputSize, inputAddress);
987 const char* addressPart = &inputAddress[0];
988 const char* scopeIdPart = percentChar + 1;
990 // Sanity check to make sure this string doesn't have more '%' characters
991 if (NULL != strchr(scopeIdPart, '%'))
993 return OC_STACK_ERROR;
996 // If no string follows the first '%', then the input was invalid.
997 if (scopeIdPart[0] == '\0')
999 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
1000 return OC_STACK_ERROR;
1003 // Check to see if the string is already encoded
1004 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
1006 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Input string is already encoded");
1007 return OC_STACK_ERROR;
1010 // Fail if we don't have room for encoded string's two additional chars
1011 if (outputSize < (inputSize + 2))
1013 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: encoded output will not fit!");
1014 return OC_STACK_ERROR;
1017 // Restore the null terminator with an escaped '%' character, per RFC 6874
1018 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
1019 OICStrcat(outputAddress, outputSize, "%25");
1020 OICStrcat(outputAddress, outputSize, scopeIdPart);
1025 OCStackResult OCDecodeAddressForRFC6874(char *outputAddress,
1027 const char *inputAddress,
1030 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
1031 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
1035 end = inputAddress + strlen(inputAddress);
1037 size_t inputLength = end - inputAddress;
1039 const char *percent = strchr(inputAddress, '%');
1040 if (!percent || (percent > end))
1042 OICStrcpyPartial(outputAddress, outputSize, inputAddress, inputLength);
1046 if (percent[1] != '2' || percent[2] != '5')
1048 return OC_STACK_INVALID_URI;
1051 int addrlen = percent - inputAddress + 1;
1052 OICStrcpyPartial(outputAddress, outputSize, inputAddress, addrlen);
1053 OICStrcpyPartial(outputAddress + addrlen, outputSize - addrlen,
1054 percent + 3, end - percent - 3);
1060 #ifdef WITH_PRESENCE
1062 * The cononical presence allows constructed URIs to be string compared.
1064 * requestUri must be a char array of size CA_MAX_URI_LENGTH
1066 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
1067 char *presenceUri, bool isMulticast)
1069 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
1070 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1074 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1075 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1078 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1079 if (ep->adapter == CA_ADAPTER_IP)
1081 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1083 if ('\0' == ep->addr[0]) // multicast
1085 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1089 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1091 OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1092 sizeof(addressEncoded),
1095 if (OC_STACK_OK != result)
1100 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1101 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1106 if ('\0' == ep->addr[0]) // multicast
1108 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1109 ep->port = OC_MULTICAST_PORT;
1111 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1112 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1116 // might work for other adapters (untested, but better than nothing)
1117 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1118 OC_RSRVD_PRESENCE_URI);
1122 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1123 const CAResponseInfo_t *responseInfo)
1125 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1126 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1128 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1129 ClientCB * cbNode = NULL;
1130 char *resourceTypeName = NULL;
1131 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1132 OCStackResult result = OC_STACK_ERROR;
1133 uint32_t maxAge = 0;
1135 char presenceUri[CA_MAX_URI_LENGTH];
1137 int presenceSubscribe = 0;
1138 int multicastPresenceSubscribe = 0;
1140 if (responseInfo->result != CA_CONTENT)
1142 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1143 return OC_STACK_ERROR;
1146 response.payload = NULL;
1147 response.result = OC_STACK_OK;
1149 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1150 FixUpClientResponse(&response);
1152 if (responseInfo->info.payload)
1154 result = OCParsePayload(&response.payload,
1155 PAYLOAD_TYPE_PRESENCE,
1156 responseInfo->info.payload,
1157 responseInfo->info.payloadSize);
1159 if(result != OC_STACK_OK)
1161 OIC_LOG(ERROR, TAG, "Presence parse failed");
1164 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1166 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1167 result = OC_STACK_ERROR;
1170 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1171 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1172 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1175 // check for unicast presence
1176 uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1177 responseInfo->isMulticast);
1178 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1180 return OC_STACK_INVALID_URI;
1182 OIC_LOG(INFO, TAG, "check for unicast presence");
1183 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1186 presenceSubscribe = 1;
1190 // check for multicast presence
1191 OIC_LOG(INFO, TAG, "check for multicast presence");
1192 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1195 multicastPresenceSubscribe = 1;
1199 if (!presenceSubscribe && !multicastPresenceSubscribe)
1201 OIC_LOG(INFO, TAG, "Received a presence notification, "
1202 "but need to register presence callback, ignoring");
1206 if (presenceSubscribe)
1208 if(cbNode->sequenceNumber == response.sequenceNumber)
1210 OIC_LOG(INFO, TAG, "No presence change");
1211 ResetPresenceTTL(cbNode, maxAge);
1212 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1218 OIC_LOG(INFO, TAG, "Stopping presence");
1219 response.result = OC_STACK_PRESENCE_STOPPED;
1220 if(cbNode->presence)
1222 OICFree(cbNode->presence->timeOut);
1223 OICFree(cbNode->presence);
1224 cbNode->presence = NULL;
1229 if(!cbNode->presence)
1231 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1233 if(!(cbNode->presence))
1235 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1236 result = OC_STACK_NO_MEMORY;
1240 VERIFY_NON_NULL_V(cbNode->presence);
1241 cbNode->presence->timeOut = NULL;
1242 cbNode->presence->timeOut = (uint32_t *)
1243 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1244 if(!(cbNode->presence->timeOut)){
1246 "Could not allocate memory for cbNode->presence->timeOut");
1247 OICFree(cbNode->presence);
1248 result = OC_STACK_NO_MEMORY;
1253 ResetPresenceTTL(cbNode, maxAge);
1255 cbNode->sequenceNumber = response.sequenceNumber;
1260 // This is the multicast case
1261 OIC_LOG(INFO, TAG, "this is the multicast presence");
1264 OIC_LOG(INFO, TAG, "Stopping presence");
1265 response.result = OC_STACK_PRESENCE_STOPPED;
1269 // Ensure that a filter is actually applied.
1270 if (resourceTypeName && cbNode->filterResourceType)
1272 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1273 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1279 OIC_LOG(INFO, TAG, "Callback for presence");
1281 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1283 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1285 FindAndDeleteClientCB(cbNode);
1289 OCPayloadDestroy(response.payload);
1292 #endif // WITH_PRESENCE
1294 OCStackResult HandleBatchResponse(char *requestUri, OCRepPayload **payload)
1296 if (requestUri && *payload)
1298 char *interfaceName = NULL;
1299 char *rtTypeName = NULL;
1300 char *uriQuery = NULL;
1301 char *uriWithoutQuery = NULL;
1302 if (OC_STACK_OK == getQueryFromUri(requestUri, &uriQuery, &uriWithoutQuery))
1304 if (OC_STACK_OK == ExtractFiltersFromQuery(uriQuery, &interfaceName, &rtTypeName))
1306 if (interfaceName && (0 == strcmp(OC_RSRVD_INTERFACE_BATCH, interfaceName)))
1308 char *uri = (*payload)->uri;
1309 if (uri && 0 != strcmp(uriWithoutQuery, uri))
1311 OCRepPayload *newPayload = OCRepPayloadCreate();
1314 OCRepPayloadSetUri(newPayload, uri);
1315 newPayload->next = *payload;
1316 *payload = newPayload;
1323 OICFree(interfaceName);
1324 OICFree(rtTypeName);
1326 OICFree(uriWithoutQuery);
1329 return OC_STACK_INVALID_PARAM;
1332 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1334 OIC_TRACE_MARK(%s:OCHandleResponse:%s, TAG, responseInfo->info.resourceUri);
1335 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1337 #ifdef WITH_PRESENCE
1338 if(responseInfo->info.resourceUri &&
1339 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1341 HandlePresenceResponse(endPoint, responseInfo);
1346 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1347 responseInfo->info.tokenLength, NULL, NULL);
1351 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1353 // check obs header option
1354 bool obsHeaderOpt = false;
1355 CAHeaderOption_t *options = responseInfo->info.options;
1356 for (uint8_t i = 0; i< responseInfo->info.numOptions; i++)
1358 if (options && options[i].protocolID == CA_COAP_ID &&
1359 options[i].optionID == COAP_OPTION_OBSERVE)
1361 obsHeaderOpt = true;
1366 if(responseInfo->result == CA_EMPTY)
1368 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1369 // We do not have a case for the client to receive a RESET
1370 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1372 //This is the case of receiving an ACK on a request to a slow resource!
1373 OIC_LOG(INFO, TAG, "This is a pure ACK");
1374 //TODO: should we inform the client
1375 // app that at least the request was received at the server?
1378 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1380 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1381 OIC_LOG(INFO, TAG, "Calling into application address space");
1383 OCClientResponse response =
1384 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1385 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1386 FixUpClientResponse(&response);
1387 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1388 memcpy(response.identity.id, responseInfo->info.identity.id,
1389 sizeof (response.identity.id));
1390 response.identity.id_length = responseInfo->info.identity.id_length;
1392 response.result = CAResponseToOCStackResult(responseInfo->result);
1393 cbNode->callBack(cbNode->context,
1394 cbNode->handle, &response);
1395 FindAndDeleteClientCB(cbNode);
1396 OICFree(response.resourceUri);
1399 else if ((cbNode->method == OC_REST_OBSERVE || cbNode->method == OC_REST_OBSERVE_ALL)
1400 && (responseInfo->result == CA_CONTENT) && !obsHeaderOpt)
1402 OCClientResponse response =
1403 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1404 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1405 FixUpClientResponse(&response);
1406 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1407 memcpy(response.identity.id, responseInfo->info.identity.id,
1408 sizeof (response.identity.id));
1409 response.identity.id_length = responseInfo->info.identity.id_length;
1410 response.result = OC_STACK_UNAUTHORIZED_REQ;
1412 cbNode->callBack(cbNode->context,
1415 FindAndDeleteClientCB(cbNode);
1416 OICFree(response.resourceUri);
1421 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1422 OIC_LOG(INFO, TAG, "Calling into application address space");
1424 OCClientResponse response;
1425 memset(&response, 0, sizeof(OCClientResponse));
1426 response.devAddr.adapter = OC_DEFAULT_ADAPTER;
1428 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1429 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1430 FixUpClientResponse(&response);
1431 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1432 memcpy(response.identity.id, responseInfo->info.identity.id,
1433 sizeof (response.identity.id));
1434 response.identity.id_length = responseInfo->info.identity.id_length;
1436 response.result = CAResponseToOCStackResult(responseInfo->result);
1438 if(responseInfo->info.payload &&
1439 responseInfo->info.payloadSize)
1441 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1442 // check the security resource
1443 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1445 type = PAYLOAD_TYPE_SECURITY;
1447 else if (cbNode->method == OC_REST_DISCOVER)
1449 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1450 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1452 type = PAYLOAD_TYPE_DISCOVERY;
1455 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1457 type = PAYLOAD_TYPE_DISCOVERY;
1460 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1462 type = PAYLOAD_TYPE_REPRESENTATION;
1464 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1466 type = PAYLOAD_TYPE_REPRESENTATION;
1469 #ifdef ROUTING_GATEWAY
1470 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1472 type = PAYLOAD_TYPE_REPRESENTATION;
1475 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1477 type = PAYLOAD_TYPE_REPRESENTATION;
1480 else if (strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1482 type = PAYLOAD_TYPE_REPRESENTATION;
1487 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1488 cbNode->method, cbNode->requestUri);
1489 OICFree(response.resourceUri);
1493 else if (cbNode->method == OC_REST_GET ||
1494 cbNode->method == OC_REST_PUT ||
1495 cbNode->method == OC_REST_POST ||
1496 cbNode->method == OC_REST_OBSERVE ||
1497 cbNode->method == OC_REST_OBSERVE_ALL ||
1498 cbNode->method == OC_REST_DELETE)
1500 if (cbNode->requestUri)
1502 if (0 == strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri))
1504 type = PAYLOAD_TYPE_REPRESENTATION;
1506 else if (0 == strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri))
1508 type = PAYLOAD_TYPE_REPRESENTATION;
1510 if (type == PAYLOAD_TYPE_INVALID)
1512 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1513 cbNode->method, cbNode->requestUri);
1514 type = PAYLOAD_TYPE_REPRESENTATION;
1519 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1520 type = PAYLOAD_TYPE_REPRESENTATION;
1525 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1526 cbNode->method, cbNode->requestUri);
1527 OICFree(response.resourceUri);
1531 // In case of error, still want application to receive the error message.
1532 if (OCResultToSuccess(response.result) || PAYLOAD_TYPE_REPRESENTATION == type)
1534 if(OC_STACK_OK != OCParsePayload(&response.payload,
1536 responseInfo->info.payload,
1537 responseInfo->info.payloadSize))
1539 OIC_LOG(ERROR, TAG, "Error converting payload");
1540 OCPayloadDestroy(response.payload);
1541 OICFree(response.resourceUri);
1547 response.resourceUri = OICStrdup(cbNode->requestUri);
1551 response.numRcvdVendorSpecificHeaderOptions = 0;
1552 if(responseInfo->info.numOptions > 0)
1555 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1556 if(responseInfo->info.options
1557 && responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1560 uint32_t observationOption;
1561 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1562 for (observationOption=0, i=0;
1563 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1567 (observationOption << 8) | optionData[i];
1569 response.sequenceNumber = observationOption;
1570 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1575 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1578 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1580 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1581 OCPayloadDestroy(response.payload);
1582 OICFree(response.resourceUri);
1586 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1588 if(&(responseInfo->info.options[i]))
1590 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1591 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1596 if (cbNode->method == OC_REST_OBSERVE &&
1597 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1598 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1599 response.sequenceNumber <= cbNode->sequenceNumber)
1601 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1602 response.sequenceNumber);
1607 if (cbNode->requestUri)
1609 // if request uri is '/oic/rd', update ins value of resource.
1610 char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
1613 OCUpdateResourceInsWithResponse(cbNode->requestUri, &response);
1617 // set remoteID(device ID) into OCClientResponse callback parameter
1618 if (OC_REST_DISCOVER == cbNode->method)
1620 OIC_LOG(INFO, TAG, "cbNode method is OC_REST_DISCOVER");
1621 OCDiscoveryPayload *payload = (OCDiscoveryPayload*) response.payload;
1622 // Payload can be empty in case of error message.
1623 if (payload && payload->sid)
1625 OICStrcpy(response.devAddr.remoteId, sizeof(response.devAddr.remoteId),
1627 OIC_LOG_V(INFO_PRIVATE, TAG, "Device ID of response : %s",
1628 response.devAddr.remoteId);
1631 if(NULL == response.resourceUri)
1633 response.resourceUri = OICStrdup(cbNode->requestUri);
1637 if (cbNode->requestUri)
1639 OIC_LOG_V(INFO, TAG, "cbNode requestUri is %s", cbNode->requestUri);
1640 if (cbNode->method == OC_REST_POST &&
1641 strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1643 OCHandleKeepAliveResponse(endPoint, response.payload);
1647 if (response.payload && response.payload->type == PAYLOAD_TYPE_REPRESENTATION)
1649 OIC_LOG(INFO, TAG, "Handle batch response");
1650 HandleBatchResponse(cbNode->requestUri, (OCRepPayload **)&response.payload);
1653 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1656 cbNode->sequenceNumber = response.sequenceNumber;
1658 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1660 FindAndDeleteClientCB(cbNode);
1664 // To keep discovery callbacks active.
1665 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1666 MILLISECONDS_PER_SECOND);
1670 //Need to send ACK when the response is CON
1671 if(responseInfo->info.type == CA_MSG_CONFIRM)
1673 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1675 OIC_LOG(INFO, TAG, "Received a confirmable message. Sending EMPTY");
1676 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1677 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1681 OICFree(response.resourceUri);
1682 OCPayloadDestroy(response.payload);
1687 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1688 responseInfo->info.tokenLength);
1692 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1693 if(responseInfo->result == CA_EMPTY)
1695 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1696 if(responseInfo->info.type == CA_MSG_RESET)
1698 OIC_LOG(INFO, TAG, "This is a RESET");
1699 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1700 OC_OBSERVER_NOT_INTERESTED);
1702 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1704 OIC_LOG(INFO, TAG, "This is a pure ACK");
1705 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1706 OC_OBSERVER_STILL_INTERESTED);
1709 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1711 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1712 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1713 OC_OBSERVER_FAILED_COMM);
1716 FreeObserver(observer);
1720 if(!cbNode && !observer)
1722 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1723 || myStackMode == OC_GATEWAY)
1725 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1726 if(responseInfo->result == CA_EMPTY)
1728 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1732 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1734 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1735 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1736 CA_MSG_RESET, 0, NULL, NULL, 0, NULL,
1737 CA_RESPONSE_FOR_RES);
1742 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1743 || myStackMode == OC_GATEWAY)
1745 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1746 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1748 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1749 responseInfo->info.messageId);
1751 if (responseInfo->info.type == CA_MSG_RESET)
1753 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1754 responseInfo->info.messageId);
1762 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1764 VERIFY_NON_NULL_NR(endPoint, FATAL);
1765 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1767 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1768 OIC_TRACE_BEGIN(%s:HandleCAResponses, TAG);
1770 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1771 #ifdef ROUTING_GATEWAY
1772 bool needRIHandling = false;
1774 * Routing manager is going to update either of endpoint or response or both.
1775 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1776 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1779 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1781 if(ret != OC_STACK_OK || !needRIHandling)
1783 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1790 * Put source in sender endpoint so that the next packet from application can be routed to
1791 * proper destination and remove "RM" coap header option before passing request / response to
1792 * RI as this option will make no sense to either RI or application.
1794 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1795 (uint8_t *) &(responseInfo->info.numOptions),
1796 (CAEndpoint_t *) endPoint);
1799 OCHandleResponse(endPoint, responseInfo);
1801 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1805 * This function handles error response from CA
1806 * code shall be added to handle the errors
1808 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1810 VERIFY_NON_NULL_NR(endPoint, FATAL);
1811 VERIFY_NON_NULL_NR(errorInfo, FATAL);
1813 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1814 OIC_TRACE_BEGIN(%s:HandleCAErrorResponse, TAG);
1816 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1817 errorInfo->info.tokenLength, NULL, NULL);
1820 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1821 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1822 FixUpClientResponse(&response);
1823 response.resourceUri = errorInfo->info.resourceUri;
1824 memcpy(response.identity.id, errorInfo->info.identity.id,
1825 sizeof (response.identity.id));
1826 response.identity.id_length = errorInfo->info.identity.id_length;
1827 response.result = CAResultToOCResult(errorInfo->result);
1829 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1832 ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1833 errorInfo->info.tokenLength);
1836 OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1837 OCStackResult result = CAResultToOCResult(errorInfo->result);
1838 if (OC_STACK_COMM_ERROR == result)
1840 OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1841 OC_OBSERVER_FAILED_COMM);
1845 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1850 * This function sends out Direct Stack Responses. These are responses that are not coming
1851 * from the application entity handler. These responses have no payload and are usually ACKs,
1852 * RESETs or some error conditions that were caught by the stack.
1854 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1855 const CAResponseResult_t responseResult, const CAMessageType_t type,
1856 const uint8_t numOptions, const CAHeaderOption_t *options,
1857 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1858 CADataType_t dataType)
1860 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1862 if (endPoint->flags & CA_MULTICAST)
1864 OIC_LOG(ERROR, TAG, "It is unnecessary to respond to a multicast request");
1868 CAResponseInfo_t respInfo = { .result = responseResult };
1869 respInfo.info.messageId = coapID;
1870 respInfo.info.numOptions = numOptions;
1872 if (respInfo.info.numOptions)
1874 respInfo.info.options =
1875 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1876 memcpy (respInfo.info.options, options,
1877 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1881 respInfo.info.payload = NULL;
1882 respInfo.info.token = token;
1883 respInfo.info.tokenLength = tokenLength;
1884 respInfo.info.type = type;
1885 respInfo.info.resourceUri = OICStrdup (resourceUri);
1886 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1887 respInfo.info.dataType = dataType;
1889 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1890 // Add the destination to route option from the endpoint->routeData.
1891 bool doPost = false;
1892 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1893 if(OC_STACK_OK != result)
1895 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1896 OICFree (respInfo.info.resourceUri);
1897 OICFree (respInfo.info.options);
1902 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1903 CARequestInfo_t reqInfo = {.method = CA_POST };
1904 /* The following initialization is not done in a single initializer block as in
1905 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1906 * does not have designated initalizers. This is a work-around for now.
1908 reqInfo.info.type = CA_MSG_NONCONFIRM;
1909 reqInfo.info.messageId = coapID;
1910 reqInfo.info.tokenLength = tokenLength;
1911 reqInfo.info.token = token;
1912 reqInfo.info.numOptions = respInfo.info.numOptions;
1913 reqInfo.info.payload = NULL;
1914 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1915 if (reqInfo.info.numOptions)
1917 reqInfo.info.options =
1918 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1919 if (NULL == reqInfo.info.options)
1921 OIC_LOG(ERROR, TAG, "Calloc failed");
1922 OICFree (reqInfo.info.resourceUri);
1923 OICFree (respInfo.info.resourceUri);
1924 OICFree (respInfo.info.options);
1925 return OC_STACK_NO_MEMORY;
1927 memcpy (reqInfo.info.options, respInfo.info.options,
1928 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1931 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1932 OICFree (reqInfo.info.resourceUri);
1933 OICFree (reqInfo.info.options);
1934 OICFree (respInfo.info.resourceUri);
1935 OICFree (respInfo.info.options);
1936 if (CA_STATUS_OK != caResult)
1938 OIC_LOG(ERROR, TAG, "CASendRequest error");
1939 return CAResultToOCResult(caResult);
1945 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1947 // resourceUri in the info field is cloned in the CA layer and
1948 // thus ownership is still here.
1949 OICFree (respInfo.info.resourceUri);
1950 OICFree (respInfo.info.options);
1951 if(CA_STATUS_OK != caResult)
1953 OIC_LOG(ERROR, TAG, "CASendResponse error");
1954 return CAResultToOCResult(caResult);
1957 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1961 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1963 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1964 OCStackResult result = OC_STACK_ERROR;
1965 if(!protocolRequest)
1967 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1968 return OC_STACK_INVALID_PARAM;
1971 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1972 protocolRequest->tokenLength);
1975 OIC_LOG(INFO, TAG, "This is a new Server Request");
1976 result = AddServerRequest(&request, protocolRequest->coapID,
1977 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1978 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1979 protocolRequest->observationOption, protocolRequest->qos,
1980 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1981 protocolRequest->payload, protocolRequest->requestToken,
1982 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1983 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1984 &protocolRequest->devAddr);
1985 if (OC_STACK_OK != result)
1987 OIC_LOG(ERROR, TAG, "Error adding server request");
1993 OIC_LOG(ERROR, TAG, "Out of Memory");
1994 return OC_STACK_NO_MEMORY;
1997 if(!protocolRequest->reqMorePacket)
1999 request->requestComplete = 1;
2004 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
2007 if(request->requestComplete)
2009 OIC_LOG(INFO, TAG, "This Server Request is complete");
2010 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2011 OCResource *resource = NULL;
2012 result = DetermineResourceHandling (request, &resHandling, &resource);
2013 if (result == OC_STACK_OK)
2015 result = ProcessRequest(resHandling, resource, request);
2020 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2021 result = OC_STACK_CONTINUE;
2026 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2028 OIC_TRACE_MARK(%s:OCHandleRequests:%s, TAG, requestInfo->info.resourceUri);
2029 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2031 OCStackResult requestResult = OC_STACK_ERROR;
2033 if(myStackMode == OC_CLIENT)
2035 //TODO: should the client be responding to requests?
2039 OCServerProtocolRequest serverRequest = {0};
2041 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2043 char * uriWithoutQuery = NULL;
2044 char * query = NULL;
2046 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2048 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2050 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2053 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2054 OIC_LOG_V(INFO, TAG, "Query : %s", query);
2056 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2058 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2059 OICFree(uriWithoutQuery);
2063 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2064 OICFree(uriWithoutQuery);
2071 if(strlen(query) < MAX_QUERY_LENGTH)
2073 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2078 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2084 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2086 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2087 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2088 if (!serverRequest.payload)
2090 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2093 memcpy (serverRequest.payload, requestInfo->info.payload,
2094 requestInfo->info.payloadSize);
2098 serverRequest.reqTotalSize = 0;
2101 switch (requestInfo->method)
2104 serverRequest.method = OC_REST_GET;
2107 serverRequest.method = OC_REST_PUT;
2110 serverRequest.method = OC_REST_POST;
2113 serverRequest.method = OC_REST_DELETE;
2116 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2117 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2118 requestInfo->info.type, requestInfo->info.numOptions,
2119 requestInfo->info.options, requestInfo->info.token,
2120 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2122 OICFree(serverRequest.payload);
2126 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2127 requestInfo->info.tokenLength);
2129 serverRequest.tokenLength = requestInfo->info.tokenLength;
2130 if (serverRequest.tokenLength) {
2132 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2134 if (!serverRequest.requestToken)
2136 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2137 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2138 requestInfo->info.type, requestInfo->info.numOptions,
2139 requestInfo->info.options, requestInfo->info.token,
2140 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2142 OICFree(serverRequest.payload);
2145 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2148 switch (requestInfo->info.acceptFormat)
2150 case CA_FORMAT_APPLICATION_CBOR:
2151 serverRequest.acceptFormat = OC_FORMAT_CBOR;
2153 case CA_FORMAT_UNDEFINED:
2154 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2157 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2160 if (requestInfo->info.type == CA_MSG_CONFIRM)
2162 serverRequest.qos = OC_HIGH_QOS;
2166 serverRequest.qos = OC_LOW_QOS;
2168 // CA does not need the following field
2169 // Are we sure CA does not need them? how is it responding to multicast
2170 serverRequest.delayedResNeeded = 0;
2172 serverRequest.coapID = requestInfo->info.messageId;
2174 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2176 // copy vendor specific header options
2177 uint8_t tempNum = (requestInfo->info.numOptions);
2179 // Assume no observation requested and it is a pure GET.
2180 // If obs registration/de-registration requested it'll be fetched from the
2181 // options in GetObserveHeaderOption()
2182 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2184 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2185 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2188 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2189 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2190 requestInfo->info.type, requestInfo->info.numOptions,
2191 requestInfo->info.options, requestInfo->info.token,
2192 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2194 OICFree(serverRequest.payload);
2195 OICFree(serverRequest.requestToken);
2198 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2199 if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2201 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
2202 sizeof(CAHeaderOption_t)*tempNum);
2205 requestResult = HandleStackRequests (&serverRequest);
2207 // Send ACK to client as precursor to slow response
2208 if (requestResult == OC_STACK_SLOW_RESOURCE)
2210 if (requestInfo->info.type == CA_MSG_CONFIRM)
2212 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2213 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2218 if (requestResult == OC_STACK_RESOURCE_ERROR
2219 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2221 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2224 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2226 if (requestResult == OC_STACK_RESOURCE_ERROR)
2228 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2230 else if (!OCResultToSuccess(requestResult))
2232 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2236 else if(!OCResultToSuccess(requestResult))
2238 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2240 CAResponseResult_t stackResponse =
2241 OCToCAStackResult(requestResult, serverRequest.method);
2243 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2244 requestInfo->info.type, requestInfo->info.numOptions,
2245 requestInfo->info.options, requestInfo->info.token,
2246 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2249 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2250 // The token is copied in there, and is thus still owned by this function.
2251 OICFree(serverRequest.payload);
2252 OICFree(serverRequest.requestToken);
2253 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2256 //This function will be called back by CA layer when a request is received
2257 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2259 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2260 OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2263 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2270 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2275 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2276 #ifdef ROUTING_GATEWAY
2277 bool needRIHandling = false;
2278 bool isEmptyMsg = false;
2280 * Routing manager is going to update either of endpoint or request or both.
2281 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2282 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2283 * destination. It can also remove "RM" coap header option before passing request / response to
2284 * RI as this option will make no sense to either RI or application.
2286 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2287 &needRIHandling, &isEmptyMsg);
2288 if(OC_STACK_OK != ret || !needRIHandling)
2290 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2297 * Put source in sender endpoint so that the next packet from application can be routed to
2298 * proper destination and remove RM header option.
2300 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2301 (uint8_t *) &(requestInfo->info.numOptions),
2302 (CAEndpoint_t *) endPoint);
2304 #ifdef ROUTING_GATEWAY
2308 * In Gateways, the MSGType in route option is used to check if the actual
2309 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2310 * EMPTY response is sent in the form of POST request which need to be changed
2311 * to a EMPTY response by RM. This translation is done in this part of the code.
2313 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2314 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2315 .info.messageId = requestInfo->info.messageId,
2316 .info.type = CA_MSG_ACKNOWLEDGE};
2317 OCHandleResponse(endPoint, &respInfo);
2323 // Normal handling of the packet
2324 OCHandleRequests(endPoint, requestInfo);
2326 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2330 //-----------------------------------------------------------------------------
2332 //-----------------------------------------------------------------------------
2334 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2337 !raInfo->username ||
2338 !raInfo->hostname ||
2339 !raInfo->xmpp_domain)
2342 return OC_STACK_INVALID_PARAM;
2344 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2345 gRASetInfo = (result == OC_STACK_OK)? true : false;
2351 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2355 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2358 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2360 OIC_LOG(DEBUG, TAG, "call OCInit1");
2361 return OCInit2(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS, OC_DEFAULT_ADAPTER);
2364 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2365 OCTransportAdapter transportType)
2367 if(stackState == OC_STACK_INITIALIZED)
2369 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2370 OCStop() between them are ignored.");
2374 #ifndef ROUTING_GATEWAY
2375 if (OC_GATEWAY == mode)
2377 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2378 return OC_STACK_INVALID_PARAM;
2385 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2386 return OC_STACK_ERROR;
2390 OCStackResult result = OC_STACK_ERROR;
2391 OIC_LOG(INFO, TAG, "Entering OCInit");
2394 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2395 || (mode == OC_GATEWAY)))
2397 OIC_LOG(ERROR, TAG, "Invalid mode");
2398 return OC_STACK_ERROR;
2402 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2404 caglobals.client = true;
2406 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2408 caglobals.server = true;
2411 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2412 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2414 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2416 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2417 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2419 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2422 defaultDeviceHandler = NULL;
2423 defaultDeviceHandlerCallbackParameter = NULL;
2425 result = InitializeScheduleResourceList();
2426 VERIFY_SUCCESS(result, OC_STACK_OK);
2428 result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2429 VERIFY_SUCCESS(result, OC_STACK_OK);
2431 result = CAResultToOCResult(OCSelectNetwork(transportType));
2432 VERIFY_SUCCESS(result, OC_STACK_OK);
2434 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2435 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2436 VERIFY_SUCCESS(result, OC_STACK_OK);
2438 switch (myStackMode)
2441 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2442 result = CAResultToOCResult(CAStartDiscoveryServer());
2443 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2446 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2447 result = CAResultToOCResult(CAStartListeningServer());
2448 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2450 case OC_CLIENT_SERVER:
2452 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2453 result = CAResultToOCResult(CAStartListeningServer());
2454 if(result == OC_STACK_OK)
2456 result = CAResultToOCResult(CAStartDiscoveryServer());
2460 VERIFY_SUCCESS(result, OC_STACK_OK);
2463 CARegisterKeepAliveHandler(OCHandleKeepAliveConnCB);
2466 #ifdef WITH_PRESENCE
2467 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2468 #endif // WITH_PRESENCE
2470 //Update Stack state to initialized
2471 stackState = OC_STACK_INITIALIZED;
2473 // Initialize resource
2474 if(myStackMode != OC_CLIENT)
2476 result = initResources();
2479 // Initialize the SRM Policy Engine
2480 if(result == OC_STACK_OK)
2482 result = SRMInitPolicyEngine();
2483 // TODO after BeachHead delivery: consolidate into single SRMInit()
2485 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2486 RMSetStackMode(mode);
2487 #ifdef ROUTING_GATEWAY
2488 if (OC_GATEWAY == myStackMode)
2490 result = RMInitialize();
2496 if (result == OC_STACK_OK)
2498 result = OCInitializeKeepAlive(myStackMode);
2502 InitializeObseverList();
2505 if(result != OC_STACK_OK)
2507 OIC_LOG(ERROR, TAG, "Stack initialization error");
2508 TerminateScheduleResourceList();
2509 deleteAllResources();
2511 stackState = OC_STACK_UNINITIALIZED;
2516 OCStackResult OCStop()
2518 OIC_LOG(INFO, TAG, "Entering OCStop");
2520 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2522 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2525 else if (stackState != OC_STACK_INITIALIZED)
2527 OIC_LOG(INFO, TAG, "Stack not initialized");
2528 return OC_STACK_ERROR;
2531 // unset cautil config
2532 CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2533 CAUtilSetBTConfigure(configs);
2535 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2537 CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2538 OCDefaultConnectionStateChangedHandler);
2540 #ifdef WITH_PRESENCE
2541 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2542 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2543 presenceResource.presenceTTL = 0;
2544 presenceState = OC_PRESENCE_UNINITIALIZED;
2545 #endif // WITH_PRESENCE
2547 #ifdef ROUTING_GATEWAY
2548 if (OC_GATEWAY == myStackMode)
2555 OCTerminateKeepAlive(myStackMode);
2558 TerminateScheduleResourceList();
2559 // Remove all observers
2560 TerminateObserverList();
2561 // Free memory dynamically allocated for resources
2562 deleteAllResources();
2563 // Remove all the client callbacks
2564 DeleteClientCBList();
2565 // Terminate connectivity-abstraction layer.
2568 // De-init the SRM Policy Engine
2569 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2570 SRMDeInitPolicyEngine();
2572 stackState = OC_STACK_UNINITIALIZED;
2576 OCStackResult OCStartMulticastServer()
2578 if(stackState != OC_STACK_INITIALIZED)
2580 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2581 return OC_STACK_ERROR;
2583 CAResult_t ret = CAStartListeningServer();
2584 if (CA_STATUS_OK != ret)
2586 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2587 return OC_STACK_ERROR;
2592 OCStackResult OCStopMulticastServer()
2594 CAResult_t ret = CAStopListeningServer();
2595 if (CA_STATUS_OK != ret)
2597 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2598 return OC_STACK_ERROR;
2603 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2608 return CA_MSG_CONFIRM;
2613 return CA_MSG_NONCONFIRM;
2617 OCStackResult ParseRequestUri(const char *fullUri,
2618 OCTransportAdapter adapter,
2619 OCTransportFlags flags,
2620 OCDevAddr **devAddr,
2622 char **resourceType)
2624 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2626 OCStackResult result = OC_STACK_OK;
2627 OCDevAddr *da = NULL;
2631 // provide defaults for all returned values
2638 *resourceUri = NULL;
2642 *resourceType = NULL;
2645 // delimit url prefix, if any
2646 const char *start = fullUri;
2647 char *slash2 = strstr(start, "//");
2652 char *slash = strchr(start, '/');
2655 return OC_STACK_INVALID_URI;
2658 // process url scheme
2659 size_t prefixLen = slash2 - fullUri;
2663 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2664 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2670 // TODO: this logic should come in with unit tests exercising the various strings
2671 // processs url prefix, if any
2672 size_t urlLen = slash - start;
2676 if (urlLen && devAddr)
2677 { // construct OCDevAddr
2678 if (start[0] == '[')
2680 char *close = strchr(++start, ']');
2681 if (!close || close > slash)
2683 return OC_STACK_INVALID_URI;
2686 if (close[1] == ':')
2693 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2697 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2699 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2703 char *dot = strchr(start, '.');
2704 if (dot && dot < slash)
2706 colon = strchr(start, ':');
2707 end = (colon && colon < slash) ? colon : slash;
2712 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2716 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2718 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2726 if (len >= sizeof(da->addr))
2728 return OC_STACK_INVALID_URI;
2730 // collect port, if any
2731 if (colon && colon < slash)
2733 for (colon++; colon < slash; colon++)
2736 if (c < '0' || c > '9')
2738 return OC_STACK_INVALID_URI;
2740 port = 10 * port + c - '0';
2745 if (len >= sizeof(da->addr))
2747 return OC_STACK_INVALID_URI;
2750 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2753 return OC_STACK_NO_MEMORY;
2756 // Decode address per RFC 6874.
2757 result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2758 if (result != OC_STACK_OK)
2765 da->adapter = adapter;
2767 if (!strncmp(fullUri, "coaps", 5))
2769 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2774 // process resource uri, if any
2776 { // request uri and query
2777 size_t ulen = strlen(slash); // resource uri length
2778 size_t tlen = 0; // resource type length
2781 static const char strPresence[] = "/oic/ad?rt=";
2782 static const size_t lenPresence = sizeof(strPresence) - 1;
2783 if (!strncmp(slash, strPresence, lenPresence))
2785 type = slash + lenPresence;
2786 tlen = ulen - lenPresence;
2791 *resourceUri = (char *)OICMalloc(ulen + 1);
2794 result = OC_STACK_NO_MEMORY;
2797 OICStrcpy(*resourceUri, (ulen + 1), slash);
2800 if (type && resourceType)
2802 *resourceType = (char *)OICMalloc(tlen + 1);
2805 result = OC_STACK_NO_MEMORY;
2809 OICStrcpy(*resourceType, (tlen+1), type);
2816 // free all returned values
2823 OICFree(*resourceUri);
2827 OICFree(*resourceType);
2832 #ifdef WITH_PRESENCE
2833 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2837 char uri[CA_MAX_URI_LENGTH];
2839 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2841 *requestUri = OICStrdup(uri);
2844 return OC_STACK_NO_MEMORY;
2849 #endif // WITH_PRESENCE
2852 * Discover or Perform requests on a specified resource
2854 OCStackResult OCDoResource(OCDoHandle *handle,
2856 const char *requestUri,
2857 const OCDevAddr *destination,
2859 OCConnectivityType connectivityType,
2860 OCQualityOfService qos,
2861 OCCallbackData *cbData,
2862 OCHeaderOption *options,
2865 OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
2866 connectivityType, qos, cbData, options, numOptions);
2868 // This is the owner of the payload object, so we free it
2869 OCPayloadDestroy(payload);
2874 * Discover or Perform requests on a specified resource
2876 OCStackResult OCDoRequest(OCDoHandle *handle,
2878 const char *requestUri,
2879 const OCDevAddr *destination,
2881 OCConnectivityType connectivityType,
2882 OCQualityOfService qos,
2883 OCCallbackData *cbData,
2884 OCHeaderOption *options,
2887 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2888 OIC_TRACE_BEGIN(%s:OCDoRequest, TAG);
2890 // Validate input parameters
2891 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2892 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2894 OCStackResult result = OC_STACK_ERROR;
2895 CAResult_t caResult;
2896 CAToken_t token = NULL;
2897 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2898 ClientCB *clientCB = NULL;
2899 OCDoHandle resHandle = NULL;
2900 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2901 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2903 OCTransportAdapter adapter;
2904 OCTransportFlags flags;
2905 // the request contents are put here
2906 CARequestInfo_t requestInfo = {.method = CA_GET};
2907 // requestUri will be parsed into the following three variables
2908 OCDevAddr *devAddr = NULL;
2909 char *resourceUri = NULL;
2910 char *resourceType = NULL;
2913 * Support original behavior with address on resourceUri argument.
2915 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2916 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2920 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2921 if (result != OC_STACK_OK)
2923 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2927 else if (!checkProxyUri(options, numOptions))
2929 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2936 case OC_REST_OBSERVE:
2937 case OC_REST_OBSERVE_ALL:
2938 requestInfo.method = CA_GET;
2941 requestInfo.method = CA_PUT;
2944 requestInfo.method = CA_POST;
2946 case OC_REST_DELETE:
2947 requestInfo.method = CA_DELETE;
2949 case OC_REST_DISCOVER:
2950 #ifdef WITH_PRESENCE
2951 case OC_REST_PRESENCE:
2953 if (destination || devAddr)
2955 requestInfo.isMulticast = false;
2959 tmpDevAddr.adapter = adapter;
2960 tmpDevAddr.flags = flags;
2961 destination = &tmpDevAddr;
2962 requestInfo.isMulticast = true;
2965 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
2966 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
2967 // replacing method type with GET.
2968 requestInfo.method = CA_GET;
2971 result = OC_STACK_INVALID_METHOD;
2975 if (!devAddr && !destination)
2977 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2978 result = OC_STACK_INVALID_PARAM;
2982 /* If not original behavior, use destination argument */
2983 if (destination && !devAddr)
2985 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2988 result = OC_STACK_NO_MEMORY;
2991 OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
2992 *devAddr = *destination;
2997 OIC_LOG_V(INFO_PRIVATE, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
2998 if (!requestInfo.isMulticast)
3000 OIC_LOG_V(DEBUG, TAG, "remoteAddr of devAddr : [%s]:[%d]",
3001 devAddr->addr, devAddr->port);
3005 resHandle = GenerateInvocationHandle();
3008 result = OC_STACK_NO_MEMORY;
3012 caResult = CAGenerateToken(&token, tokenLength);
3013 if (caResult != CA_STATUS_OK)
3015 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3016 result= OC_STACK_ERROR;
3020 // fill in request data
3021 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3022 requestInfo.info.token = token;
3023 requestInfo.info.tokenLength = tokenLength;
3025 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3027 result = CreateObserveHeaderOption (&(requestInfo.info.options),
3028 options, numOptions, OC_OBSERVE_REGISTER);
3029 if (result != OC_STACK_OK)
3033 requestInfo.info.numOptions = numOptions + 1;
3037 requestInfo.info.numOptions = numOptions;
3038 requestInfo.info.options =
3039 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3040 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3041 numOptions * sizeof(CAHeaderOption_t));
3044 CopyDevAddrToEndpoint(devAddr, &endpoint);
3049 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3052 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3055 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3059 requestInfo.info.payload = NULL;
3060 requestInfo.info.payloadSize = 0;
3061 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3064 // prepare for response
3065 #ifdef WITH_PRESENCE
3066 if (method == OC_REST_PRESENCE)
3068 char *presenceUri = NULL;
3069 result = OCPreparePresence(&endpoint, &presenceUri,
3070 requestInfo.isMulticast);
3071 if (OC_STACK_OK != result)
3076 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3077 // Presence notification will form a canonical uri to
3078 // look for callbacks into the application.
3081 OICFree(resourceUri);
3083 resourceUri = presenceUri;
3087 // update resourceUri onto requestInfo after check presence uri
3088 requestInfo.info.resourceUri = resourceUri;
3090 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3091 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3092 method, devAddr, resourceUri, resourceType, ttl);
3093 if (OC_STACK_OK != result)
3098 devAddr = NULL; // Client CB list entry now owns it
3099 resourceUri = NULL; // Client CB list entry now owns it
3100 resourceType = NULL; // Client CB list entry now owns it
3102 #ifdef WITH_PRESENCE
3103 if (method == OC_REST_PRESENCE)
3105 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3109 *handle = resHandle;
3117 result = OCSendRequest(&endpoint, &requestInfo);
3118 if (OC_STACK_OK != result)
3125 *handle = resHandle;
3129 if (result != OC_STACK_OK)
3131 OIC_LOG(ERROR, TAG, "OCDoResource error");
3132 FindAndDeleteClientCB(clientCB);
3133 CADestroyToken(token);
3141 OICFree(requestInfo.info.payload);
3143 OICFree(resourceUri);
3144 OICFree(resourceType);
3145 OICFree(requestInfo.info.options);
3150 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3154 * This ftn is implemented one of two ways in the case of observation:
3156 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3157 * Remove the callback associated on client side.
3158 * When the next notification comes in from server,
3159 * reply with RESET message to server.
3160 * Keep in mind that the server will react to RESET only
3161 * if the last notification was sent as CON
3163 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3164 * and it is associated with an observe request
3165 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3166 * Send CON Observe request to server with
3167 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3168 * Remove the callback associated on client side.
3170 OCStackResult ret = OC_STACK_OK;
3171 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3172 CARequestInfo_t requestInfo = {.method = CA_GET};
3176 return OC_STACK_INVALID_PARAM;
3179 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3182 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3183 return OC_STACK_ERROR;
3186 switch (clientCB->method)
3188 case OC_REST_OBSERVE:
3189 case OC_REST_OBSERVE_ALL:
3191 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3193 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3195 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
3197 FindAndDeleteClientCB(clientCB);
3201 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3203 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3204 requestInfo.info.token = clientCB->token;
3205 requestInfo.info.tokenLength = clientCB->tokenLength;
3207 if (CreateObserveHeaderOption (&(requestInfo.info.options),
3208 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3210 return OC_STACK_ERROR;
3212 requestInfo.info.numOptions = numOptions + 1;
3213 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3216 ret = OCSendRequest(&endpoint, &requestInfo);
3218 if (requestInfo.info.options)
3220 OICFree (requestInfo.info.options);
3222 if (requestInfo.info.resourceUri)
3224 OICFree (requestInfo.info.resourceUri);
3229 case OC_REST_DISCOVER:
3230 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3231 clientCB->requestUri);
3232 FindAndDeleteClientCB(clientCB);
3235 #ifdef WITH_PRESENCE
3236 case OC_REST_PRESENCE:
3237 FindAndDeleteClientCB(clientCB);
3243 case OC_REST_DELETE:
3244 OIC_LOG_V(INFO, TAG, "Cancelling request callback for resource %s",
3245 clientCB->requestUri);
3246 FindAndDeleteClientCB(clientCB);
3250 ret = OC_STACK_INVALID_METHOD;
3258 * @brief Register Persistent storage callback.
3259 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3261 * OC_STACK_OK - No errors; Success
3262 * OC_STACK_INVALID_PARAM - Invalid parameter
3264 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3266 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3267 if(!persistentStorageHandler)
3269 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3270 return OC_STACK_INVALID_PARAM;
3274 if( !persistentStorageHandler->open ||
3275 !persistentStorageHandler->close ||
3276 !persistentStorageHandler->read ||
3277 !persistentStorageHandler->unlink ||
3278 !persistentStorageHandler->write)
3280 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3281 return OC_STACK_INVALID_PARAM;
3284 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3287 #ifdef WITH_PRESENCE
3289 OCStackResult OCProcessPresence()
3291 OCStackResult result = OC_STACK_OK;
3293 // the following line floods the log with messages that are irrelevant
3294 // to most purposes. Uncomment as needed.
3295 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3296 ClientCB* cbNode = NULL;
3297 OCClientResponse clientResponse;
3298 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3300 LL_FOREACH(cbList, cbNode)
3302 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3307 uint32_t now = GetTicks(0);
3308 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3309 cbNode->presence->TTLlevel);
3310 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3312 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3317 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3319 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3320 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3322 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3324 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3326 clientResponse.sequenceNumber = 0;
3327 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3328 clientResponse.devAddr = *cbNode->devAddr;
3329 FixUpClientResponse(&clientResponse);
3330 clientResponse.payload = NULL;
3332 // Increment the TTLLevel (going to a next state), so we don't keep
3333 // sending presence notification to client.
3334 cbNode->presence->TTLlevel++;
3335 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3336 cbNode->presence->TTLlevel);
3338 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3339 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3341 FindAndDeleteClientCB(cbNode);
3345 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3350 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3351 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3352 CARequestInfo_t requestInfo = {.method = CA_GET};
3354 OIC_LOG(DEBUG, TAG, "time to test server presence");
3356 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3358 requestData.type = CA_MSG_NONCONFIRM;
3359 requestData.token = cbNode->token;
3360 requestData.tokenLength = cbNode->tokenLength;
3361 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3362 requestInfo.method = CA_GET;
3363 requestInfo.info = requestData;
3365 result = OCSendRequest(&endpoint, &requestInfo);
3366 if (OC_STACK_OK != result)
3371 cbNode->presence->TTLlevel++;
3372 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3375 if (result != OC_STACK_OK)
3377 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3382 #endif // WITH_PRESENCE
3384 OCStackResult OCProcess()
3386 if (stackState == OC_STACK_UNINITIALIZED)
3388 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3389 return OC_STACK_ERROR;
3391 #ifdef WITH_PRESENCE
3392 OCProcessPresence();
3394 CAHandleRequestResponse();
3396 #ifdef ROUTING_GATEWAY
3401 OCProcessKeepAlive();
3406 #ifdef WITH_PRESENCE
3407 OCStackResult OCStartPresence(const uint32_t ttl)
3409 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3410 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3411 OCChangeResourceProperty(
3412 &(((OCResource *)presenceResource.handle)->resourceProperties),
3415 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3417 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3418 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3422 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3423 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3427 presenceResource.presenceTTL = ttl;
3430 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3433 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3435 presenceState = OC_PRESENCE_INITIALIZED;
3437 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3439 CAToken_t caToken = NULL;
3440 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3441 if (caResult != CA_STATUS_OK)
3443 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3444 CADestroyToken(caToken);
3445 return OC_STACK_ERROR;
3448 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3449 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3450 CADestroyToken(caToken);
3453 // Each time OCStartPresence is called
3454 // a different random 32-bit integer number is used
3455 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3457 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3458 OC_PRESENCE_TRIGGER_CREATE);
3461 OCStackResult OCStopPresence()
3463 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3464 OCStackResult result = OC_STACK_ERROR;
3466 if(presenceResource.handle)
3468 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3470 // make resource inactive
3471 result = OCChangeResourceProperty(
3472 &(((OCResource *) presenceResource.handle)->resourceProperties),
3476 if(result != OC_STACK_OK)
3479 "Changing the presence resource properties to ACTIVE not successful");
3483 return SendStopNotification();
3487 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3488 void* callbackParameter)
3490 defaultDeviceHandler = entityHandler;
3491 defaultDeviceHandlerCallbackParameter = callbackParameter;
3496 OCStackResult OCCreateResource(OCResourceHandle *handle,
3497 const char *resourceTypeName,
3498 const char *resourceInterfaceName,
3499 const char *uri, OCEntityHandler entityHandler,
3500 void* callbackParam,
3501 uint8_t resourceProperties)
3504 OCResource *pointer = NULL;
3505 OCStackResult result = OC_STACK_ERROR;
3507 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3509 if(myStackMode == OC_CLIENT)
3511 return OC_STACK_INVALID_PARAM;
3513 // Validate parameters
3514 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3516 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3517 return OC_STACK_INVALID_URI;
3519 // Is it presented during resource discovery?
3520 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3522 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3523 return OC_STACK_INVALID_PARAM;
3526 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3528 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3532 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3534 // Make sure resourceProperties bitmask has allowed properties specified
3535 if (resourceProperties
3536 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3537 OC_EXPLICIT_DISCOVERABLE
3546 OIC_LOG(ERROR, TAG, "Invalid property");
3547 return OC_STACK_INVALID_PARAM;
3550 // If the headResource is NULL, then no resources have been created...
3551 pointer = headResource;
3554 // At least one resources is in the resource list, so we need to search for
3555 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3558 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3560 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3561 return OC_STACK_INVALID_PARAM;
3563 pointer = pointer->next;
3566 // Create the pointer and insert it into the resource list
3567 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3570 result = OC_STACK_NO_MEMORY;
3573 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3575 insertResource(pointer);
3578 pointer->uri = OICStrdup(uri);
3581 result = OC_STACK_NO_MEMORY;
3585 // Set properties. Set OC_ACTIVE
3586 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3589 // Add the resourcetype to the resource
3590 result = BindResourceTypeToResource(pointer, resourceTypeName);
3591 if (result != OC_STACK_OK)
3593 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3597 // Add the resourceinterface to the resource
3598 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3599 if (result != OC_STACK_OK)
3601 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3605 // If an entity handler has been passed, attach it to the newly created
3606 // resource. Otherwise, set the default entity handler.
3609 pointer->entityHandler = entityHandler;
3610 pointer->entityHandlerCallbackParam = callbackParam;
3614 pointer->entityHandler = defaultResourceEHandler;
3615 pointer->entityHandlerCallbackParam = NULL;
3618 // Initialize a pointer indicating child resources in case of collection
3619 pointer->rsrcChildResourcesHead = NULL;
3622 result = OC_STACK_OK;
3624 #ifdef WITH_PRESENCE
3625 if (presenceResource.handle)
3627 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3628 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3632 if (result != OC_STACK_OK)
3634 // Deep delete of resource and other dynamic elements that it contains
3635 deleteResource(pointer);
3640 OCStackResult OCBindResource(
3641 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3643 OCResource *resource = NULL;
3644 OCChildResource *tempChildResource = NULL;
3645 OCChildResource *newChildResource = NULL;
3647 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3649 // Validate parameters
3650 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3651 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3652 // Container cannot contain itself
3653 if (collectionHandle == resourceHandle)
3655 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3656 return OC_STACK_INVALID_PARAM;
3659 // Use the handle to find the resource in the resource linked list
3660 resource = findResource((OCResource *) collectionHandle);
3663 OIC_LOG(ERROR, TAG, "Collection handle not found");
3664 return OC_STACK_INVALID_PARAM;
3667 // Look for an open slot to add add the child resource.
3668 // If found, add it and return success
3670 tempChildResource = resource->rsrcChildResourcesHead;
3672 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3674 // TODO: what if one of child resource was deregistered without unbinding?
3675 tempChildResource = tempChildResource->next;
3678 // Do memory allocation for child resource
3679 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3680 if(!newChildResource)
3682 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3683 return OC_STACK_ERROR;
3686 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3687 newChildResource->next = NULL;
3689 if(!resource->rsrcChildResourcesHead)
3691 resource->rsrcChildResourcesHead = newChildResource;
3694 tempChildResource->next = newChildResource;
3697 OIC_LOG(INFO, TAG, "resource bound");
3699 #ifdef WITH_PRESENCE
3700 if (presenceResource.handle)
3702 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3703 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3704 OC_PRESENCE_TRIGGER_CHANGE);
3711 OCStackResult OCUnBindResource(
3712 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3714 OCResource *resource = NULL;
3715 OCChildResource *tempChildResource = NULL;
3716 OCChildResource *tempLastChildResource = NULL;
3718 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3720 // Validate parameters
3721 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3722 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3723 // Container cannot contain itself
3724 if (collectionHandle == resourceHandle)
3726 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3727 return OC_STACK_INVALID_PARAM;
3730 // Use the handle to find the resource in the resource linked list
3731 resource = findResource((OCResource *) collectionHandle);
3734 OIC_LOG(ERROR, TAG, "Collection handle not found");
3735 return OC_STACK_INVALID_PARAM;
3738 // Look for an open slot to add add the child resource.
3739 // If found, add it and return success
3740 if(!resource->rsrcChildResourcesHead)
3742 OIC_LOG(INFO, TAG, "resource not found in collection");
3744 // Unable to add resourceHandle, so return error
3745 return OC_STACK_ERROR;
3749 tempChildResource = resource->rsrcChildResourcesHead;
3751 while (tempChildResource)
3753 if(tempChildResource->rsrcResource == resourceHandle)
3755 // if resource going to be unbinded is the head one.
3756 if( tempChildResource == resource->rsrcChildResourcesHead )
3758 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3759 OICFree(resource->rsrcChildResourcesHead);
3760 resource->rsrcChildResourcesHead = temp;
3765 OCChildResource *temp = tempChildResource->next;
3766 OICFree(tempChildResource);
3767 if (tempLastChildResource)
3769 tempLastChildResource->next = temp;
3774 OIC_LOG(INFO, TAG, "resource unbound");
3776 // Send notification when resource is unbounded successfully.
3777 #ifdef WITH_PRESENCE
3778 if (presenceResource.handle)
3780 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3781 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3782 OC_PRESENCE_TRIGGER_CHANGE);
3785 tempChildResource = NULL;
3786 tempLastChildResource = NULL;
3792 tempLastChildResource = tempChildResource;
3793 tempChildResource = tempChildResource->next;
3796 OIC_LOG(INFO, TAG, "resource not found in collection");
3798 tempChildResource = NULL;
3799 tempLastChildResource = NULL;
3801 // Unable to add resourceHandle, so return error
3802 return OC_STACK_ERROR;
3805 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3807 if (!resourceItemName)
3811 // Per RFC 6690 only registered values must follow the first rule below.
3812 // At this point in time the only values registered begin with "core", and
3813 // all other values are specified as opaque strings where multiple values
3814 // are separated by a space.
3815 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3817 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3819 if (resourceItemName[index] != '.'
3820 && resourceItemName[index] != '-'
3821 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3822 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3830 for (size_t index = 0; resourceItemName[index]; ++index)
3832 if (resourceItemName[index] == ' '
3833 || resourceItemName[index] == '\t'
3834 || resourceItemName[index] == '\r'
3835 || resourceItemName[index] == '\n')
3845 OCStackResult BindResourceTypeToResource(OCResource* resource,
3846 const char *resourceTypeName)
3848 OCResourceType *pointer = NULL;
3850 OCStackResult result = OC_STACK_ERROR;
3852 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3854 if (!ValidateResourceTypeInterface(resourceTypeName))
3856 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3857 return OC_STACK_INVALID_PARAM;
3860 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3863 result = OC_STACK_NO_MEMORY;
3867 str = OICStrdup(resourceTypeName);
3870 result = OC_STACK_NO_MEMORY;
3873 pointer->resourcetypename = str;
3874 pointer->next = NULL;
3876 insertResourceType(resource, pointer);
3877 result = OC_STACK_OK;
3880 if (result != OC_STACK_OK)
3889 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3890 const char *resourceInterfaceName)
3892 OCResourceInterface *pointer = NULL;
3894 OCStackResult result = OC_STACK_ERROR;
3896 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3898 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3900 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3901 return OC_STACK_INVALID_PARAM;
3904 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3906 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3909 result = OC_STACK_NO_MEMORY;
3913 str = OICStrdup(resourceInterfaceName);
3916 result = OC_STACK_NO_MEMORY;
3919 pointer->name = str;
3921 // Bind the resourceinterface to the resource
3922 insertResourceInterface(resource, pointer);
3924 result = OC_STACK_OK;
3927 if (result != OC_STACK_OK)
3936 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3937 const char *resourceTypeName)
3940 OCStackResult result = OC_STACK_ERROR;
3941 OCResource *resource = NULL;
3943 resource = findResource((OCResource *) handle);
3946 OIC_LOG(ERROR, TAG, "Resource not found");
3947 return OC_STACK_ERROR;
3950 result = BindResourceTypeToResource(resource, resourceTypeName);
3952 #ifdef WITH_PRESENCE
3953 if(presenceResource.handle)
3955 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3956 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3963 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3964 const char *resourceInterfaceName)
3967 OCStackResult result = OC_STACK_ERROR;
3968 OCResource *resource = NULL;
3970 resource = findResource((OCResource *) handle);
3973 OIC_LOG(ERROR, TAG, "Resource not found");
3974 return OC_STACK_ERROR;
3977 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3979 #ifdef WITH_PRESENCE
3980 if (presenceResource.handle)
3982 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3983 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3990 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3992 OCResource *pointer = headResource;
3994 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3998 *numResources = *numResources + 1;
3999 pointer = pointer->next;
4004 OCResourceHandle OCGetResourceHandle(uint8_t index)
4006 OCResource *pointer = headResource;
4008 for( uint8_t i = 0; i < index && pointer; ++i)
4010 pointer = pointer->next;
4012 return (OCResourceHandle) pointer;
4015 OCStackResult OCDeleteResource(OCResourceHandle handle)
4019 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4020 return OC_STACK_INVALID_PARAM;
4023 OCResource *resource = findResource((OCResource *) handle);
4024 if (resource == NULL)
4026 OIC_LOG(ERROR, TAG, "Resource not found");
4027 return OC_STACK_NO_RESOURCE;
4030 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4032 OIC_LOG(ERROR, TAG, "Error deleting resource");
4033 return OC_STACK_ERROR;
4039 const char *OCGetResourceUri(OCResourceHandle handle)
4041 OCResource *resource = NULL;
4043 resource = findResource((OCResource *) handle);
4046 return resource->uri;
4048 return (const char *) NULL;
4051 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4053 OCResource *resource = NULL;
4055 resource = findResource((OCResource *) handle);
4058 return resource->resourceProperties;
4060 return (OCResourceProperty)-1;
4063 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4064 uint8_t *numResourceTypes)
4066 OCResource *resource = NULL;
4067 OCResourceType *pointer = NULL;
4069 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4070 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4072 *numResourceTypes = 0;
4074 resource = findResource((OCResource *) handle);
4077 pointer = resource->rsrcType;
4080 *numResourceTypes = *numResourceTypes + 1;
4081 pointer = pointer->next;
4087 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4089 OCResourceType *resourceType = NULL;
4091 resourceType = findResourceTypeAtIndex(handle, index);
4094 return resourceType->resourcetypename;
4096 return (const char *) NULL;
4099 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4100 uint8_t *numResourceInterfaces)
4102 OCResourceInterface *pointer = NULL;
4103 OCResource *resource = NULL;
4105 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4106 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4108 *numResourceInterfaces = 0;
4109 resource = findResource((OCResource *) handle);
4112 pointer = resource->rsrcInterface;
4115 *numResourceInterfaces = *numResourceInterfaces + 1;
4116 pointer = pointer->next;
4122 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4124 OCResourceInterface *resourceInterface = NULL;
4126 resourceInterface = findResourceInterfaceAtIndex(handle, index);
4127 if (resourceInterface)
4129 return resourceInterface->name;
4131 return (const char *) NULL;
4134 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4137 OCResource *resource = NULL;
4138 OCChildResource *tempChildResource = NULL;
4141 resource = findResource((OCResource *) collectionHandle);
4147 tempChildResource = resource->rsrcChildResourcesHead;
4149 while(tempChildResource)
4153 return tempChildResource->rsrcResource;
4156 tempChildResource = tempChildResource->next;
4159 // In this case, the number of resource handles in the collection exceeds the index
4160 tempChildResource = NULL;
4164 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4165 OCEntityHandler entityHandler,
4166 void* callbackParam)
4168 OCResource *resource = NULL;
4170 // Validate parameters
4171 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4173 // Use the handle to find the resource in the resource linked list
4174 resource = findResource((OCResource *)handle);
4177 OIC_LOG(ERROR, TAG, "Resource not found");
4178 return OC_STACK_ERROR;
4182 resource->entityHandler = entityHandler;
4183 resource->entityHandlerCallbackParam = callbackParam;
4185 #ifdef WITH_PRESENCE
4186 if (presenceResource.handle)
4188 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4189 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4196 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4198 OCResource *resource = NULL;
4200 resource = findResource((OCResource *)handle);
4203 OIC_LOG(ERROR, TAG, "Resource not found");
4208 return resource->entityHandler;
4211 void incrementSequenceNumber(OCResource * resPtr)
4213 // Increment the sequence number
4214 resPtr->sequenceNum += 1;
4215 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4217 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4222 #ifdef WITH_PRESENCE
4223 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4224 OCPresenceTrigger trigger)
4226 OIC_LOG(INFO, TAG, "SendPresenceNotification");
4227 OCResource *resPtr = NULL;
4228 OCStackResult result = OC_STACK_ERROR;
4229 OCMethod method = OC_REST_PRESENCE;
4230 uint32_t maxAge = 0;
4231 resPtr = findResource((OCResource *) presenceResource.handle);
4234 return OC_STACK_NO_RESOURCE;
4237 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4239 maxAge = presenceResource.presenceTTL;
4241 result = SendAllObserverNotification(method, resPtr, maxAge,
4242 trigger, resourceType, OC_LOW_QOS);
4248 OCStackResult SendStopNotification()
4250 OIC_LOG(INFO, TAG, "SendStopNotification");
4251 OCResource *resPtr = NULL;
4252 OCStackResult result = OC_STACK_ERROR;
4253 OCMethod method = OC_REST_PRESENCE;
4254 resPtr = findResource((OCResource *) presenceResource.handle);
4257 return OC_STACK_NO_RESOURCE;
4260 // maxAge is 0. ResourceType is NULL.
4261 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4267 #endif // WITH_PRESENCE
4268 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4270 OCResource *resPtr = NULL;
4271 OCStackResult result = OC_STACK_ERROR;
4272 OCMethod method = OC_REST_NOMETHOD;
4273 uint32_t maxAge = 0;
4275 OIC_LOG(INFO, TAG, "Notifying all observers");
4276 #ifdef WITH_PRESENCE
4277 if(handle == presenceResource.handle)
4281 #endif // WITH_PRESENCE
4282 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4284 // Verify that the resource exists
4285 resPtr = findResource ((OCResource *) handle);
4288 return OC_STACK_NO_RESOURCE;
4292 //only increment in the case of regular observing (not presence)
4293 incrementSequenceNumber(resPtr);
4294 method = OC_REST_OBSERVE;
4295 maxAge = MAX_OBSERVE_AGE;
4296 #ifdef WITH_PRESENCE
4297 result = SendAllObserverNotification (method, resPtr, maxAge,
4298 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4300 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4307 OCNotifyListOfObservers (OCResourceHandle handle,
4308 OCObservationId *obsIdList,
4309 uint8_t numberOfIds,
4310 const OCRepPayload *payload,
4311 OCQualityOfService qos)
4313 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4315 OCResource *resPtr = NULL;
4316 //TODO: we should allow the server to define this
4317 uint32_t maxAge = MAX_OBSERVE_AGE;
4319 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4320 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4321 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4323 resPtr = findResource ((OCResource *) handle);
4324 if (NULL == resPtr || myStackMode == OC_CLIENT)
4326 return OC_STACK_NO_RESOURCE;
4330 incrementSequenceNumber(resPtr);
4332 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4333 payload, maxAge, qos));
4336 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4338 OIC_TRACE_BEGIN(%s:OCDoResponse, TAG);
4339 OCStackResult result = OC_STACK_ERROR;
4340 OCServerRequest *serverRequest = NULL;
4342 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4344 // Validate input parameters
4345 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4346 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4349 // Get pointer to request info
4350 serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
4353 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4354 result = serverRequest->ehResponseHandler(ehResponse);
4361 //#ifdef DIRECT_PAIRING
4362 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4364 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4365 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4367 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4371 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4374 const OCDPDev_t* OCGetDirectPairedDevices()
4376 return (const OCDPDev_t*)DPGetPairedDevices();
4379 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4380 OCDirectPairingCB resultCallback)
4382 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4383 if(NULL == peer || NULL == pinNumber)
4385 OIC_LOG(ERROR, TAG, "Invalid parameters");
4386 return OC_STACK_INVALID_PARAM;
4388 if (NULL == resultCallback)
4390 OIC_LOG(ERROR, TAG, "Invalid callback");
4391 return OC_STACK_INVALID_CALLBACK;
4394 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4395 pinNumber, (OCDirectPairingResultCB)resultCallback);
4397 //#endif // DIRECT_PAIRING
4399 //-----------------------------------------------------------------------------
4400 // Private internal function definitions
4401 //-----------------------------------------------------------------------------
4402 static OCDoHandle GenerateInvocationHandle()
4404 OCDoHandle handle = NULL;
4405 // Generate token here, it will be deleted when the transaction is deleted
4406 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4409 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4415 #ifdef WITH_PRESENCE
4416 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4417 OCResourceProperty resourceProperties, uint8_t enable)
4421 return OC_STACK_INVALID_PARAM;
4423 if (resourceProperties
4424 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4426 OIC_LOG(ERROR, TAG, "Invalid property");
4427 return OC_STACK_INVALID_PARAM;
4431 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4435 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4441 OCStackResult initResources()
4443 OCStackResult result = OC_STACK_OK;
4445 headResource = NULL;
4446 tailResource = NULL;
4447 // Init Virtual Resources
4448 #ifdef WITH_PRESENCE
4449 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4451 result = OCCreateResource(&presenceResource.handle,
4452 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4454 OC_RSRVD_PRESENCE_URI,
4458 //make resource inactive
4459 result = OCChangeResourceProperty(
4460 &(((OCResource *) presenceResource.handle)->resourceProperties),
4463 #ifndef WITH_ARDUINO
4464 if (result == OC_STACK_OK)
4466 result = SRMInitSecureResources();
4470 if(result == OC_STACK_OK)
4472 CreateResetProfile();
4473 result = OCCreateResource(&deviceResource,
4474 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4475 OC_RSRVD_INTERFACE_DEFAULT,
4476 OC_RSRVD_DEVICE_URI,
4480 if(result == OC_STACK_OK)
4482 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4483 OC_RSRVD_INTERFACE_READ);
4487 if(result == OC_STACK_OK)
4489 result = OCCreateResource(&platformResource,
4490 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4491 OC_RSRVD_INTERFACE_DEFAULT,
4492 OC_RSRVD_PLATFORM_URI,
4496 if(result == OC_STACK_OK)
4498 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4499 OC_RSRVD_INTERFACE_READ);
4506 void insertResource(OCResource *resource)
4510 headResource = resource;
4511 tailResource = resource;
4515 tailResource->next = resource;
4516 tailResource = resource;
4518 resource->next = NULL;
4521 OCResource *findResource(OCResource *resource)
4523 OCResource *pointer = headResource;
4527 if (pointer == resource)
4531 pointer = pointer->next;
4536 void deleteAllResources()
4538 OCResource *pointer = headResource;
4539 OCResource *temp = NULL;
4543 temp = pointer->next;
4544 #ifdef WITH_PRESENCE
4545 if (pointer != (OCResource *) presenceResource.handle)
4547 #endif // WITH_PRESENCE
4548 deleteResource(pointer);
4549 #ifdef WITH_PRESENCE
4551 #endif // WITH_PRESENCE
4554 memset(&platformResource, 0, sizeof(platformResource));
4555 memset(&deviceResource, 0, sizeof(deviceResource));
4557 memset(&brokerResource, 0, sizeof(brokerResource));
4560 SRMDeInitSecureResources();
4562 #ifdef WITH_PRESENCE
4563 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4564 // presence notification attributed to their deletion to be processed.
4565 deleteResource((OCResource *) presenceResource.handle);
4566 memset(&presenceResource, 0, sizeof(presenceResource));
4567 #endif // WITH_PRESENCE
4570 OCStackResult deleteResource(OCResource *resource)
4572 OCResource *prev = NULL;
4573 OCResource *temp = NULL;
4576 OIC_LOG(DEBUG,TAG,"resource is NULL");
4577 return OC_STACK_INVALID_PARAM;
4580 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4582 temp = headResource;
4585 if (temp == resource)
4587 // Invalidate all Resource Properties.
4588 resource->resourceProperties = (OCResourceProperty) 0;
4589 #ifdef WITH_PRESENCE
4590 if(resource != (OCResource *) presenceResource.handle)
4592 #endif // WITH_PRESENCE
4593 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4594 #ifdef WITH_PRESENCE
4597 if(presenceResource.handle)
4599 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4600 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4603 // Only resource in list.
4604 if (temp == headResource && temp == tailResource)
4606 headResource = NULL;
4607 tailResource = NULL;
4610 else if (temp == headResource)
4612 headResource = temp->next;
4615 else if (temp == tailResource && prev)
4617 tailResource = prev;
4618 tailResource->next = NULL;
4622 prev->next = temp->next;
4625 deleteResourceElements(temp);
4636 return OC_STACK_ERROR;
4639 void deleteResourceElements(OCResource *resource)
4648 OICFree(resource->uri);
4649 resource->uri = NULL;
4651 if (resource->rsrcType)
4653 deleteResourceType(resource->rsrcType);
4654 resource->rsrcType = NULL;
4656 if (resource->rsrcInterface)
4658 deleteResourceInterface(resource->rsrcInterface);
4659 resource->rsrcInterface = NULL;
4661 if (resource->rsrcChildResourcesHead)
4663 deleteResourceChild(resource->rsrcChildResourcesHead);
4664 resource->rsrcChildResourcesHead = NULL;
4666 if (resource->rsrcAttributes)
4668 OCDeleteResourceAttributes(resource->rsrcAttributes);
4669 resource->rsrcAttributes = NULL;
4674 void deleteResourceType(OCResourceType *resourceType)
4676 OCResourceType *next = NULL;
4678 for (OCResourceType *pointer = resourceType; pointer; pointer = next)
4680 next = pointer->next ? pointer->next : NULL;
4681 if (pointer->resourcetypename)
4683 OICFree(pointer->resourcetypename);
4684 pointer->resourcetypename = NULL;
4690 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4692 OCResourceInterface *next = NULL;
4693 for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
4695 next = pointer->next ? pointer->next : NULL;
4698 OICFree(pointer->name);
4699 pointer->name = NULL;
4705 void deleteResourceChild(OCChildResource *resourceChild)
4707 OCChildResource *next = NULL;
4708 for (OCChildResource *pointer = resourceChild; pointer; pointer = next)
4710 next = pointer->next ? pointer->next : NULL;
4711 if (pointer->rsrcResource)
4713 deleteResourceElements(pointer->rsrcResource);
4714 pointer->rsrcResource = NULL;
4720 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
4722 OCAttribute *next = NULL;
4723 for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
4725 next = pointer->next ? pointer->next : NULL;
4726 if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
4728 OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
4729 pointer->attrValue = NULL;
4731 else if (pointer->attrValue)
4733 OICFree(pointer->attrValue);
4734 pointer->attrValue = NULL;
4736 if (pointer->attrName)
4738 OICFree(pointer->attrName);
4739 pointer->attrName = NULL;
4745 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4747 OCResourceType *pointer = NULL;
4748 OCResourceType *previous = NULL;
4749 if (!resource || !resourceType)
4753 // resource type list is empty.
4754 else if (!resource->rsrcType)
4756 resource->rsrcType = resourceType;
4760 pointer = resource->rsrcType;
4764 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4766 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4767 OICFree(resourceType->resourcetypename);
4768 OICFree(resourceType);
4772 pointer = pointer->next;
4777 previous->next = resourceType;
4780 resourceType->next = NULL;
4782 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4785 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4787 OCResource *resource = NULL;
4788 OCResourceType *pointer = NULL;
4790 // Find the specified resource
4791 resource = findResource((OCResource *) handle);
4797 // Make sure a resource has a resourcetype
4798 if (!resource->rsrcType)
4803 // Iterate through the list
4804 pointer = resource->rsrcType;
4805 for(uint8_t i = 0; i< index && pointer; ++i)
4807 pointer = pointer->next;
4812 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4814 if(resourceTypeList && resourceTypeName)
4816 OCResourceType * rtPointer = resourceTypeList;
4817 while(resourceTypeName && rtPointer)
4819 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4820 if(rtPointer->resourcetypename &&
4821 strcmp(resourceTypeName, (const char *)
4822 (rtPointer->resourcetypename)) == 0)
4826 rtPointer = rtPointer->next;
4834 * Insert a new interface into interface linked list only if not already present.
4835 * If alredy present, 2nd arg is free'd.
4836 * Default interface will always be first if present.
4838 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4840 OCResourceInterface *pointer = NULL;
4841 OCResourceInterface *previous = NULL;
4843 newInterface->next = NULL;
4845 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4847 if (!*firstInterface)
4849 // If first interface is not oic.if.baseline, by default add it as first interface type.
4850 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4852 *firstInterface = newInterface;
4856 OCStackResult result = BindResourceInterfaceToResource(resource,
4857 OC_RSRVD_INTERFACE_DEFAULT);
4858 if (result != OC_STACK_OK)
4860 OICFree(newInterface->name);
4861 OICFree(newInterface);
4864 if (*firstInterface)
4866 (*firstInterface)->next = newInterface;
4870 // If once add oic.if.baseline, later too below code take care of freeing memory.
4871 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4873 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4875 OICFree(newInterface->name);
4876 OICFree(newInterface);
4879 // This code will not hit anymore, keeping
4882 newInterface->next = *firstInterface;
4883 *firstInterface = newInterface;
4888 pointer = *firstInterface;
4891 if (strcmp(newInterface->name, pointer->name) == 0)
4893 OICFree(newInterface->name);
4894 OICFree(newInterface);
4898 pointer = pointer->next;
4903 previous->next = newInterface;
4908 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4911 OCResource *resource = NULL;
4912 OCResourceInterface *pointer = NULL;
4914 // Find the specified resource
4915 resource = findResource((OCResource *) handle);
4921 // Make sure a resource has a resourceinterface
4922 if (!resource->rsrcInterface)
4927 // Iterate through the list
4928 pointer = resource->rsrcInterface;
4930 for (uint8_t i = 0; i < index && pointer; ++i)
4932 pointer = pointer->next;
4938 * This function splits the uri using the '?' delimiter.
4939 * "uriWithoutQuery" is the block of characters between the beginning
4940 * till the delimiter or '\0' which ever comes first.
4941 * "query" is whatever is to the right of the delimiter if present.
4942 * No delimiter sets the query to NULL.
4943 * If either are present, they will be malloc'ed into the params 2, 3.
4944 * The first param, *uri is left untouched.
4946 * NOTE: This function does not account for whitespace at the end of the uri NOR
4947 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4948 * part of the query.
4950 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4954 return OC_STACK_INVALID_URI;
4956 if(!query || !uriWithoutQuery)
4958 return OC_STACK_INVALID_PARAM;
4962 *uriWithoutQuery = NULL;
4964 size_t uriWithoutQueryLen = 0;
4965 size_t queryLen = 0;
4966 size_t uriLen = strlen(uri);
4968 char *pointerToDelimiter = strstr(uri, "?");
4970 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4971 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4973 if (uriWithoutQueryLen)
4975 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4976 if (!*uriWithoutQuery)
4980 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4984 *query = (char *) OICCalloc(queryLen + 1, 1);
4987 OICFree(*uriWithoutQuery);
4988 *uriWithoutQuery = NULL;
4991 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4997 return OC_STACK_NO_MEMORY;
5000 const char* OCGetServerInstanceIDString(void)
5002 static char sidStr[UUID_STRING_SIZE];
5004 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5006 OIC_LOG(FATAL, TAG, "GetDoxmDeviceID failed!");
5010 if (OCConvertUuidToString(sid.id, sidStr) != RAND_UUID_OK)
5012 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5019 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5021 OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5022 CAResult_t retResult = CA_STATUS_FAILED;
5023 CAResult_t caResult = CA_STATUS_OK;
5025 CATransportAdapter_t connTypes[] = {
5027 CA_ADAPTER_RFCOMM_BTEDR,
5028 CA_ADAPTER_GATT_BTLE,
5031 ,CA_ADAPTER_REMOTE_ACCESS
5038 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5040 for(int i = 0; i < numConnTypes; i++)
5042 // If CA status is not initialized, CASelectNetwork() will not be called.
5043 if (caResult != CA_STATUS_NOT_INITIALIZED)
5045 if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5047 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5048 caResult = CASelectNetwork(connTypes[i]);
5049 if (caResult == CA_STATUS_OK)
5051 retResult = CA_STATUS_OK;
5056 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5061 if (retResult != CA_STATUS_OK)
5063 return caResult; // Returns error of appropriate transport that failed fatally.
5069 OCStackResult CAResultToOCResult(CAResult_t caResult)
5075 case CA_STATUS_INVALID_PARAM:
5076 return OC_STACK_INVALID_PARAM;
5077 case CA_ADAPTER_NOT_ENABLED:
5078 return OC_STACK_ADAPTER_NOT_ENABLED;
5079 case CA_SERVER_STARTED_ALREADY:
5081 case CA_SERVER_NOT_STARTED:
5082 return OC_STACK_ERROR;
5083 case CA_DESTINATION_NOT_REACHABLE:
5084 return OC_STACK_COMM_ERROR;
5085 case CA_SOCKET_OPERATION_FAILED:
5086 return OC_STACK_COMM_ERROR;
5087 case CA_SEND_FAILED:
5088 return OC_STACK_COMM_ERROR;
5089 case CA_RECEIVE_FAILED:
5090 return OC_STACK_COMM_ERROR;
5091 case CA_MEMORY_ALLOC_FAILED:
5092 return OC_STACK_NO_MEMORY;
5093 case CA_REQUEST_TIMEOUT:
5094 return OC_STACK_TIMEOUT;
5095 case CA_DESTINATION_DISCONNECTED:
5096 return OC_STACK_COMM_ERROR;
5097 case CA_STATUS_FAILED:
5098 return OC_STACK_ERROR;
5099 case CA_NOT_SUPPORTED:
5100 return OC_STACK_NOTIMPL;
5102 return OC_STACK_ERROR;
5106 bool OCResultToSuccess(OCStackResult ocResult)
5111 case OC_STACK_RESOURCE_CREATED:
5112 case OC_STACK_RESOURCE_DELETED:
5113 case OC_STACK_CONTINUE:
5114 case OC_STACK_RESOURCE_CHANGED:
5115 case OC_STACK_SLOW_RESOURCE:
5123 OCStackResult OCSetProxyURI(const char *uri)
5125 return CAResultToOCResult(CASetProxyUri(uri));
5129 #if defined(RD_CLIENT) || defined(RD_SERVER)
5130 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5132 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5134 OCResource *resource = NULL;
5136 resource = findResource((OCResource *) handle);
5139 OIC_LOG(ERROR, TAG, "Resource not found");
5140 return OC_STACK_ERROR;
5143 resource->ins = ins;
5149 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5150 const OCClientResponse *response)
5152 // Validate input parameters
5153 VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5154 VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5156 char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5159 return OC_STACK_NO_MEMORY;
5161 strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5163 if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5165 OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5167 char rdPubUri[MAX_URI_LENGTH] = { 0 };
5168 snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5169 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5171 if (strcmp(rdPubUri, targetUri) == 0)
5173 // Update resource unique id in stack.
5176 if (response->payload)
5178 OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5179 OCRepPayload **links = NULL;
5180 size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5181 if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5182 &links, dimensions))
5185 for (; i < dimensions[0]; i++)
5188 if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5190 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5192 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5194 OCBindResourceInsToResource(handle, ins);
5203 else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5205 OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5207 uint8_t numResources = 0;
5208 OCGetNumberOfResources(&numResources);
5210 char *ins = strstr(targetUri, OC_RSRVD_INS);
5213 for (uint8_t i = 0; i < numResources; i++)
5215 OCResourceHandle resHandle = OCGetResourceHandle(i);
5218 OCBindResourceInsToResource(resHandle, 0);
5224 const char *token = "&";
5225 char *iterTokenPtr = NULL;
5226 char *start = strtok_r(targetUri, token, &iterTokenPtr);
5228 while (start != NULL)
5230 char *query = start;
5231 query = strstr(query, OC_RSRVD_INS);
5234 int64_t queryIns = atoi(query + 4);
5235 for (uint8_t i = 0; i < numResources; i++)
5237 OCResourceHandle resHandle = OCGetResourceHandle(i);
5241 OCGetResourceIns(resHandle, &resIns);
5242 if (queryIns && queryIns == resIns)
5244 OCBindResourceInsToResource(resHandle, 0);
5250 start = strtok_r(NULL, token, &iterTokenPtr);
5259 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5263 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5267 OCResource *pointer = headResource;
5271 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5273 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5276 pointer = pointer->next;
5281 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t *ins)
5283 OCResource *resource = NULL;
5285 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5286 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5288 resource = findResource((OCResource *) handle);
5291 *ins = resource->ins;
5294 return OC_STACK_ERROR;
5298 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5299 void* optionData, size_t optionDataLength)
5303 OIC_LOG (INFO, TAG, "Header options are NULL");
5304 return OC_STACK_INVALID_PARAM;
5309 OIC_LOG (INFO, TAG, "optionData are NULL");
5310 return OC_STACK_INVALID_PARAM;
5315 OIC_LOG (INFO, TAG, "numOptions is NULL");
5316 return OC_STACK_INVALID_PARAM;
5319 if (*numOptions >= MAX_HEADER_OPTIONS)
5321 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5322 return OC_STACK_NO_MEMORY;
5325 ocHdrOpt += *numOptions;
5326 ocHdrOpt->protocolID = OC_COAP_ID;
5327 ocHdrOpt->optionID = optionID;
5328 ocHdrOpt->optionLength =
5329 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
5330 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5331 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5337 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5338 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5340 if (!ocHdrOpt || !numOptions)
5342 OIC_LOG (INFO, TAG, "No options present");
5348 OIC_LOG (INFO, TAG, "optionData are NULL");
5349 return OC_STACK_INVALID_PARAM;
5352 if (!receivedDataLength)
5354 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5355 return OC_STACK_INVALID_PARAM;
5358 for (uint8_t i = 0; i < numOptions; i++)
5360 if (ocHdrOpt[i].optionID == optionID)
5362 if (optionDataLength >= ocHdrOpt->optionLength)
5364 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5365 *receivedDataLength = ocHdrOpt->optionLength;
5370 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5371 return OC_STACK_ERROR;
5378 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5380 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5381 if (g_adapterHandler)
5383 g_adapterHandler(adapter, enabled);
5387 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5389 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5390 if (g_connectionHandler)
5392 g_connectionHandler(info, isConnected);
5396 * If the client observes one or more resources over a reliable connection,
5397 * then the CoAP server (or intermediary in the role of the CoAP server)
5398 * MUST remove all entries associated with the client endpoint from the lists
5399 * of observers when the connection is either closed or times out.
5403 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5404 CopyEndpointToDevAddr(info, &devAddr);
5406 // remove observer list with remote device address.
5407 DeleteObserverUsingDevAddr(&devAddr);
5411 void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
5412 CAConnectionStateChangedCB connectionHandler)
5414 OIC_LOG(DEBUG, TAG, "OCSetNetworkMonitorHandler");
5415 g_adapterHandler = adapterHandler;
5416 g_connectionHandler = connectionHandler;
5419 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5422 OCStackResult ret = OC_STACK_ERROR;
5424 ret = GetDoxmDeviceID(&oicUuid);
5425 if (OC_STACK_OK == ret)
5427 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5431 OIC_LOG(ERROR, TAG, "Device ID Get error");
5436 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5439 OCStackResult ret = OC_STACK_ERROR;
5441 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5442 for (int i = 0; i < UUID_LENGTH; i++)
5444 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5446 ret = SetDoxmDeviceID(&oicUuid);
5450 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5452 bool isDeviceOwned = true;
5453 OCStackResult ret = OC_STACK_ERROR;
5455 ret = GetDoxmIsOwned(&isDeviceOwned);
5456 if (OC_STACK_OK == ret)
5458 *isOwned = isDeviceOwned;
5462 OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5467 void OCClearCallBackList()
5469 DeleteClientCBList();
5472 void OCClearObserverlist()
5474 DeleteObserverList();
5477 int OCEncrypt(const unsigned char *pt, size_t pt_len,
5478 unsigned char **ct, size_t *ct_len)
5480 #ifndef __SECURE_PSI__
5481 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5484 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5486 return psiEncrypt(pt, pt_len, ct, ct_len);
5487 #endif // __SECURE_PSI__
5490 int OCDecrypt(const unsigned char *ct, size_t ct_len,
5491 unsigned char **pt, size_t *pt_len)
5493 #ifndef __SECURE_PSI__
5494 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5497 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5499 return psiDecrypt(ct, ct_len, pt, pt_len);
5500 #endif // __SECURE_PSI__
5503 OCStackResult OCSetKey(const unsigned char* key)
5505 #ifndef __SECURE_PSI__
5506 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5509 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5511 return psiSetKey(key);
5512 #endif // __SECURE_PSI__
5515 OCStackResult OCGetKey(unsigned char* key)
5517 #ifndef __SECURE_PSI__
5518 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5521 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5523 return psiGetKey(key);
5524 #endif // __SECURE_PSI__
5527 OCStackResult OCSetSecurePSI(const unsigned char *key, const OCPersistentStorage *psPlain,
5528 const OCPersistentStorage *psEnc, const OCPersistentStorage *psRescue)
5530 #ifndef __SECURE_PSI__
5531 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5534 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5536 return setSecurePSI(key, psPlain, psEnc, psRescue);
5537 #endif // __SECURE_PSI__
5540 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5541 static void OtmEventHandler(const char *addr, uint16_t port, const char *uuid, int event)
5543 if (g_otmEventHandler.cb)
5545 g_otmEventHandler.cb(g_otmEventHandler.ctx, addr, port, uuid, event);
5550 * It is already declared in srmutility.h.
5551 * We can't include the header file, because of "redefined VERIFY_NON_NULL"
5553 typedef void (*OicSecOtmEventHandler_t)(const char* addr, uint16_t port,
5554 const char* uuid, int event);
5555 void SetOtmEventHandler(OicSecOtmEventHandler_t otmEventHandler);
5558 OCStackResult OCSetOtmEventHandler(void *ctx, OCOtmEventHandler cb)
5560 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5561 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5563 g_otmEventHandler.cb = cb;
5564 g_otmEventHandler.ctx = ctx;
5566 if (g_otmEventHandler.cb)
5568 OIC_LOG(DEBUG, TAG, "SET OCOtmEventHandler");
5569 SetOtmEventHandler(OtmEventHandler);
5573 OIC_LOG(DEBUG, TAG, "UNSET OCOtmEventHandler");
5574 SetOtmEventHandler(NULL);
5577 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);