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, "Before calling into application address space for presence");
1280 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1281 OIC_LOG(INFO, TAG, "After calling into application address space for presence");
1283 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1285 FindAndDeleteClientCB(cbNode);
1289 OCPayloadDestroy(response.payload);
1292 #endif // WITH_PRESENCE
1294 OCStackResult HandleBatchResponse(char *requestUri, OCRepPayload **payload)
1296 if (requestUri && *payload)
1298 char *interfaceName = NULL;
1299 char *rtTypeName = NULL;
1300 char *uriQuery = NULL;
1301 char *uriWithoutQuery = NULL;
1302 if (OC_STACK_OK == getQueryFromUri(requestUri, &uriQuery, &uriWithoutQuery))
1304 if (OC_STACK_OK == ExtractFiltersFromQuery(uriQuery, &interfaceName, &rtTypeName))
1306 if (interfaceName && (0 == strcmp(OC_RSRVD_INTERFACE_BATCH, interfaceName)))
1308 char *uri = (*payload)->uri;
1309 if (uri && 0 != strcmp(uriWithoutQuery, uri))
1311 OCRepPayload *newPayload = OCRepPayloadCreate();
1314 OCRepPayloadSetUri(newPayload, uri);
1315 newPayload->next = *payload;
1316 *payload = newPayload;
1323 OICFree(interfaceName);
1324 OICFree(rtTypeName);
1326 OICFree(uriWithoutQuery);
1329 return OC_STACK_INVALID_PARAM;
1332 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1334 OIC_TRACE_MARK(%s:OCHandleResponse:%s, TAG, responseInfo->info.resourceUri);
1335 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1337 #ifdef WITH_PRESENCE
1338 if(responseInfo->info.resourceUri &&
1339 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1341 HandlePresenceResponse(endPoint, responseInfo);
1346 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1347 responseInfo->info.tokenLength, NULL, NULL);
1351 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1353 // check obs header option
1354 bool obsHeaderOpt = false;
1355 CAHeaderOption_t *options = responseInfo->info.options;
1356 for (uint8_t i = 0; i< responseInfo->info.numOptions; i++)
1358 if (options && options[i].protocolID == CA_COAP_ID &&
1359 options[i].optionID == COAP_OPTION_OBSERVE)
1361 obsHeaderOpt = true;
1366 if(responseInfo->result == CA_EMPTY)
1368 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1369 // We do not have a case for the client to receive a RESET
1370 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1372 //This is the case of receiving an ACK on a request to a slow resource!
1373 OIC_LOG(INFO, TAG, "This is a pure ACK");
1374 //TODO: should we inform the client
1375 // app that at least the request was received at the server?
1378 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1380 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1382 OCClientResponse response =
1383 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1384 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1385 FixUpClientResponse(&response);
1386 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1387 memcpy(response.identity.id, responseInfo->info.identity.id,
1388 sizeof (response.identity.id));
1389 response.identity.id_length = responseInfo->info.identity.id_length;
1391 response.result = CAResponseToOCStackResult(responseInfo->result);
1392 OIC_LOG(INFO, TAG, "Before calling into application address space for reTrans timeout");
1393 cbNode->callBack(cbNode->context,
1394 cbNode->handle, &response);
1395 OIC_LOG(INFO, TAG, "After calling into application address space for reTrans timeout");
1396 FindAndDeleteClientCB(cbNode);
1397 OICFree((void *)response.resourceUri);
1400 else if ((cbNode->method == OC_REST_OBSERVE || cbNode->method == OC_REST_OBSERVE_ALL)
1401 && (responseInfo->result == CA_CONTENT) && !obsHeaderOpt)
1403 OCClientResponse response =
1404 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1405 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1406 FixUpClientResponse(&response);
1407 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1408 memcpy(response.identity.id, responseInfo->info.identity.id,
1409 sizeof (response.identity.id));
1410 response.identity.id_length = responseInfo->info.identity.id_length;
1411 response.result = OC_STACK_UNAUTHORIZED_REQ;
1413 OIC_LOG(INFO, TAG, "Before calling into application address space for observe resp");
1414 cbNode->callBack(cbNode->context,
1417 OIC_LOG(INFO, TAG, "After calling into application address space for observe resp");
1419 FindAndDeleteClientCB(cbNode);
1420 OICFree(response.resourceUri);
1425 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1427 OCClientResponse response;
1428 memset(&response, 0, sizeof(OCClientResponse));
1429 response.devAddr.adapter = OC_DEFAULT_ADAPTER;
1431 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1432 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1433 FixUpClientResponse(&response);
1434 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1435 memcpy(response.identity.id, responseInfo->info.identity.id,
1436 sizeof (response.identity.id));
1437 response.identity.id_length = responseInfo->info.identity.id_length;
1439 response.result = CAResponseToOCStackResult(responseInfo->result);
1441 if(responseInfo->info.payload &&
1442 responseInfo->info.payloadSize)
1444 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1445 // check the security resource
1446 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1448 type = PAYLOAD_TYPE_SECURITY;
1450 else if (cbNode->method == OC_REST_DISCOVER)
1452 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1453 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1455 type = PAYLOAD_TYPE_DISCOVERY;
1458 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1460 type = PAYLOAD_TYPE_DISCOVERY;
1463 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1465 type = PAYLOAD_TYPE_REPRESENTATION;
1467 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1469 type = PAYLOAD_TYPE_REPRESENTATION;
1472 #ifdef ROUTING_GATEWAY
1473 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1475 type = PAYLOAD_TYPE_REPRESENTATION;
1478 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1480 type = PAYLOAD_TYPE_REPRESENTATION;
1483 else if (strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1485 type = PAYLOAD_TYPE_REPRESENTATION;
1490 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1491 cbNode->method, cbNode->requestUri);
1492 OICFree((void *)response.resourceUri);
1496 else if (cbNode->method == OC_REST_GET ||
1497 cbNode->method == OC_REST_PUT ||
1498 cbNode->method == OC_REST_POST ||
1499 cbNode->method == OC_REST_OBSERVE ||
1500 cbNode->method == OC_REST_OBSERVE_ALL ||
1501 cbNode->method == OC_REST_DELETE)
1503 if (cbNode->requestUri)
1505 if (0 == strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri))
1507 type = PAYLOAD_TYPE_REPRESENTATION;
1509 else if (0 == strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri))
1511 type = PAYLOAD_TYPE_REPRESENTATION;
1513 if (type == PAYLOAD_TYPE_INVALID)
1515 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1516 cbNode->method, cbNode->requestUri);
1517 type = PAYLOAD_TYPE_REPRESENTATION;
1522 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1523 type = PAYLOAD_TYPE_REPRESENTATION;
1528 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1529 cbNode->method, cbNode->requestUri);
1530 OICFree((void *)response.resourceUri);
1534 // In case of error, still want application to receive the error message.
1535 if (OCResultToSuccess(response.result) || PAYLOAD_TYPE_REPRESENTATION == type)
1537 if(OC_STACK_OK != OCParsePayload(&response.payload,
1539 responseInfo->info.payload,
1540 responseInfo->info.payloadSize))
1542 OIC_LOG(ERROR, TAG, "Error converting payload");
1543 OCPayloadDestroy(response.payload);
1544 OICFree((void *)response.resourceUri);
1550 response.resourceUri = OICStrdup(cbNode->requestUri);
1554 response.numRcvdVendorSpecificHeaderOptions = 0;
1555 if(responseInfo->info.numOptions > 0)
1558 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1559 if(responseInfo->info.options
1560 && responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1563 uint32_t observationOption;
1564 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1565 for (observationOption=0, i=0;
1566 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1570 (observationOption << 8) | optionData[i];
1572 response.sequenceNumber = observationOption;
1573 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1578 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1581 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1583 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1584 OCPayloadDestroy(response.payload);
1585 OICFree((void *)response.resourceUri);
1589 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1591 if(&(responseInfo->info.options[i]))
1593 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1594 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1599 if (cbNode->method == OC_REST_OBSERVE &&
1600 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1601 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1602 response.sequenceNumber <= cbNode->sequenceNumber)
1604 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1605 response.sequenceNumber);
1610 if (cbNode->requestUri)
1612 // if request uri is '/oic/rd', update ins value of resource.
1613 char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
1616 OCUpdateResourceInsWithResponse(cbNode->requestUri, &response);
1620 // set remoteID(device ID) into OCClientResponse callback parameter
1621 if (OC_REST_DISCOVER == cbNode->method)
1623 OIC_LOG(INFO, TAG, "cbNode method is OC_REST_DISCOVER");
1624 OCDiscoveryPayload *payload = (OCDiscoveryPayload*) response.payload;
1625 // Payload can be empty in case of error message.
1626 if (payload && payload->sid)
1628 OICStrcpy(response.devAddr.remoteId, sizeof(response.devAddr.remoteId),
1630 OIC_LOG_V(INFO_PRIVATE, TAG, "Device ID of response : %s",
1631 response.devAddr.remoteId);
1634 if(NULL == response.resourceUri)
1636 response.resourceUri = OICStrdup(cbNode->requestUri);
1640 if (cbNode->requestUri)
1642 OIC_LOG_V(INFO, TAG, "cbNode requestUri is %s", cbNode->requestUri);
1643 if (cbNode->method == OC_REST_POST &&
1644 strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1646 OCHandleKeepAliveResponse(endPoint, response.payload);
1650 if (response.payload && response.payload->type == PAYLOAD_TYPE_REPRESENTATION)
1652 OIC_LOG(INFO, TAG, "Handle batch response");
1653 HandleBatchResponse(cbNode->requestUri, (OCRepPayload **)&response.payload);
1656 OIC_LOG(INFO, TAG, "Before calling into application address space for handleResponse");
1657 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1660 OIC_LOG(INFO, TAG, "After calling into application address space for handleResponse");
1662 cbNode->sequenceNumber = response.sequenceNumber;
1664 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1666 FindAndDeleteClientCB(cbNode);
1670 // To keep discovery callbacks active.
1671 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1672 MILLISECONDS_PER_SECOND);
1676 //Need to send ACK when the response is CON
1677 if(responseInfo->info.type == CA_MSG_CONFIRM)
1679 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1681 OIC_LOG(INFO, TAG, "Received a confirmable message. Sending EMPTY");
1682 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1683 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1687 OICFree((void *)response.resourceUri);
1688 OCPayloadDestroy(response.payload);
1693 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1694 responseInfo->info.tokenLength);
1698 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1699 if(responseInfo->result == CA_EMPTY)
1701 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1702 if(responseInfo->info.type == CA_MSG_RESET)
1704 OIC_LOG(INFO, TAG, "This is a RESET");
1705 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1706 OC_OBSERVER_NOT_INTERESTED);
1708 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1710 OIC_LOG(INFO, TAG, "This is a pure ACK");
1711 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1712 OC_OBSERVER_STILL_INTERESTED);
1715 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1717 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1718 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1719 OC_OBSERVER_FAILED_COMM);
1722 FreeObserver(observer);
1726 if(!cbNode && !observer)
1728 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1729 || myStackMode == OC_GATEWAY)
1731 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1732 if(responseInfo->result == CA_EMPTY)
1734 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1738 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1740 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1741 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1742 CA_MSG_RESET, 0, NULL, NULL, 0, NULL,
1743 CA_RESPONSE_FOR_RES);
1748 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1749 || myStackMode == OC_GATEWAY)
1751 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1752 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1754 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1755 responseInfo->info.messageId);
1757 if (responseInfo->info.type == CA_MSG_RESET)
1759 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1760 responseInfo->info.messageId);
1768 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1770 VERIFY_NON_NULL_NR(endPoint, FATAL);
1771 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1773 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1774 OIC_TRACE_BEGIN(%s:HandleCAResponses, TAG);
1776 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1777 #ifdef ROUTING_GATEWAY
1778 bool needRIHandling = false;
1780 * Routing manager is going to update either of endpoint or response or both.
1781 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1782 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1785 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1787 if(ret != OC_STACK_OK || !needRIHandling)
1789 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1796 * Put source in sender endpoint so that the next packet from application can be routed to
1797 * proper destination and remove "RM" coap header option before passing request / response to
1798 * RI as this option will make no sense to either RI or application.
1800 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1801 (uint8_t *) &(responseInfo->info.numOptions),
1802 (CAEndpoint_t *) endPoint);
1805 OCHandleResponse(endPoint, responseInfo);
1807 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1811 * This function handles error response from CA
1812 * code shall be added to handle the errors
1814 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1816 VERIFY_NON_NULL_NR(endPoint, FATAL);
1817 VERIFY_NON_NULL_NR(errorInfo, FATAL);
1819 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1820 OIC_TRACE_BEGIN(%s:HandleCAErrorResponse, TAG);
1822 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1823 errorInfo->info.tokenLength, NULL, NULL);
1826 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1827 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1828 FixUpClientResponse(&response);
1829 response.resourceUri = errorInfo->info.resourceUri;
1830 memcpy(response.identity.id, errorInfo->info.identity.id,
1831 sizeof (response.identity.id));
1832 response.identity.id_length = errorInfo->info.identity.id_length;
1833 response.result = CAResultToOCResult(errorInfo->result);
1835 OIC_LOG(INFO, TAG, "Before calling into application address space for error response");
1836 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1837 OIC_LOG(INFO, TAG, "After calling into application address space for error response");
1840 ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1841 errorInfo->info.tokenLength);
1844 OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1845 OCStackResult result = CAResultToOCResult(errorInfo->result);
1846 if (OC_STACK_COMM_ERROR == result)
1848 OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1849 OC_OBSERVER_FAILED_COMM);
1853 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1858 * This function sends out Direct Stack Responses. These are responses that are not coming
1859 * from the application entity handler. These responses have no payload and are usually ACKs,
1860 * RESETs or some error conditions that were caught by the stack.
1862 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1863 const CAResponseResult_t responseResult, const CAMessageType_t type,
1864 const uint8_t numOptions, const CAHeaderOption_t *options,
1865 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1866 CADataType_t dataType)
1868 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1870 if (endPoint->flags & CA_MULTICAST)
1872 OIC_LOG(ERROR, TAG, "It is unnecessary to respond to a multicast request");
1876 CAResponseInfo_t respInfo = { .result = responseResult };
1877 respInfo.info.messageId = coapID;
1878 respInfo.info.numOptions = numOptions;
1880 if (respInfo.info.numOptions)
1882 respInfo.info.options =
1883 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1884 memcpy (respInfo.info.options, options,
1885 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1889 respInfo.info.payload = NULL;
1890 respInfo.info.token = token;
1891 respInfo.info.tokenLength = tokenLength;
1892 respInfo.info.type = type;
1893 respInfo.info.resourceUri = OICStrdup (resourceUri);
1894 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1895 respInfo.info.dataType = dataType;
1897 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1898 // Add the destination to route option from the endpoint->routeData.
1899 bool doPost = false;
1900 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1901 if(OC_STACK_OK != result)
1903 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1904 OICFree (respInfo.info.resourceUri);
1905 OICFree (respInfo.info.options);
1910 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1911 CARequestInfo_t reqInfo = {.method = CA_POST };
1912 /* The following initialization is not done in a single initializer block as in
1913 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1914 * does not have designated initalizers. This is a work-around for now.
1916 reqInfo.info.type = CA_MSG_NONCONFIRM;
1917 reqInfo.info.messageId = coapID;
1918 reqInfo.info.tokenLength = tokenLength;
1919 reqInfo.info.token = token;
1920 reqInfo.info.numOptions = respInfo.info.numOptions;
1921 reqInfo.info.payload = NULL;
1922 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1923 if (reqInfo.info.numOptions)
1925 reqInfo.info.options =
1926 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1927 if (NULL == reqInfo.info.options)
1929 OIC_LOG(ERROR, TAG, "Calloc failed");
1930 OICFree (reqInfo.info.resourceUri);
1931 OICFree (respInfo.info.resourceUri);
1932 OICFree (respInfo.info.options);
1933 return OC_STACK_NO_MEMORY;
1935 memcpy (reqInfo.info.options, respInfo.info.options,
1936 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1939 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1940 OICFree (reqInfo.info.resourceUri);
1941 OICFree (reqInfo.info.options);
1942 OICFree (respInfo.info.resourceUri);
1943 OICFree (respInfo.info.options);
1944 if (CA_STATUS_OK != caResult)
1946 OIC_LOG(ERROR, TAG, "CASendRequest error");
1947 return CAResultToOCResult(caResult);
1953 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1955 // resourceUri in the info field is cloned in the CA layer and
1956 // thus ownership is still here.
1957 OICFree (respInfo.info.resourceUri);
1958 OICFree (respInfo.info.options);
1959 if(CA_STATUS_OK != caResult)
1961 OIC_LOG(ERROR, TAG, "CASendResponse error");
1962 return CAResultToOCResult(caResult);
1965 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1969 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1971 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1972 OCStackResult result = OC_STACK_ERROR;
1973 if(!protocolRequest)
1975 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1976 return OC_STACK_INVALID_PARAM;
1979 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1980 protocolRequest->tokenLength);
1983 OIC_LOG(INFO, TAG, "This is a new Server Request");
1984 result = AddServerRequest(&request, protocolRequest->coapID,
1985 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1986 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1987 protocolRequest->observationOption, protocolRequest->qos,
1988 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1989 protocolRequest->payload, protocolRequest->requestToken,
1990 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1991 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1992 &protocolRequest->devAddr);
1993 if (OC_STACK_OK != result)
1995 OIC_LOG(ERROR, TAG, "Error adding server request");
2001 OIC_LOG(ERROR, TAG, "Out of Memory");
2002 return OC_STACK_NO_MEMORY;
2005 if(!protocolRequest->reqMorePacket)
2007 request->requestComplete = 1;
2012 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
2015 if(request->requestComplete)
2017 OIC_LOG(INFO, TAG, "This Server Request is complete");
2018 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2019 OCResource *resource = NULL;
2020 result = DetermineResourceHandling (request, &resHandling, &resource);
2021 if (result == OC_STACK_OK)
2023 result = ProcessRequest(resHandling, resource, request);
2028 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2029 result = OC_STACK_CONTINUE;
2034 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2036 OIC_TRACE_MARK(%s:OCHandleRequests:%s, TAG, requestInfo->info.resourceUri);
2037 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2039 OCStackResult requestResult = OC_STACK_ERROR;
2041 if(myStackMode == OC_CLIENT)
2043 //TODO: should the client be responding to requests?
2047 OCServerProtocolRequest serverRequest = {0};
2049 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2051 char * uriWithoutQuery = NULL;
2052 char * query = NULL;
2054 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2056 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2058 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2061 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2062 OIC_LOG_V(INFO, TAG, "Query : %s", query);
2064 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2066 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2067 OICFree(uriWithoutQuery);
2071 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2072 OICFree(uriWithoutQuery);
2079 if(strlen(query) < MAX_QUERY_LENGTH)
2081 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2086 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2092 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2094 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2095 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2096 if (!serverRequest.payload)
2098 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2101 memcpy (serverRequest.payload, requestInfo->info.payload,
2102 requestInfo->info.payloadSize);
2106 serverRequest.reqTotalSize = 0;
2109 switch (requestInfo->method)
2112 serverRequest.method = OC_REST_GET;
2115 serverRequest.method = OC_REST_PUT;
2118 serverRequest.method = OC_REST_POST;
2121 serverRequest.method = OC_REST_DELETE;
2124 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2125 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2126 requestInfo->info.type, requestInfo->info.numOptions,
2127 requestInfo->info.options, requestInfo->info.token,
2128 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2130 OICFree(serverRequest.payload);
2134 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2135 requestInfo->info.tokenLength);
2137 serverRequest.tokenLength = requestInfo->info.tokenLength;
2138 if (serverRequest.tokenLength) {
2140 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2142 if (!serverRequest.requestToken)
2144 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2145 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2146 requestInfo->info.type, requestInfo->info.numOptions,
2147 requestInfo->info.options, requestInfo->info.token,
2148 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2150 OICFree(serverRequest.payload);
2153 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2156 switch (requestInfo->info.acceptFormat)
2158 case CA_FORMAT_APPLICATION_CBOR:
2159 serverRequest.acceptFormat = OC_FORMAT_CBOR;
2161 case CA_FORMAT_UNDEFINED:
2162 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2165 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2168 if (requestInfo->info.type == CA_MSG_CONFIRM)
2170 serverRequest.qos = OC_HIGH_QOS;
2174 serverRequest.qos = OC_LOW_QOS;
2176 // CA does not need the following field
2177 // Are we sure CA does not need them? how is it responding to multicast
2178 serverRequest.delayedResNeeded = 0;
2180 serverRequest.coapID = requestInfo->info.messageId;
2182 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2184 // copy vendor specific header options
2185 uint8_t tempNum = (requestInfo->info.numOptions);
2187 // Assume no observation requested and it is a pure GET.
2188 // If obs registration/de-registration requested it'll be fetched from the
2189 // options in GetObserveHeaderOption()
2190 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2192 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2193 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2196 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2197 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2198 requestInfo->info.type, requestInfo->info.numOptions,
2199 requestInfo->info.options, requestInfo->info.token,
2200 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2202 OICFree(serverRequest.payload);
2203 OICFree(serverRequest.requestToken);
2206 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2207 if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2209 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
2210 sizeof(CAHeaderOption_t)*tempNum);
2213 requestResult = HandleStackRequests (&serverRequest);
2215 // Send ACK to client as precursor to slow response
2216 if (requestResult == OC_STACK_SLOW_RESOURCE)
2218 if (requestInfo->info.type == CA_MSG_CONFIRM)
2220 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2221 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2226 if (requestResult == OC_STACK_RESOURCE_ERROR
2227 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2229 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2232 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2234 if (requestResult == OC_STACK_RESOURCE_ERROR)
2236 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2238 else if (!OCResultToSuccess(requestResult))
2240 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2244 else if(!OCResultToSuccess(requestResult))
2246 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2248 CAResponseResult_t stackResponse =
2249 OCToCAStackResult(requestResult, serverRequest.method);
2251 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2252 requestInfo->info.type, requestInfo->info.numOptions,
2253 requestInfo->info.options, requestInfo->info.token,
2254 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2257 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2258 // The token is copied in there, and is thus still owned by this function.
2259 OICFree(serverRequest.payload);
2260 OICFree(serverRequest.requestToken);
2261 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2264 //This function will be called back by CA layer when a request is received
2265 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2267 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2268 OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2271 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2278 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2283 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2284 #ifdef ROUTING_GATEWAY
2285 bool needRIHandling = false;
2286 bool isEmptyMsg = false;
2288 * Routing manager is going to update either of endpoint or request or both.
2289 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2290 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2291 * destination. It can also remove "RM" coap header option before passing request / response to
2292 * RI as this option will make no sense to either RI or application.
2294 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2295 &needRIHandling, &isEmptyMsg);
2296 if(OC_STACK_OK != ret || !needRIHandling)
2298 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2305 * Put source in sender endpoint so that the next packet from application can be routed to
2306 * proper destination and remove RM header option.
2308 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2309 (uint8_t *) &(requestInfo->info.numOptions),
2310 (CAEndpoint_t *) endPoint);
2312 #ifdef ROUTING_GATEWAY
2316 * In Gateways, the MSGType in route option is used to check if the actual
2317 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2318 * EMPTY response is sent in the form of POST request which need to be changed
2319 * to a EMPTY response by RM. This translation is done in this part of the code.
2321 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2322 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2323 .info.messageId = requestInfo->info.messageId,
2324 .info.type = CA_MSG_ACKNOWLEDGE};
2325 OCHandleResponse(endPoint, &respInfo);
2331 // Normal handling of the packet
2332 OCHandleRequests(endPoint, requestInfo);
2334 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2338 //-----------------------------------------------------------------------------
2340 //-----------------------------------------------------------------------------
2342 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2345 !raInfo->username ||
2346 !raInfo->hostname ||
2347 !raInfo->xmpp_domain)
2350 return OC_STACK_INVALID_PARAM;
2352 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2353 gRASetInfo = (result == OC_STACK_OK)? true : false;
2359 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2363 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2366 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2368 OC_UNUSED(serverFlags);
2369 OC_UNUSED(clientFlags);
2371 OIC_LOG(DEBUG, TAG, "call OCInit1");
2372 return OCInit2(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS, OC_DEFAULT_ADAPTER);
2375 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2376 OCTransportAdapter transportType)
2378 if(stackState == OC_STACK_INITIALIZED)
2380 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2381 OCStop() between them are ignored.");
2385 #ifndef ROUTING_GATEWAY
2386 if (OC_GATEWAY == mode)
2388 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2389 return OC_STACK_INVALID_PARAM;
2396 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2397 return OC_STACK_ERROR;
2401 OCStackResult result = OC_STACK_ERROR;
2402 OIC_LOG(INFO, TAG, "Entering OCInit");
2405 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2406 || (mode == OC_GATEWAY)))
2408 OIC_LOG(ERROR, TAG, "Invalid mode");
2409 return OC_STACK_ERROR;
2413 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2415 caglobals.client = true;
2417 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2419 caglobals.server = true;
2422 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2423 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2425 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2427 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2428 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2430 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2433 defaultDeviceHandler = NULL;
2434 defaultDeviceHandlerCallbackParameter = NULL;
2436 result = InitializeScheduleResourceList();
2437 VERIFY_SUCCESS(result, OC_STACK_OK);
2439 result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2440 VERIFY_SUCCESS(result, OC_STACK_OK);
2442 result = CAResultToOCResult(OCSelectNetwork(transportType));
2443 VERIFY_SUCCESS(result, OC_STACK_OK);
2445 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2446 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2447 VERIFY_SUCCESS(result, OC_STACK_OK);
2449 switch (myStackMode)
2452 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2453 result = CAResultToOCResult(CAStartDiscoveryServer());
2454 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2457 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2458 result = CAResultToOCResult(CAStartListeningServer());
2459 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2461 case OC_CLIENT_SERVER:
2463 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2464 result = CAResultToOCResult(CAStartListeningServer());
2465 if(result == OC_STACK_OK)
2467 result = CAResultToOCResult(CAStartDiscoveryServer());
2471 VERIFY_SUCCESS(result, OC_STACK_OK);
2474 CARegisterKeepAliveHandler(OCHandleKeepAliveConnCB);
2477 #ifdef WITH_PRESENCE
2478 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2479 #endif // WITH_PRESENCE
2481 //Update Stack state to initialized
2482 stackState = OC_STACK_INITIALIZED;
2484 // Initialize resource
2485 if(myStackMode != OC_CLIENT)
2487 result = initResources();
2490 // Initialize the SRM Policy Engine
2491 if(result == OC_STACK_OK)
2493 result = SRMInitPolicyEngine();
2494 // TODO after BeachHead delivery: consolidate into single SRMInit()
2496 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2497 RMSetStackMode(mode);
2498 #ifdef ROUTING_GATEWAY
2499 if (OC_GATEWAY == myStackMode)
2501 result = RMInitialize();
2507 if (result == OC_STACK_OK)
2509 result = OCInitializeKeepAlive(myStackMode);
2513 InitializeObseverList();
2516 if(result != OC_STACK_OK)
2518 OIC_LOG(ERROR, TAG, "Stack initialization error");
2519 TerminateScheduleResourceList();
2520 deleteAllResources();
2522 stackState = OC_STACK_UNINITIALIZED;
2527 OCStackResult OCStop()
2529 OIC_LOG(INFO, TAG, "Entering OCStop");
2531 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2533 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2536 else if (stackState != OC_STACK_INITIALIZED)
2538 OIC_LOG(INFO, TAG, "Stack not initialized");
2539 return OC_STACK_ERROR;
2542 // unset cautil config
2543 CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2544 CAUtilSetBTConfigure(configs);
2546 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2548 CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2549 OCDefaultConnectionStateChangedHandler);
2551 #ifdef WITH_PRESENCE
2552 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2553 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2554 presenceResource.presenceTTL = 0;
2555 presenceState = OC_PRESENCE_UNINITIALIZED;
2556 #endif // WITH_PRESENCE
2558 #ifdef ROUTING_GATEWAY
2559 if (OC_GATEWAY == myStackMode)
2566 OCTerminateKeepAlive(myStackMode);
2569 TerminateScheduleResourceList();
2570 // Remove all observers
2571 TerminateObserverList();
2572 // Free memory dynamically allocated for resources
2573 deleteAllResources();
2574 // Remove all the client callbacks
2575 DeleteClientCBList();
2576 // Terminate connectivity-abstraction layer.
2579 // De-init the SRM Policy Engine
2580 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2581 SRMDeInitPolicyEngine();
2583 stackState = OC_STACK_UNINITIALIZED;
2587 OCStackResult OCStartMulticastServer()
2589 if(stackState != OC_STACK_INITIALIZED)
2591 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2592 return OC_STACK_ERROR;
2594 CAResult_t ret = CAStartListeningServer();
2595 if (CA_STATUS_OK != ret)
2597 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2598 return OC_STACK_ERROR;
2603 OCStackResult OCStopMulticastServer()
2605 CAResult_t ret = CAStopListeningServer();
2606 if (CA_STATUS_OK != ret)
2608 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2609 return OC_STACK_ERROR;
2614 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2619 return CA_MSG_CONFIRM;
2624 return CA_MSG_NONCONFIRM;
2628 OCStackResult ParseRequestUri(const char *fullUri,
2629 OCTransportAdapter adapter,
2630 OCTransportFlags flags,
2631 OCDevAddr **devAddr,
2633 char **resourceType)
2635 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2637 OCStackResult result = OC_STACK_OK;
2638 OCDevAddr *da = NULL;
2642 // provide defaults for all returned values
2649 *resourceUri = NULL;
2653 *resourceType = NULL;
2656 // delimit url prefix, if any
2657 const char *start = fullUri;
2658 char *slash2 = strstr(start, "//");
2663 char *slash = strchr(start, '/');
2666 return OC_STACK_INVALID_URI;
2669 // process url scheme
2670 size_t prefixLen = slash2 - fullUri;
2674 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2675 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2681 // TODO: this logic should come in with unit tests exercising the various strings
2682 // processs url prefix, if any
2683 size_t urlLen = slash - start;
2687 if (urlLen && devAddr)
2688 { // construct OCDevAddr
2689 if (start[0] == '[')
2691 char *close = strchr(++start, ']');
2692 if (!close || close > slash)
2694 return OC_STACK_INVALID_URI;
2697 if (close[1] == ':')
2704 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2708 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2710 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2714 char *dot = strchr(start, '.');
2715 if (dot && dot < slash)
2717 colon = strchr(start, ':');
2718 end = (colon && colon < slash) ? colon : slash;
2723 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2727 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2729 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2737 if (len >= sizeof(da->addr))
2739 return OC_STACK_INVALID_URI;
2741 // collect port, if any
2742 if (colon && colon < slash)
2744 for (colon++; colon < slash; colon++)
2747 if (c < '0' || c > '9')
2749 return OC_STACK_INVALID_URI;
2751 port = 10 * port + c - '0';
2756 if (len >= sizeof(da->addr))
2758 return OC_STACK_INVALID_URI;
2761 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2764 return OC_STACK_NO_MEMORY;
2767 // Decode address per RFC 6874.
2768 result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2769 if (result != OC_STACK_OK)
2776 da->adapter = adapter;
2778 if (!strncmp(fullUri, "coaps", 5))
2780 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2785 // process resource uri, if any
2787 { // request uri and query
2788 size_t ulen = strlen(slash); // resource uri length
2789 size_t tlen = 0; // resource type length
2792 static const char strPresence[] = "/oic/ad?rt=";
2793 static const size_t lenPresence = sizeof(strPresence) - 1;
2794 if (!strncmp(slash, strPresence, lenPresence))
2796 type = slash + lenPresence;
2797 tlen = ulen - lenPresence;
2802 *resourceUri = (char *)OICMalloc(ulen + 1);
2805 result = OC_STACK_NO_MEMORY;
2808 OICStrcpy(*resourceUri, (ulen + 1), slash);
2811 if (type && resourceType)
2813 *resourceType = (char *)OICMalloc(tlen + 1);
2816 result = OC_STACK_NO_MEMORY;
2820 OICStrcpy(*resourceType, (tlen+1), type);
2827 // free all returned values
2834 OICFree(*resourceUri);
2838 OICFree(*resourceType);
2843 #ifdef WITH_PRESENCE
2844 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2848 char uri[CA_MAX_URI_LENGTH];
2850 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2852 *requestUri = OICStrdup(uri);
2855 return OC_STACK_NO_MEMORY;
2860 #endif // WITH_PRESENCE
2863 * Discover or Perform requests on a specified resource
2865 OCStackResult OCDoResource(OCDoHandle *handle,
2867 const char *requestUri,
2868 const OCDevAddr *destination,
2870 OCConnectivityType connectivityType,
2871 OCQualityOfService qos,
2872 OCCallbackData *cbData,
2873 OCHeaderOption *options,
2876 OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
2877 connectivityType, qos, cbData, options, numOptions);
2879 // This is the owner of the payload object, so we free it
2880 OCPayloadDestroy(payload);
2885 * Discover or Perform requests on a specified resource
2887 OCStackResult OCDoRequest(OCDoHandle *handle,
2889 const char *requestUri,
2890 const OCDevAddr *destination,
2892 OCConnectivityType connectivityType,
2893 OCQualityOfService qos,
2894 OCCallbackData *cbData,
2895 OCHeaderOption *options,
2898 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2899 OIC_TRACE_BEGIN(%s:OCDoRequest, TAG);
2901 // Validate input parameters
2902 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2903 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2905 OCStackResult result = OC_STACK_ERROR;
2906 CAResult_t caResult;
2907 CAToken_t token = NULL;
2908 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2909 ClientCB *clientCB = NULL;
2910 OCDoHandle resHandle = NULL;
2911 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2912 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2914 OCTransportAdapter adapter;
2915 OCTransportFlags flags;
2916 // the request contents are put here
2917 CARequestInfo_t requestInfo = {.method = CA_GET};
2918 // requestUri will be parsed into the following three variables
2919 OCDevAddr *devAddr = NULL;
2920 char *resourceUri = NULL;
2921 char *resourceType = NULL;
2924 * Support original behavior with address on resourceUri argument.
2926 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2927 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2931 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2932 if (result != OC_STACK_OK)
2934 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2938 else if (!checkProxyUri(options, numOptions))
2940 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2947 case OC_REST_OBSERVE:
2948 case OC_REST_OBSERVE_ALL:
2949 requestInfo.method = CA_GET;
2952 requestInfo.method = CA_PUT;
2955 requestInfo.method = CA_POST;
2957 case OC_REST_DELETE:
2958 requestInfo.method = CA_DELETE;
2960 case OC_REST_DISCOVER:
2961 #ifdef WITH_PRESENCE
2962 case OC_REST_PRESENCE:
2964 if (destination || devAddr)
2966 requestInfo.isMulticast = false;
2970 tmpDevAddr.adapter = adapter;
2971 tmpDevAddr.flags = flags;
2972 destination = &tmpDevAddr;
2973 requestInfo.isMulticast = true;
2976 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
2977 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
2978 // replacing method type with GET.
2979 requestInfo.method = CA_GET;
2982 result = OC_STACK_INVALID_METHOD;
2986 if (!devAddr && !destination)
2988 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2989 result = OC_STACK_INVALID_PARAM;
2993 /* If not original behavior, use destination argument */
2994 if (destination && !devAddr)
2996 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2999 result = OC_STACK_NO_MEMORY;
3002 OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
3003 *devAddr = *destination;
3008 OIC_LOG_V(INFO_PRIVATE, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
3009 if (!requestInfo.isMulticast)
3011 OIC_LOG_V(DEBUG, TAG, "remoteAddr of devAddr : [%s]:[%d]",
3012 devAddr->addr, devAddr->port);
3016 resHandle = GenerateInvocationHandle();
3019 result = OC_STACK_NO_MEMORY;
3023 caResult = CAGenerateToken(&token, tokenLength);
3024 if (caResult != CA_STATUS_OK)
3026 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3027 result= OC_STACK_ERROR;
3031 // fill in request data
3032 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3033 requestInfo.info.token = token;
3034 requestInfo.info.tokenLength = tokenLength;
3036 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3038 result = CreateObserveHeaderOption (&(requestInfo.info.options),
3039 options, numOptions, OC_OBSERVE_REGISTER);
3040 if (result != OC_STACK_OK)
3044 requestInfo.info.numOptions = numOptions + 1;
3048 requestInfo.info.numOptions = numOptions;
3049 requestInfo.info.options =
3050 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3051 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3052 numOptions * sizeof(CAHeaderOption_t));
3055 CopyDevAddrToEndpoint(devAddr, &endpoint);
3060 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3063 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3066 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3070 requestInfo.info.payload = NULL;
3071 requestInfo.info.payloadSize = 0;
3072 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3075 // prepare for response
3076 #ifdef WITH_PRESENCE
3077 if (method == OC_REST_PRESENCE)
3079 char *presenceUri = NULL;
3080 result = OCPreparePresence(&endpoint, &presenceUri,
3081 requestInfo.isMulticast);
3082 if (OC_STACK_OK != result)
3087 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3088 // Presence notification will form a canonical uri to
3089 // look for callbacks into the application.
3092 OICFree(resourceUri);
3094 resourceUri = presenceUri;
3098 // update resourceUri onto requestInfo after check presence uri
3099 requestInfo.info.resourceUri = resourceUri;
3101 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3102 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3103 method, devAddr, resourceUri, resourceType, ttl);
3104 if (OC_STACK_OK != result)
3109 devAddr = NULL; // Client CB list entry now owns it
3110 resourceUri = NULL; // Client CB list entry now owns it
3111 resourceType = NULL; // Client CB list entry now owns it
3113 #ifdef WITH_PRESENCE
3114 if (method == OC_REST_PRESENCE)
3116 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3120 *handle = resHandle;
3128 result = OCSendRequest(&endpoint, &requestInfo);
3129 if (OC_STACK_OK != result)
3136 *handle = resHandle;
3140 if (result != OC_STACK_OK)
3142 OIC_LOG(ERROR, TAG, "OCDoResource error");
3143 FindAndDeleteClientCB(clientCB);
3144 CADestroyToken(token);
3152 OICFree(requestInfo.info.payload);
3154 OICFree(resourceUri);
3155 OICFree(resourceType);
3156 OICFree(requestInfo.info.options);
3161 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3165 * This ftn is implemented one of two ways in the case of observation:
3167 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3168 * Remove the callback associated on client side.
3169 * When the next notification comes in from server,
3170 * reply with RESET message to server.
3171 * Keep in mind that the server will react to RESET only
3172 * if the last notification was sent as CON
3174 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3175 * and it is associated with an observe request
3176 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3177 * Send CON Observe request to server with
3178 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3179 * Remove the callback associated on client side.
3181 OCStackResult ret = OC_STACK_OK;
3182 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3183 CARequestInfo_t requestInfo = {.method = CA_GET};
3187 return OC_STACK_INVALID_PARAM;
3190 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3193 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3194 return OC_STACK_ERROR;
3197 switch (clientCB->method)
3199 case OC_REST_OBSERVE:
3200 case OC_REST_OBSERVE_ALL:
3202 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3204 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3206 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
3208 FindAndDeleteClientCB(clientCB);
3212 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3214 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3215 requestInfo.info.token = clientCB->token;
3216 requestInfo.info.tokenLength = clientCB->tokenLength;
3218 if (CreateObserveHeaderOption (&(requestInfo.info.options),
3219 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3221 return OC_STACK_ERROR;
3223 requestInfo.info.numOptions = numOptions + 1;
3224 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3227 ret = OCSendRequest(&endpoint, &requestInfo);
3229 if (requestInfo.info.options)
3231 OICFree (requestInfo.info.options);
3233 if (requestInfo.info.resourceUri)
3235 OICFree (requestInfo.info.resourceUri);
3240 case OC_REST_DISCOVER:
3241 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3242 clientCB->requestUri);
3243 FindAndDeleteClientCB(clientCB);
3246 #ifdef WITH_PRESENCE
3247 case OC_REST_PRESENCE:
3248 FindAndDeleteClientCB(clientCB);
3254 case OC_REST_DELETE:
3255 OIC_LOG_V(INFO, TAG, "Cancelling request callback for resource %s",
3256 clientCB->requestUri);
3257 FindAndDeleteClientCB(clientCB);
3261 ret = OC_STACK_INVALID_METHOD;
3269 * @brief Register Persistent storage callback.
3270 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3272 * OC_STACK_OK - No errors; Success
3273 * OC_STACK_INVALID_PARAM - Invalid parameter
3275 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3277 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3278 if(!persistentStorageHandler)
3280 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3281 return OC_STACK_INVALID_PARAM;
3285 if( !persistentStorageHandler->open ||
3286 !persistentStorageHandler->close ||
3287 !persistentStorageHandler->read ||
3288 !persistentStorageHandler->unlink ||
3289 !persistentStorageHandler->write)
3291 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3292 return OC_STACK_INVALID_PARAM;
3295 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3298 #ifdef WITH_PRESENCE
3300 OCStackResult OCProcessPresence()
3302 OCStackResult result = OC_STACK_OK;
3304 // the following line floods the log with messages that are irrelevant
3305 // to most purposes. Uncomment as needed.
3306 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3307 ClientCB* cbNode = NULL;
3308 OCClientResponse clientResponse;
3309 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3311 LL_FOREACH(cbList, cbNode)
3313 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3318 uint32_t now = GetTicks(0);
3319 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3320 cbNode->presence->TTLlevel);
3321 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3323 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3328 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3330 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3331 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3333 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3335 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3337 clientResponse.sequenceNumber = 0;
3338 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3339 clientResponse.devAddr = *cbNode->devAddr;
3340 FixUpClientResponse(&clientResponse);
3341 clientResponse.payload = NULL;
3343 // Increment the TTLLevel (going to a next state), so we don't keep
3344 // sending presence notification to client.
3345 cbNode->presence->TTLlevel++;
3346 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3347 cbNode->presence->TTLlevel);
3349 OIC_LOG(INFO, TAG, "Before calling into application address space for presence timeout");
3350 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3351 OIC_LOG(INFO, TAG, "After calling into application address space for presence timeout");
3353 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3355 FindAndDeleteClientCB(cbNode);
3359 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3364 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3365 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3366 CARequestInfo_t requestInfo = {.method = CA_GET};
3368 OIC_LOG(DEBUG, TAG, "time to test server presence");
3370 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3372 requestData.type = CA_MSG_NONCONFIRM;
3373 requestData.token = cbNode->token;
3374 requestData.tokenLength = cbNode->tokenLength;
3375 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3376 requestInfo.method = CA_GET;
3377 requestInfo.info = requestData;
3379 result = OCSendRequest(&endpoint, &requestInfo);
3380 if (OC_STACK_OK != result)
3385 cbNode->presence->TTLlevel++;
3386 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3389 if (result != OC_STACK_OK)
3391 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3396 #endif // WITH_PRESENCE
3398 OCStackResult OCProcess()
3400 if (stackState == OC_STACK_UNINITIALIZED)
3402 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3403 return OC_STACK_ERROR;
3405 #ifdef WITH_PRESENCE
3406 OCProcessPresence();
3408 CAHandleRequestResponse();
3410 #ifdef ROUTING_GATEWAY
3415 OCProcessKeepAlive();
3420 #ifdef WITH_PRESENCE
3421 OCStackResult OCStartPresence(const uint32_t ttl)
3423 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3424 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3425 OCChangeResourceProperty(
3426 &(((OCResource *)presenceResource.handle)->resourceProperties),
3429 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3431 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3432 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3436 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3437 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3441 presenceResource.presenceTTL = ttl;
3444 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3447 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3449 presenceState = OC_PRESENCE_INITIALIZED;
3451 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3453 CAToken_t caToken = NULL;
3454 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3455 if (caResult != CA_STATUS_OK)
3457 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3458 CADestroyToken(caToken);
3459 return OC_STACK_ERROR;
3462 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3463 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3464 CADestroyToken(caToken);
3467 // Each time OCStartPresence is called
3468 // a different random 32-bit integer number is used
3469 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3471 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3472 OC_PRESENCE_TRIGGER_CREATE);
3475 OCStackResult OCStopPresence()
3477 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3478 OCStackResult result = OC_STACK_ERROR;
3480 if(presenceResource.handle)
3482 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3484 // make resource inactive
3485 result = OCChangeResourceProperty(
3486 &(((OCResource *) presenceResource.handle)->resourceProperties),
3490 if(result != OC_STACK_OK)
3493 "Changing the presence resource properties to ACTIVE not successful");
3497 return SendStopNotification();
3501 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3502 void* callbackParameter)
3504 defaultDeviceHandler = entityHandler;
3505 defaultDeviceHandlerCallbackParameter = callbackParameter;
3510 OCStackResult OCCreateResource(OCResourceHandle *handle,
3511 const char *resourceTypeName,
3512 const char *resourceInterfaceName,
3513 const char *uri, OCEntityHandler entityHandler,
3514 void* callbackParam,
3515 uint8_t resourceProperties)
3518 OCResource *pointer = NULL;
3519 OCStackResult result = OC_STACK_ERROR;
3521 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3523 if(myStackMode == OC_CLIENT)
3525 return OC_STACK_INVALID_PARAM;
3527 // Validate parameters
3528 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3530 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3531 return OC_STACK_INVALID_URI;
3533 // Is it presented during resource discovery?
3534 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3536 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3537 return OC_STACK_INVALID_PARAM;
3540 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3542 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3546 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3548 // Make sure resourceProperties bitmask has allowed properties specified
3549 if (resourceProperties
3550 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3551 OC_EXPLICIT_DISCOVERABLE
3560 OIC_LOG(ERROR, TAG, "Invalid property");
3561 return OC_STACK_INVALID_PARAM;
3564 // If the headResource is NULL, then no resources have been created...
3565 pointer = headResource;
3568 // At least one resources is in the resource list, so we need to search for
3569 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3572 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3574 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3575 return OC_STACK_INVALID_PARAM;
3577 pointer = pointer->next;
3580 // Create the pointer and insert it into the resource list
3581 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3584 result = OC_STACK_NO_MEMORY;
3587 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3589 insertResource(pointer);
3592 pointer->uri = OICStrdup(uri);
3595 result = OC_STACK_NO_MEMORY;
3599 // Set properties. Set OC_ACTIVE
3600 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3603 // Add the resourcetype to the resource
3604 result = BindResourceTypeToResource(pointer, resourceTypeName);
3605 if (result != OC_STACK_OK)
3607 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3611 // Add the resourceinterface to the resource
3612 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3613 if (result != OC_STACK_OK)
3615 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3619 // If an entity handler has been passed, attach it to the newly created
3620 // resource. Otherwise, set the default entity handler.
3623 pointer->entityHandler = entityHandler;
3624 pointer->entityHandlerCallbackParam = callbackParam;
3628 pointer->entityHandler = defaultResourceEHandler;
3629 pointer->entityHandlerCallbackParam = NULL;
3632 // Initialize a pointer indicating child resources in case of collection
3633 pointer->rsrcChildResourcesHead = NULL;
3636 result = OC_STACK_OK;
3638 #ifdef WITH_PRESENCE
3639 if (presenceResource.handle)
3641 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3642 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3646 if (result != OC_STACK_OK)
3648 // Deep delete of resource and other dynamic elements that it contains
3649 deleteResource(pointer);
3654 OCStackResult OCBindResource(
3655 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3657 OCResource *resource = NULL;
3658 OCChildResource *tempChildResource = NULL;
3659 OCChildResource *newChildResource = NULL;
3661 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3663 // Validate parameters
3664 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3665 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3666 // Container cannot contain itself
3667 if (collectionHandle == resourceHandle)
3669 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3670 return OC_STACK_INVALID_PARAM;
3673 // Use the handle to find the resource in the resource linked list
3674 resource = findResource((OCResource *) collectionHandle);
3677 OIC_LOG(ERROR, TAG, "Collection handle not found");
3678 return OC_STACK_INVALID_PARAM;
3681 // Look for an open slot to add add the child resource.
3682 // If found, add it and return success
3684 tempChildResource = resource->rsrcChildResourcesHead;
3686 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3688 // TODO: what if one of child resource was deregistered without unbinding?
3689 tempChildResource = tempChildResource->next;
3692 // Do memory allocation for child resource
3693 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3694 if(!newChildResource)
3696 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3697 return OC_STACK_ERROR;
3700 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3701 newChildResource->next = NULL;
3703 if(!resource->rsrcChildResourcesHead)
3705 resource->rsrcChildResourcesHead = newChildResource;
3708 tempChildResource->next = newChildResource;
3711 OIC_LOG(INFO, TAG, "resource bound");
3713 #ifdef WITH_PRESENCE
3714 if (presenceResource.handle)
3716 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3717 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3718 OC_PRESENCE_TRIGGER_CHANGE);
3725 OCStackResult OCUnBindResource(
3726 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3728 OCResource *resource = NULL;
3729 OCChildResource *tempChildResource = NULL;
3730 OCChildResource *tempLastChildResource = NULL;
3732 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3734 // Validate parameters
3735 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3736 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3737 // Container cannot contain itself
3738 if (collectionHandle == resourceHandle)
3740 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3741 return OC_STACK_INVALID_PARAM;
3744 // Use the handle to find the resource in the resource linked list
3745 resource = findResource((OCResource *) collectionHandle);
3748 OIC_LOG(ERROR, TAG, "Collection handle not found");
3749 return OC_STACK_INVALID_PARAM;
3752 // Look for an open slot to add add the child resource.
3753 // If found, add it and return success
3754 if(!resource->rsrcChildResourcesHead)
3756 OIC_LOG(INFO, TAG, "resource not found in collection");
3758 // Unable to add resourceHandle, so return error
3759 return OC_STACK_ERROR;
3763 tempChildResource = resource->rsrcChildResourcesHead;
3765 while (tempChildResource)
3767 if(tempChildResource->rsrcResource == resourceHandle)
3769 // if resource going to be unbinded is the head one.
3770 if( tempChildResource == resource->rsrcChildResourcesHead )
3772 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3773 OICFree(resource->rsrcChildResourcesHead);
3774 resource->rsrcChildResourcesHead = temp;
3779 OCChildResource *temp = tempChildResource->next;
3780 OICFree(tempChildResource);
3781 if (tempLastChildResource)
3783 tempLastChildResource->next = temp;
3788 OIC_LOG(INFO, TAG, "resource unbound");
3790 // Send notification when resource is unbounded successfully.
3791 #ifdef WITH_PRESENCE
3792 if (presenceResource.handle)
3794 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3795 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3796 OC_PRESENCE_TRIGGER_CHANGE);
3799 tempChildResource = NULL;
3800 tempLastChildResource = NULL;
3806 tempLastChildResource = tempChildResource;
3807 tempChildResource = tempChildResource->next;
3810 OIC_LOG(INFO, TAG, "resource not found in collection");
3812 tempChildResource = NULL;
3813 tempLastChildResource = NULL;
3815 // Unable to add resourceHandle, so return error
3816 return OC_STACK_ERROR;
3819 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3821 if (!resourceItemName)
3825 // Per RFC 6690 only registered values must follow the first rule below.
3826 // At this point in time the only values registered begin with "core", and
3827 // all other values are specified as opaque strings where multiple values
3828 // are separated by a space.
3829 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3831 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3833 if (resourceItemName[index] != '.'
3834 && resourceItemName[index] != '-'
3835 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3836 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3844 for (size_t index = 0; resourceItemName[index]; ++index)
3846 if (resourceItemName[index] == ' '
3847 || resourceItemName[index] == '\t'
3848 || resourceItemName[index] == '\r'
3849 || resourceItemName[index] == '\n')
3859 OCStackResult BindResourceTypeToResource(OCResource* resource,
3860 const char *resourceTypeName)
3862 OCResourceType *pointer = NULL;
3864 OCStackResult result = OC_STACK_ERROR;
3866 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3868 if (!ValidateResourceTypeInterface(resourceTypeName))
3870 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3871 return OC_STACK_INVALID_PARAM;
3874 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3877 result = OC_STACK_NO_MEMORY;
3881 str = OICStrdup(resourceTypeName);
3884 result = OC_STACK_NO_MEMORY;
3887 pointer->resourcetypename = str;
3888 pointer->next = NULL;
3890 insertResourceType(resource, pointer);
3891 result = OC_STACK_OK;
3894 if (result != OC_STACK_OK)
3903 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3904 const char *resourceInterfaceName)
3906 OCResourceInterface *pointer = NULL;
3908 OCStackResult result = OC_STACK_ERROR;
3910 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3912 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3914 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3915 return OC_STACK_INVALID_PARAM;
3918 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3920 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3923 result = OC_STACK_NO_MEMORY;
3927 str = OICStrdup(resourceInterfaceName);
3930 result = OC_STACK_NO_MEMORY;
3933 pointer->name = str;
3935 // Bind the resourceinterface to the resource
3936 insertResourceInterface(resource, pointer);
3938 result = OC_STACK_OK;
3941 if (result != OC_STACK_OK)
3950 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3951 const char *resourceTypeName)
3954 OCStackResult result = OC_STACK_ERROR;
3955 OCResource *resource = NULL;
3957 resource = findResource((OCResource *) handle);
3960 OIC_LOG(ERROR, TAG, "Resource not found");
3961 return OC_STACK_ERROR;
3964 result = BindResourceTypeToResource(resource, resourceTypeName);
3966 #ifdef WITH_PRESENCE
3967 if(presenceResource.handle)
3969 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3970 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3977 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3978 const char *resourceInterfaceName)
3981 OCStackResult result = OC_STACK_ERROR;
3982 OCResource *resource = NULL;
3984 resource = findResource((OCResource *) handle);
3987 OIC_LOG(ERROR, TAG, "Resource not found");
3988 return OC_STACK_ERROR;
3991 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3993 #ifdef WITH_PRESENCE
3994 if (presenceResource.handle)
3996 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3997 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4004 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
4006 OCResource *pointer = headResource;
4008 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
4012 *numResources = *numResources + 1;
4013 pointer = pointer->next;
4018 OCResourceHandle OCGetResourceHandle(uint8_t index)
4020 OCResource *pointer = headResource;
4022 for( uint8_t i = 0; i < index && pointer; ++i)
4024 pointer = pointer->next;
4026 return (OCResourceHandle) pointer;
4029 OCStackResult OCDeleteResource(OCResourceHandle handle)
4033 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4034 return OC_STACK_INVALID_PARAM;
4037 OCResource *resource = findResource((OCResource *) handle);
4038 if (resource == NULL)
4040 OIC_LOG(ERROR, TAG, "Resource not found");
4041 return OC_STACK_NO_RESOURCE;
4044 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4046 OIC_LOG(ERROR, TAG, "Error deleting resource");
4047 return OC_STACK_ERROR;
4053 const char *OCGetResourceUri(OCResourceHandle handle)
4055 OCResource *resource = NULL;
4057 resource = findResource((OCResource *) handle);
4060 return resource->uri;
4062 return (const char *) NULL;
4065 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4067 OCResource *resource = NULL;
4069 resource = findResource((OCResource *) handle);
4072 return resource->resourceProperties;
4074 return (OCResourceProperty)-1;
4077 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4078 uint8_t *numResourceTypes)
4080 OCResource *resource = NULL;
4081 OCResourceType *pointer = NULL;
4083 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4084 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4086 *numResourceTypes = 0;
4088 resource = findResource((OCResource *) handle);
4091 pointer = resource->rsrcType;
4094 *numResourceTypes = *numResourceTypes + 1;
4095 pointer = pointer->next;
4101 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4103 OCResourceType *resourceType = NULL;
4105 resourceType = findResourceTypeAtIndex(handle, index);
4108 return resourceType->resourcetypename;
4110 return (const char *) NULL;
4113 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4114 uint8_t *numResourceInterfaces)
4116 OCResourceInterface *pointer = NULL;
4117 OCResource *resource = NULL;
4119 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4120 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4122 *numResourceInterfaces = 0;
4123 resource = findResource((OCResource *) handle);
4126 pointer = resource->rsrcInterface;
4129 *numResourceInterfaces = *numResourceInterfaces + 1;
4130 pointer = pointer->next;
4136 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4138 OCResourceInterface *resourceInterface = NULL;
4140 resourceInterface = findResourceInterfaceAtIndex(handle, index);
4141 if (resourceInterface)
4143 return resourceInterface->name;
4145 return (const char *) NULL;
4148 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4151 OCResource *resource = NULL;
4152 OCChildResource *tempChildResource = NULL;
4155 resource = findResource((OCResource *) collectionHandle);
4161 tempChildResource = resource->rsrcChildResourcesHead;
4163 while(tempChildResource)
4167 return tempChildResource->rsrcResource;
4170 tempChildResource = tempChildResource->next;
4173 // In this case, the number of resource handles in the collection exceeds the index
4174 tempChildResource = NULL;
4178 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4179 OCEntityHandler entityHandler,
4180 void* callbackParam)
4182 OCResource *resource = NULL;
4184 // Validate parameters
4185 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4187 // Use the handle to find the resource in the resource linked list
4188 resource = findResource((OCResource *)handle);
4191 OIC_LOG(ERROR, TAG, "Resource not found");
4192 return OC_STACK_ERROR;
4196 resource->entityHandler = entityHandler;
4197 resource->entityHandlerCallbackParam = callbackParam;
4199 #ifdef WITH_PRESENCE
4200 if (presenceResource.handle)
4202 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4203 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4210 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4212 OCResource *resource = NULL;
4214 resource = findResource((OCResource *)handle);
4217 OIC_LOG(ERROR, TAG, "Resource not found");
4222 return resource->entityHandler;
4225 void incrementSequenceNumber(OCResource * resPtr)
4227 // Increment the sequence number
4228 resPtr->sequenceNum += 1;
4229 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4231 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4236 #ifdef WITH_PRESENCE
4237 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4238 OCPresenceTrigger trigger)
4240 OIC_LOG(INFO, TAG, "SendPresenceNotification");
4241 OCResource *resPtr = NULL;
4242 OCStackResult result = OC_STACK_ERROR;
4243 OCMethod method = OC_REST_PRESENCE;
4244 uint32_t maxAge = 0;
4245 resPtr = findResource((OCResource *) presenceResource.handle);
4248 return OC_STACK_NO_RESOURCE;
4251 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4253 maxAge = presenceResource.presenceTTL;
4255 result = SendAllObserverNotification(method, resPtr, maxAge,
4256 trigger, resourceType, OC_LOW_QOS);
4262 OCStackResult SendStopNotification()
4264 OIC_LOG(INFO, TAG, "SendStopNotification");
4265 OCResource *resPtr = NULL;
4266 OCStackResult result = OC_STACK_ERROR;
4267 OCMethod method = OC_REST_PRESENCE;
4268 resPtr = findResource((OCResource *) presenceResource.handle);
4271 return OC_STACK_NO_RESOURCE;
4274 // maxAge is 0. ResourceType is NULL.
4275 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4281 #endif // WITH_PRESENCE
4282 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4284 OCResource *resPtr = NULL;
4285 OCStackResult result = OC_STACK_ERROR;
4286 OCMethod method = OC_REST_NOMETHOD;
4287 uint32_t maxAge = 0;
4289 OIC_LOG(INFO, TAG, "Notifying all observers");
4290 #ifdef WITH_PRESENCE
4291 if(handle == presenceResource.handle)
4295 #endif // WITH_PRESENCE
4296 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4298 // Verify that the resource exists
4299 resPtr = findResource ((OCResource *) handle);
4302 return OC_STACK_NO_RESOURCE;
4306 //only increment in the case of regular observing (not presence)
4307 incrementSequenceNumber(resPtr);
4308 method = OC_REST_OBSERVE;
4309 maxAge = MAX_OBSERVE_AGE;
4310 #ifdef WITH_PRESENCE
4311 result = SendAllObserverNotification (method, resPtr, maxAge,
4312 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4314 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4321 OCNotifyListOfObservers (OCResourceHandle handle,
4322 OCObservationId *obsIdList,
4323 uint8_t numberOfIds,
4324 const OCRepPayload *payload,
4325 OCQualityOfService qos)
4327 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4329 OCResource *resPtr = NULL;
4330 //TODO: we should allow the server to define this
4331 uint32_t maxAge = MAX_OBSERVE_AGE;
4333 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4334 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4335 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4337 resPtr = findResource ((OCResource *) handle);
4338 if (NULL == resPtr || myStackMode == OC_CLIENT)
4340 return OC_STACK_NO_RESOURCE;
4344 incrementSequenceNumber(resPtr);
4346 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4347 payload, maxAge, qos));
4350 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4352 OIC_TRACE_BEGIN(%s:OCDoResponse, TAG);
4353 OCStackResult result = OC_STACK_ERROR;
4354 OCServerRequest *serverRequest = NULL;
4356 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4358 // Validate input parameters
4359 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4360 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4363 // Get pointer to request info
4364 serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
4367 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4368 result = serverRequest->ehResponseHandler(ehResponse);
4375 //#ifdef DIRECT_PAIRING
4376 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4378 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4379 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4381 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4385 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4388 const OCDPDev_t* OCGetDirectPairedDevices()
4390 return (const OCDPDev_t*)DPGetPairedDevices();
4393 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4394 OCDirectPairingCB resultCallback)
4396 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4397 if(NULL == peer || NULL == pinNumber)
4399 OIC_LOG(ERROR, TAG, "Invalid parameters");
4400 return OC_STACK_INVALID_PARAM;
4402 if (NULL == resultCallback)
4404 OIC_LOG(ERROR, TAG, "Invalid callback");
4405 return OC_STACK_INVALID_CALLBACK;
4408 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4409 pinNumber, (OCDirectPairingResultCB)resultCallback);
4411 //#endif // DIRECT_PAIRING
4413 //-----------------------------------------------------------------------------
4414 // Private internal function definitions
4415 //-----------------------------------------------------------------------------
4416 static OCDoHandle GenerateInvocationHandle()
4418 OCDoHandle handle = NULL;
4419 // Generate token here, it will be deleted when the transaction is deleted
4420 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4423 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4429 #ifdef WITH_PRESENCE
4430 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4431 OCResourceProperty resourceProperties, uint8_t enable)
4435 return OC_STACK_INVALID_PARAM;
4437 if (resourceProperties
4438 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4440 OIC_LOG(ERROR, TAG, "Invalid property");
4441 return OC_STACK_INVALID_PARAM;
4445 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4449 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4455 OCStackResult initResources()
4457 OCStackResult result = OC_STACK_OK;
4459 headResource = NULL;
4460 tailResource = NULL;
4461 // Init Virtual Resources
4462 #ifdef WITH_PRESENCE
4463 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4465 result = OCCreateResource(&presenceResource.handle,
4466 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4468 OC_RSRVD_PRESENCE_URI,
4472 //make resource inactive
4473 result = OCChangeResourceProperty(
4474 &(((OCResource *) presenceResource.handle)->resourceProperties),
4477 #ifndef WITH_ARDUINO
4478 if (result == OC_STACK_OK)
4480 result = SRMInitSecureResources();
4484 if(result == OC_STACK_OK)
4486 CreateResetProfile();
4487 result = OCCreateResource(&deviceResource,
4488 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4489 OC_RSRVD_INTERFACE_DEFAULT,
4490 OC_RSRVD_DEVICE_URI,
4494 if(result == OC_STACK_OK)
4496 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4497 OC_RSRVD_INTERFACE_READ);
4501 if(result == OC_STACK_OK)
4503 result = OCCreateResource(&platformResource,
4504 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4505 OC_RSRVD_INTERFACE_DEFAULT,
4506 OC_RSRVD_PLATFORM_URI,
4510 if(result == OC_STACK_OK)
4512 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4513 OC_RSRVD_INTERFACE_READ);
4520 void insertResource(OCResource *resource)
4524 headResource = resource;
4525 tailResource = resource;
4529 tailResource->next = resource;
4530 tailResource = resource;
4532 resource->next = NULL;
4535 OCResource *findResource(OCResource *resource)
4537 OCResource *pointer = headResource;
4541 if (pointer == resource)
4545 pointer = pointer->next;
4550 void deleteAllResources()
4552 OCResource *pointer = headResource;
4553 OCResource *temp = NULL;
4557 temp = pointer->next;
4558 #ifdef WITH_PRESENCE
4559 if (pointer != (OCResource *) presenceResource.handle)
4561 #endif // WITH_PRESENCE
4562 deleteResource(pointer);
4563 #ifdef WITH_PRESENCE
4565 #endif // WITH_PRESENCE
4568 memset(&platformResource, 0, sizeof(platformResource));
4569 memset(&deviceResource, 0, sizeof(deviceResource));
4571 memset(&brokerResource, 0, sizeof(brokerResource));
4574 SRMDeInitSecureResources();
4576 #ifdef WITH_PRESENCE
4577 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4578 // presence notification attributed to their deletion to be processed.
4579 deleteResource((OCResource *) presenceResource.handle);
4580 memset(&presenceResource, 0, sizeof(presenceResource));
4581 #endif // WITH_PRESENCE
4584 OCStackResult deleteResource(OCResource *resource)
4586 OCResource *prev = NULL;
4587 OCResource *temp = NULL;
4590 OIC_LOG(DEBUG,TAG,"resource is NULL");
4591 return OC_STACK_INVALID_PARAM;
4594 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4596 temp = headResource;
4599 if (temp == resource)
4601 // Invalidate all Resource Properties.
4602 resource->resourceProperties = (OCResourceProperty) 0;
4603 #ifdef WITH_PRESENCE
4604 if(resource != (OCResource *) presenceResource.handle)
4606 #endif // WITH_PRESENCE
4607 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4608 #ifdef WITH_PRESENCE
4611 if(presenceResource.handle)
4613 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4614 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4617 // Only resource in list.
4618 if (temp == headResource && temp == tailResource)
4620 headResource = NULL;
4621 tailResource = NULL;
4624 else if (temp == headResource)
4626 headResource = temp->next;
4629 else if (temp == tailResource && prev)
4631 tailResource = prev;
4632 tailResource->next = NULL;
4636 prev->next = temp->next;
4639 deleteResourceElements(temp);
4650 return OC_STACK_ERROR;
4653 void deleteResourceElements(OCResource *resource)
4662 OICFree(resource->uri);
4663 resource->uri = NULL;
4665 if (resource->rsrcType)
4667 deleteResourceType(resource->rsrcType);
4668 resource->rsrcType = NULL;
4670 if (resource->rsrcInterface)
4672 deleteResourceInterface(resource->rsrcInterface);
4673 resource->rsrcInterface = NULL;
4675 if (resource->rsrcChildResourcesHead)
4677 deleteResourceChild(resource->rsrcChildResourcesHead);
4678 resource->rsrcChildResourcesHead = NULL;
4680 if (resource->rsrcAttributes)
4682 OCDeleteResourceAttributes(resource->rsrcAttributes);
4683 resource->rsrcAttributes = NULL;
4688 void deleteResourceType(OCResourceType *resourceType)
4690 OCResourceType *next = NULL;
4692 for (OCResourceType *pointer = resourceType; pointer; pointer = next)
4694 next = pointer->next ? pointer->next : NULL;
4695 if (pointer->resourcetypename)
4697 OICFree(pointer->resourcetypename);
4698 pointer->resourcetypename = NULL;
4704 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4706 OCResourceInterface *next = NULL;
4707 for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
4709 next = pointer->next ? pointer->next : NULL;
4712 OICFree(pointer->name);
4713 pointer->name = NULL;
4719 void deleteResourceChild(OCChildResource *resourceChild)
4721 OCChildResource *next = NULL;
4722 for (OCChildResource *pointer = resourceChild; pointer; pointer = next)
4724 next = pointer->next ? pointer->next : NULL;
4725 if (pointer->rsrcResource)
4727 deleteResourceElements(pointer->rsrcResource);
4728 pointer->rsrcResource = NULL;
4734 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
4736 OCAttribute *next = NULL;
4737 for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
4739 next = pointer->next ? pointer->next : NULL;
4740 if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
4742 OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
4743 pointer->attrValue = NULL;
4745 else if (pointer->attrValue)
4747 OICFree(pointer->attrValue);
4748 pointer->attrValue = NULL;
4750 if (pointer->attrName)
4752 OICFree(pointer->attrName);
4753 pointer->attrName = NULL;
4759 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4761 OCResourceType *pointer = NULL;
4762 OCResourceType *previous = NULL;
4763 if (!resource || !resourceType)
4767 // resource type list is empty.
4768 else if (!resource->rsrcType)
4770 resource->rsrcType = resourceType;
4774 pointer = resource->rsrcType;
4778 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4780 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4781 OICFree(resourceType->resourcetypename);
4782 OICFree(resourceType);
4786 pointer = pointer->next;
4791 previous->next = resourceType;
4794 resourceType->next = NULL;
4796 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4799 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4801 OCResource *resource = NULL;
4802 OCResourceType *pointer = NULL;
4804 // Find the specified resource
4805 resource = findResource((OCResource *) handle);
4811 // Make sure a resource has a resourcetype
4812 if (!resource->rsrcType)
4817 // Iterate through the list
4818 pointer = resource->rsrcType;
4819 for(uint8_t i = 0; i< index && pointer; ++i)
4821 pointer = pointer->next;
4826 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4828 if(resourceTypeList && resourceTypeName)
4830 OCResourceType * rtPointer = resourceTypeList;
4831 while(resourceTypeName && rtPointer)
4833 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4834 if(rtPointer->resourcetypename &&
4835 strcmp(resourceTypeName, (const char *)
4836 (rtPointer->resourcetypename)) == 0)
4840 rtPointer = rtPointer->next;
4848 * Insert a new interface into interface linked list only if not already present.
4849 * If alredy present, 2nd arg is free'd.
4850 * Default interface will always be first if present.
4852 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4854 OCResourceInterface *pointer = NULL;
4855 OCResourceInterface *previous = NULL;
4857 newInterface->next = NULL;
4859 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4861 if (!*firstInterface)
4863 // If first interface is not oic.if.baseline, by default add it as first interface type.
4864 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4866 *firstInterface = newInterface;
4870 OCStackResult result = BindResourceInterfaceToResource(resource,
4871 OC_RSRVD_INTERFACE_DEFAULT);
4872 if (result != OC_STACK_OK)
4874 OICFree(newInterface->name);
4875 OICFree(newInterface);
4878 if (*firstInterface)
4880 (*firstInterface)->next = newInterface;
4884 // If once add oic.if.baseline, later too below code take care of freeing memory.
4885 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4887 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4889 OICFree(newInterface->name);
4890 OICFree(newInterface);
4893 // This code will not hit anymore, keeping
4896 newInterface->next = *firstInterface;
4897 *firstInterface = newInterface;
4902 pointer = *firstInterface;
4905 if (strcmp(newInterface->name, pointer->name) == 0)
4907 OICFree(newInterface->name);
4908 OICFree(newInterface);
4912 pointer = pointer->next;
4917 previous->next = newInterface;
4922 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4925 OCResource *resource = NULL;
4926 OCResourceInterface *pointer = NULL;
4928 // Find the specified resource
4929 resource = findResource((OCResource *) handle);
4935 // Make sure a resource has a resourceinterface
4936 if (!resource->rsrcInterface)
4941 // Iterate through the list
4942 pointer = resource->rsrcInterface;
4944 for (uint8_t i = 0; i < index && pointer; ++i)
4946 pointer = pointer->next;
4952 * This function splits the uri using the '?' delimiter.
4953 * "uriWithoutQuery" is the block of characters between the beginning
4954 * till the delimiter or '\0' which ever comes first.
4955 * "query" is whatever is to the right of the delimiter if present.
4956 * No delimiter sets the query to NULL.
4957 * If either are present, they will be malloc'ed into the params 2, 3.
4958 * The first param, *uri is left untouched.
4960 * NOTE: This function does not account for whitespace at the end of the uri NOR
4961 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4962 * part of the query.
4964 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4968 return OC_STACK_INVALID_URI;
4970 if(!query || !uriWithoutQuery)
4972 return OC_STACK_INVALID_PARAM;
4976 *uriWithoutQuery = NULL;
4978 size_t uriWithoutQueryLen = 0;
4979 size_t queryLen = 0;
4980 size_t uriLen = strlen(uri);
4982 char *pointerToDelimiter = strstr(uri, "?");
4984 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4985 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4987 if (uriWithoutQueryLen)
4989 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4990 if (!*uriWithoutQuery)
4994 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4998 *query = (char *) OICCalloc(queryLen + 1, 1);
5001 OICFree(*uriWithoutQuery);
5002 *uriWithoutQuery = NULL;
5005 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5011 return OC_STACK_NO_MEMORY;
5014 const char* OCGetServerInstanceIDString(void)
5016 static char sidStr[UUID_STRING_SIZE];
5018 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5020 OIC_LOG(FATAL, TAG, "GetDoxmDeviceID failed!");
5024 if (OCConvertUuidToString(sid.id, sidStr) != RAND_UUID_OK)
5026 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5033 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5035 OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5036 CAResult_t retResult = CA_STATUS_FAILED;
5037 CAResult_t caResult = CA_STATUS_OK;
5039 CATransportAdapter_t connTypes[] = {
5041 CA_ADAPTER_RFCOMM_BTEDR,
5042 CA_ADAPTER_GATT_BTLE,
5045 ,CA_ADAPTER_REMOTE_ACCESS
5052 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5054 for(int i = 0; i < numConnTypes; i++)
5056 // If CA status is not initialized, CASelectNetwork() will not be called.
5057 if (caResult != CA_STATUS_NOT_INITIALIZED)
5059 if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5061 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5062 caResult = CASelectNetwork(connTypes[i]);
5063 if (caResult == CA_STATUS_OK)
5065 retResult = CA_STATUS_OK;
5070 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5075 if (retResult != CA_STATUS_OK)
5077 return caResult; // Returns error of appropriate transport that failed fatally.
5083 OCStackResult CAResultToOCResult(CAResult_t caResult)
5089 case CA_STATUS_INVALID_PARAM:
5090 return OC_STACK_INVALID_PARAM;
5091 case CA_ADAPTER_NOT_ENABLED:
5092 return OC_STACK_ADAPTER_NOT_ENABLED;
5093 case CA_SERVER_STARTED_ALREADY:
5095 case CA_SERVER_NOT_STARTED:
5096 return OC_STACK_ERROR;
5097 case CA_DESTINATION_NOT_REACHABLE:
5098 return OC_STACK_COMM_ERROR;
5099 case CA_SOCKET_OPERATION_FAILED:
5100 return OC_STACK_COMM_ERROR;
5101 case CA_SEND_FAILED:
5102 return OC_STACK_COMM_ERROR;
5103 case CA_RECEIVE_FAILED:
5104 return OC_STACK_COMM_ERROR;
5105 case CA_MEMORY_ALLOC_FAILED:
5106 return OC_STACK_NO_MEMORY;
5107 case CA_REQUEST_TIMEOUT:
5108 return OC_STACK_TIMEOUT;
5109 case CA_DESTINATION_DISCONNECTED:
5110 return OC_STACK_COMM_ERROR;
5111 case CA_STATUS_FAILED:
5112 return OC_STACK_ERROR;
5113 case CA_NOT_SUPPORTED:
5114 return OC_STACK_NOTIMPL;
5116 return OC_STACK_ERROR;
5120 bool OCResultToSuccess(OCStackResult ocResult)
5125 case OC_STACK_RESOURCE_CREATED:
5126 case OC_STACK_RESOURCE_DELETED:
5127 case OC_STACK_CONTINUE:
5128 case OC_STACK_RESOURCE_CHANGED:
5129 case OC_STACK_SLOW_RESOURCE:
5137 OCStackResult OCSetProxyURI(const char *uri)
5139 return CAResultToOCResult(CASetProxyUri(uri));
5143 #if defined(RD_CLIENT) || defined(RD_SERVER)
5144 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5146 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5148 OCResource *resource = NULL;
5150 resource = findResource((OCResource *) handle);
5153 OIC_LOG(ERROR, TAG, "Resource not found");
5154 return OC_STACK_ERROR;
5157 resource->ins = ins;
5163 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5164 const OCClientResponse *response)
5166 // Validate input parameters
5167 VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5168 VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5170 char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5173 return OC_STACK_NO_MEMORY;
5175 strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5177 if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5179 OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5181 char rdPubUri[MAX_URI_LENGTH] = { 0 };
5182 snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5183 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5185 if (strcmp(rdPubUri, targetUri) == 0)
5187 // Update resource unique id in stack.
5190 if (response->payload)
5192 OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5193 OCRepPayload **links = NULL;
5194 size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5195 if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5196 &links, dimensions))
5199 for (; i < dimensions[0]; i++)
5202 if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5204 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5206 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5208 OCBindResourceInsToResource(handle, ins);
5217 size_t count = calcDimTotal(dimensions);
5218 for (size_t k = 0; k < count; k++)
5220 OCRepPayloadDestroy(links[k]);
5228 else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5230 OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5232 uint8_t numResources = 0;
5233 OCGetNumberOfResources(&numResources);
5235 char *ins = strstr(targetUri, OC_RSRVD_INS);
5238 for (uint8_t i = 0; i < numResources; i++)
5240 OCResourceHandle resHandle = OCGetResourceHandle(i);
5243 OCBindResourceInsToResource(resHandle, 0);
5249 const char *token = "&";
5250 char *iterTokenPtr = NULL;
5251 char *start = strtok_r(targetUri, token, &iterTokenPtr);
5253 while (start != NULL)
5255 char *query = start;
5256 query = strstr(query, OC_RSRVD_INS);
5259 int64_t queryIns = atoi(query + 4);
5260 for (uint8_t i = 0; i < numResources; i++)
5262 OCResourceHandle resHandle = OCGetResourceHandle(i);
5266 OCGetResourceIns(resHandle, &resIns);
5267 if (queryIns && queryIns == resIns)
5269 OCBindResourceInsToResource(resHandle, 0);
5275 start = strtok_r(NULL, token, &iterTokenPtr);
5284 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5288 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5292 OCResource *pointer = headResource;
5296 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5298 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5301 pointer = pointer->next;
5306 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t *ins)
5308 OCResource *resource = NULL;
5310 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5311 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5313 resource = findResource((OCResource *) handle);
5316 *ins = resource->ins;
5319 return OC_STACK_ERROR;
5323 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5324 void* optionData, size_t optionDataLength)
5328 OIC_LOG (INFO, TAG, "Header options are NULL");
5329 return OC_STACK_INVALID_PARAM;
5334 OIC_LOG (INFO, TAG, "optionData are NULL");
5335 return OC_STACK_INVALID_PARAM;
5340 OIC_LOG (INFO, TAG, "numOptions is NULL");
5341 return OC_STACK_INVALID_PARAM;
5344 if (*numOptions >= MAX_HEADER_OPTIONS)
5346 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5347 return OC_STACK_NO_MEMORY;
5350 ocHdrOpt += *numOptions;
5351 ocHdrOpt->protocolID = OC_COAP_ID;
5352 ocHdrOpt->optionID = optionID;
5353 ocHdrOpt->optionLength =
5354 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
5355 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5356 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5362 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5363 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5365 if (!ocHdrOpt || !numOptions)
5367 OIC_LOG (INFO, TAG, "No options present");
5373 OIC_LOG (INFO, TAG, "optionData are NULL");
5374 return OC_STACK_INVALID_PARAM;
5377 if (!receivedDataLength)
5379 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5380 return OC_STACK_INVALID_PARAM;
5383 for (uint8_t i = 0; i < numOptions; i++)
5385 if (ocHdrOpt[i].optionID == optionID)
5387 if (optionDataLength >= ocHdrOpt->optionLength)
5389 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5390 *receivedDataLength = ocHdrOpt->optionLength;
5395 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5396 return OC_STACK_ERROR;
5403 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5405 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5406 if (g_adapterHandler)
5408 g_adapterHandler(adapter, enabled);
5412 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5414 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5415 if (g_connectionHandler)
5417 g_connectionHandler(info, isConnected);
5421 * If the client observes one or more resources over a reliable connection,
5422 * then the CoAP server (or intermediary in the role of the CoAP server)
5423 * MUST remove all entries associated with the client endpoint from the lists
5424 * of observers when the connection is either closed or times out.
5428 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5429 CopyEndpointToDevAddr(info, &devAddr);
5431 // remove observer list with remote device address.
5432 DeleteObserverUsingDevAddr(&devAddr);
5436 void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
5437 CAConnectionStateChangedCB connectionHandler)
5439 OIC_LOG(DEBUG, TAG, "OCSetNetworkMonitorHandler");
5440 g_adapterHandler = adapterHandler;
5441 g_connectionHandler = connectionHandler;
5444 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5447 OCStackResult ret = OC_STACK_ERROR;
5449 ret = GetDoxmDeviceID(&oicUuid);
5450 if (OC_STACK_OK == ret)
5452 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5456 OIC_LOG(ERROR, TAG, "Device ID Get error");
5461 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5464 OCStackResult ret = OC_STACK_ERROR;
5466 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5467 for (int i = 0; i < UUID_LENGTH; i++)
5469 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5471 ret = SetDoxmDeviceID(&oicUuid);
5475 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5477 bool isDeviceOwned = true;
5478 OCStackResult ret = OC_STACK_ERROR;
5480 ret = GetDoxmIsOwned(&isDeviceOwned);
5481 if (OC_STACK_OK == ret)
5483 *isOwned = isDeviceOwned;
5487 OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5492 void OCClearCallBackList()
5494 DeleteClientCBList();
5497 void OCClearObserverlist()
5499 DeleteObserverList();
5502 int OCEncrypt(const unsigned char *pt, size_t pt_len,
5503 unsigned char **ct, size_t *ct_len)
5505 #ifndef __SECURE_PSI__
5506 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5509 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5511 return psiEncrypt(pt, pt_len, ct, ct_len);
5512 #endif // __SECURE_PSI__
5515 int OCDecrypt(const unsigned char *ct, size_t ct_len,
5516 unsigned char **pt, size_t *pt_len)
5518 #ifndef __SECURE_PSI__
5519 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5522 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5524 return psiDecrypt(ct, ct_len, pt, pt_len);
5525 #endif // __SECURE_PSI__
5528 OCStackResult OCSetKey(const unsigned char* key)
5530 #ifndef __SECURE_PSI__
5531 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5534 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5536 return psiSetKey(key);
5537 #endif // __SECURE_PSI__
5540 OCStackResult OCGetKey(unsigned char* key)
5542 #ifndef __SECURE_PSI__
5543 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5546 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5548 return psiGetKey(key);
5549 #endif // __SECURE_PSI__
5552 OCStackResult OCSetSecurePSI(const unsigned char *key, const OCPersistentStorage *psPlain,
5553 const OCPersistentStorage *psEnc, const OCPersistentStorage *psRescue)
5555 #ifndef __SECURE_PSI__
5556 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5559 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5561 return setSecurePSI(key, psPlain, psEnc, psRescue);
5562 #endif // __SECURE_PSI__
5565 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5566 static void OtmEventHandler(const char *addr, uint16_t port, const char *uuid, int event)
5568 if (g_otmEventHandler.cb)
5570 g_otmEventHandler.cb(g_otmEventHandler.ctx, addr, port, uuid, event);
5575 * It is already declared in srmutility.h.
5576 * We can't include the header file, because of "redefined VERIFY_NON_NULL"
5578 typedef void (*OicSecOtmEventHandler_t)(const char* addr, uint16_t port,
5579 const char* uuid, int event);
5580 void SetOtmEventHandler(OicSecOtmEventHandler_t otmEventHandler);
5583 OCStackResult OCSetOtmEventHandler(void *ctx, OCOtmEventHandler cb)
5585 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5586 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5588 g_otmEventHandler.cb = cb;
5589 g_otmEventHandler.ctx = ctx;
5591 if (g_otmEventHandler.cb)
5593 OIC_LOG(DEBUG, TAG, "SET OCOtmEventHandler");
5594 SetOtmEventHandler(OtmEventHandler);
5598 OIC_LOG(DEBUG, TAG, "UNSET OCOtmEventHandler");
5599 SetOtmEventHandler(NULL);
5602 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);