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);
434 //-----------------------------------------------------------------------------
435 // Internal functions
436 //-----------------------------------------------------------------------------
438 bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
440 if (!options || 0 == numOptions)
442 OIC_LOG (INFO, TAG, "No options present");
446 for (uint8_t i = 0; i < numOptions; i++)
448 if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
450 OIC_LOG(DEBUG, TAG, "Proxy URI is present");
457 uint32_t GetTicks(uint32_t milliSeconds)
462 // Guard against overflow of uint32_t
463 if (milliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
464 COAP_TICKS_PER_SECOND)
466 return now + (milliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
474 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
476 VERIFY_NON_NULL_NR(in, FATAL);
477 VERIFY_NON_NULL_NR(out, FATAL);
479 out->adapter = (OCTransportAdapter)in->adapter;
480 out->flags = CAToOCTransportFlags(in->flags);
481 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
482 out->port = in->port;
483 out->ifindex = in->ifindex;
484 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
485 /* This assert is to prevent accidental mismatch between address size macros defined in
486 * RI and CA and cause crash here. */
487 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
488 "Address size mismatch between RI and CA");
489 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
493 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
495 VERIFY_NON_NULL_NR(in, FATAL);
496 VERIFY_NON_NULL_NR(out, FATAL);
498 out->adapter = (CATransportAdapter_t)in->adapter;
499 out->flags = OCToCATransportFlags(in->flags);
500 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
501 OICStrcpy(out->remoteId, sizeof(out->remoteId), in->remoteId);
502 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
503 /* This assert is to prevent accidental mismatch between address size macros defined in
504 * RI and CA and cause crash here. */
505 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
506 "Address size mismatch between RI and CA");
507 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
509 out->port = in->port;
510 out->ifindex = in->ifindex;
513 void FixUpClientResponse(OCClientResponse *cr)
515 VERIFY_NON_NULL_NR(cr, FATAL);
517 cr->addr = &cr->devAddr;
518 cr->connType = (OCConnectivityType)
519 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
522 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
524 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
525 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
526 OIC_TRACE_BEGIN(%s:OCSendRequest, TAG);
528 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
529 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
530 if (OC_STACK_OK != rmResult)
532 OIC_LOG(ERROR, TAG, "Add destination option failed");
538 // OC stack prefer CBOR encoded payloads.
539 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
540 CAResult_t result = CASendRequest(object, requestInfo);
541 if(CA_STATUS_OK != result)
543 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
545 return CAResultToOCResult(result);
551 //-----------------------------------------------------------------------------
552 // Internal API function
553 //-----------------------------------------------------------------------------
555 // This internal function is called to update the stack with the status of
556 // observers and communication failures
557 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
559 OCStackResult result = OC_STACK_ERROR;
560 ResourceObserver * observer = NULL;
561 OCEntityHandlerRequest ehRequest = {0};
565 case OC_OBSERVER_NOT_INTERESTED:
566 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
567 observer = GetObserverUsingToken(token, tokenLength);
570 result = FormOCEntityHandlerRequest(&ehRequest,
574 (OCResourceHandle)NULL,
575 NULL, PAYLOAD_TYPE_REPRESENTATION,
577 OC_OBSERVE_DEREGISTER,
580 if (result != OC_STACK_OK)
582 FreeObserver(observer);
586 if (observer->resource && observer->resource->entityHandler)
588 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
589 observer->resource->entityHandlerCallbackParam);
592 FreeObserver(observer);
595 result = DeleteObserverUsingToken(token, tokenLength);
596 if (result == OC_STACK_OK)
598 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
602 result = OC_STACK_OK;
603 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
607 case OC_OBSERVER_STILL_INTERESTED:
608 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
609 observer = GetObserverUsingToken(token, tokenLength);
612 observer->forceHighQos = 0;
613 observer->failedCommCount = 0;
614 result = OC_STACK_OK;
615 FreeObserver(observer);
619 result = OC_STACK_OBSERVER_NOT_FOUND;
623 case OC_OBSERVER_FAILED_COMM:
624 OIC_LOG(DEBUG, TAG, "observer is unreachable");
625 observer = GetObserverUsingToken (token, tokenLength);
628 if (observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
630 result = FormOCEntityHandlerRequest(&ehRequest,
634 (OCResourceHandle)NULL,
635 NULL, PAYLOAD_TYPE_REPRESENTATION,
637 OC_OBSERVE_DEREGISTER,
640 if (result != OC_STACK_OK)
642 FreeObserver(observer);
643 return OC_STACK_ERROR;
646 if (observer->resource && observer->resource->entityHandler)
648 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
649 observer->resource->entityHandlerCallbackParam);
652 result = DeleteObserverUsingToken(token, tokenLength);
653 if (result == OC_STACK_OK)
655 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
659 result = OC_STACK_OK;
660 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
665 observer->failedCommCount++;
666 observer->forceHighQos = 1;
667 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",
668 observer->failedCommCount);
669 result = OC_STACK_CONTINUE;
672 FreeObserver(observer);
676 OIC_LOG(ERROR, TAG, "Unknown status");
677 result = OC_STACK_ERROR;
683 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
685 OCStackResult ret = OC_STACK_ERROR;
689 ret = OC_STACK_RESOURCE_CREATED;
692 ret = OC_STACK_RESOURCE_DELETED;
695 ret = OC_STACK_RESOURCE_CHANGED;
702 ret = OC_STACK_INVALID_QUERY;
704 case CA_UNAUTHORIZED_REQ:
705 ret = OC_STACK_UNAUTHORIZED_REQ;
708 ret = OC_STACK_INVALID_OPTION;
711 ret = OC_STACK_NO_RESOURCE;
713 case CA_REQUEST_ENTITY_TOO_LARGE:
714 ret = OC_STACK_TOO_LARGE_REQ;
716 case CA_METHOD_NOT_ALLOWED:
717 ret = OC_STACK_METHOD_NOT_ALLOWED;
719 case CA_NOT_ACCEPTABLE:
720 ret = OC_STACK_NOT_ACCEPTABLE;
722 case CA_FORBIDDEN_REQ:
723 ret = OC_STACK_FORBIDDEN_REQ;
725 case CA_INTERNAL_SERVER_ERROR:
726 ret = OC_STACK_INTERNAL_SERVER_ERROR;
728 case CA_NOT_IMPLEMENTED:
729 ret = OC_STACK_NOT_IMPLEMENTED;
732 ret = OC_STACK_BAD_GATEWAY;
734 case CA_SERVICE_UNAVAILABLE:
735 ret = OC_STACK_SERVICE_UNAVAILABLE;
737 case CA_RETRANSMIT_TIMEOUT:
738 ret = OC_STACK_GATEWAY_TIMEOUT;
740 case CA_PROXY_NOT_SUPPORTED:
741 ret = OC_STACK_PROXY_NOT_SUPPORTED;
749 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
751 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
760 // This Response Code is like HTTP 204 "No Content" but only used in
761 // response to POST and PUT requests.
765 // This Response Code is like HTTP 200 "OK" but only used in response to
770 // This should not happen but,
771 // give it a value just in case but output an error
773 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
777 case OC_STACK_RESOURCE_CREATED:
780 case OC_STACK_RESOURCE_DELETED:
783 case OC_STACK_RESOURCE_CHANGED:
786 case OC_STACK_INVALID_QUERY:
789 case OC_STACK_INVALID_OPTION:
792 case OC_STACK_NO_RESOURCE:
795 case OC_STACK_COMM_ERROR:
796 ret = CA_RETRANSMIT_TIMEOUT;
798 case OC_STACK_METHOD_NOT_ALLOWED:
799 ret = CA_METHOD_NOT_ALLOWED;
801 case OC_STACK_NOT_ACCEPTABLE:
802 ret = CA_NOT_ACCEPTABLE;
804 case OC_STACK_UNAUTHORIZED_REQ:
805 ret = CA_UNAUTHORIZED_REQ;
807 case OC_STACK_FORBIDDEN_REQ:
808 ret = CA_FORBIDDEN_REQ;
810 case OC_STACK_INTERNAL_SERVER_ERROR:
811 ret = CA_INTERNAL_SERVER_ERROR;
813 case OC_STACK_NOT_IMPLEMENTED:
814 ret = CA_NOT_IMPLEMENTED;
816 case OC_STACK_BAD_GATEWAY:
817 ret = CA_BAD_GATEWAY;
819 case OC_STACK_SERVICE_UNAVAILABLE:
820 ret = CA_SERVICE_UNAVAILABLE;
822 case OC_STACK_GATEWAY_TIMEOUT:
823 ret = CA_RETRANSMIT_TIMEOUT;
825 case OC_STACK_PROXY_NOT_SUPPORTED:
826 ret = CA_PROXY_NOT_SUPPORTED;
834 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
836 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
838 // supply default behavior.
839 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
841 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
843 if ((caFlags & OC_MASK_SCOPE) == 0)
845 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
850 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
852 return (OCTransportFlags)caFlags;
856 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
858 uint32_t lowerBound = 0;
859 uint32_t higherBound = 0;
861 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
863 return OC_STACK_INVALID_PARAM;
866 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
868 cbNode->presence->TTL = maxAgeSeconds;
870 for (int index = 0; index < PresenceTimeOutSize; index++)
872 // Guard against overflow
873 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
876 lowerBound = GetTicks((PresenceTimeOut[index] *
877 cbNode->presence->TTL *
878 MILLISECONDS_PER_SECOND)/100);
882 lowerBound = GetTicks(UINT32_MAX);
885 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
888 higherBound = GetTicks((PresenceTimeOut[index + 1] *
889 cbNode->presence->TTL *
890 MILLISECONDS_PER_SECOND)/100);
894 higherBound = GetTicks(UINT32_MAX);
897 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
899 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
900 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
901 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
904 cbNode->presence->TTLlevel = 0;
906 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
910 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
912 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
914 return OC_RSRVD_TRIGGER_CREATE;
916 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
918 return OC_RSRVD_TRIGGER_CHANGE;
922 return OC_RSRVD_TRIGGER_DELETE;
926 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
930 return OC_PRESENCE_TRIGGER_CREATE;
932 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
934 return OC_PRESENCE_TRIGGER_CREATE;
936 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
938 return OC_PRESENCE_TRIGGER_CHANGE;
942 return OC_PRESENCE_TRIGGER_DELETE;
945 #endif // WITH_PRESENCE
947 OCStackResult OCEncodeAddressForRFC6874(char *outputAddress,
949 const char *inputAddress)
951 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
952 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
954 size_t inputLength = strnlen(inputAddress, outputSize);
956 // inputSize includes the null terminator
957 size_t inputSize = inputLength + 1;
959 if (inputSize > outputSize)
961 OIC_LOG_V(ERROR, TAG,
962 "OCEncodeAddressForRFC6874 failed: "
963 "outputSize (%zu) < inputSize (%zu)",
964 outputSize, inputSize);
966 return OC_STACK_ERROR;
969 char* percentChar = strchr(inputAddress, '%');
971 // If there is no '%' character, then no change is required to the string.
972 if (NULL == percentChar)
974 OICStrcpy(outputAddress, outputSize, inputAddress);
978 const char* addressPart = &inputAddress[0];
979 const char* scopeIdPart = percentChar + 1;
981 // Sanity check to make sure this string doesn't have more '%' characters
982 if (NULL != strchr(scopeIdPart, '%'))
984 return OC_STACK_ERROR;
987 // If no string follows the first '%', then the input was invalid.
988 if (scopeIdPart[0] == '\0')
990 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
991 return OC_STACK_ERROR;
994 // Check to see if the string is already encoded
995 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
997 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Input string is already encoded");
998 return OC_STACK_ERROR;
1001 // Fail if we don't have room for encoded string's two additional chars
1002 if (outputSize < (inputSize + 2))
1004 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: encoded output will not fit!");
1005 return OC_STACK_ERROR;
1008 // Restore the null terminator with an escaped '%' character, per RFC 6874
1009 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
1010 OICStrcat(outputAddress, outputSize, "%25");
1011 OICStrcat(outputAddress, outputSize, scopeIdPart);
1016 OCStackResult OCDecodeAddressForRFC6874(char *outputAddress,
1018 const char *inputAddress,
1021 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
1022 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
1026 end = inputAddress + strlen(inputAddress);
1028 size_t inputLength = end - inputAddress;
1030 const char *percent = strchr(inputAddress, '%');
1031 if (!percent || (percent > end))
1033 OICStrcpyPartial(outputAddress, outputSize, inputAddress, inputLength);
1037 if (percent[1] != '2' || percent[2] != '5')
1039 return OC_STACK_INVALID_URI;
1042 int addrlen = percent - inputAddress + 1;
1043 OICStrcpyPartial(outputAddress, outputSize, inputAddress, addrlen);
1044 OICStrcpyPartial(outputAddress + addrlen, outputSize - addrlen,
1045 percent + 3, end - percent - 3);
1051 #ifdef WITH_PRESENCE
1053 * The cononical presence allows constructed URIs to be string compared.
1055 * requestUri must be a char array of size CA_MAX_URI_LENGTH
1057 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
1058 char *presenceUri, bool isMulticast)
1060 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
1061 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1065 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1066 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1069 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1070 if (ep->adapter == CA_ADAPTER_IP)
1072 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1074 if ('\0' == ep->addr[0]) // multicast
1076 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1080 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1082 OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1083 sizeof(addressEncoded),
1086 if (OC_STACK_OK != result)
1091 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1092 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1097 if ('\0' == ep->addr[0]) // multicast
1099 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1100 ep->port = OC_MULTICAST_PORT;
1102 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1103 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1107 // might work for other adapters (untested, but better than nothing)
1108 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1109 OC_RSRVD_PRESENCE_URI);
1113 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1114 const CAResponseInfo_t *responseInfo)
1116 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1117 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1119 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1120 ClientCB * cbNode = NULL;
1121 char *resourceTypeName = NULL;
1122 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1123 OCStackResult result = OC_STACK_ERROR;
1124 uint32_t maxAge = 0;
1126 char presenceUri[CA_MAX_URI_LENGTH];
1128 int presenceSubscribe = 0;
1129 int multicastPresenceSubscribe = 0;
1131 if (responseInfo->result != CA_CONTENT)
1133 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1134 return OC_STACK_ERROR;
1137 response.payload = NULL;
1138 response.result = OC_STACK_OK;
1140 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1141 FixUpClientResponse(&response);
1143 if (responseInfo->info.payload)
1145 result = OCParsePayload(&response.payload,
1146 PAYLOAD_TYPE_PRESENCE,
1147 responseInfo->info.payload,
1148 responseInfo->info.payloadSize);
1150 if(result != OC_STACK_OK)
1152 OIC_LOG(ERROR, TAG, "Presence parse failed");
1155 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1157 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1158 result = OC_STACK_ERROR;
1161 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1162 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1163 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1166 // check for unicast presence
1167 uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1168 responseInfo->isMulticast);
1169 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1171 return OC_STACK_INVALID_URI;
1173 OIC_LOG(INFO, TAG, "check for unicast presence");
1174 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1177 presenceSubscribe = 1;
1181 // check for multicast presence
1182 OIC_LOG(INFO, TAG, "check for multicast presence");
1183 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1186 multicastPresenceSubscribe = 1;
1190 if (!presenceSubscribe && !multicastPresenceSubscribe)
1192 OIC_LOG(INFO, TAG, "Received a presence notification, "
1193 "but need to register presence callback, ignoring");
1197 if (presenceSubscribe)
1199 if(cbNode->sequenceNumber == response.sequenceNumber)
1201 OIC_LOG(INFO, TAG, "No presence change");
1202 ResetPresenceTTL(cbNode, maxAge);
1203 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1209 OIC_LOG(INFO, TAG, "Stopping presence");
1210 response.result = OC_STACK_PRESENCE_STOPPED;
1211 if(cbNode->presence)
1213 OICFree(cbNode->presence->timeOut);
1214 OICFree(cbNode->presence);
1215 cbNode->presence = NULL;
1220 if(!cbNode->presence)
1222 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1224 if(!(cbNode->presence))
1226 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1227 result = OC_STACK_NO_MEMORY;
1231 VERIFY_NON_NULL_V(cbNode->presence);
1232 cbNode->presence->timeOut = NULL;
1233 cbNode->presence->timeOut = (uint32_t *)
1234 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1235 if(!(cbNode->presence->timeOut)){
1237 "Could not allocate memory for cbNode->presence->timeOut");
1238 OICFree(cbNode->presence);
1239 result = OC_STACK_NO_MEMORY;
1244 ResetPresenceTTL(cbNode, maxAge);
1246 cbNode->sequenceNumber = response.sequenceNumber;
1251 // This is the multicast case
1252 OIC_LOG(INFO, TAG, "this is the multicast presence");
1255 OIC_LOG(INFO, TAG, "Stopping presence");
1256 response.result = OC_STACK_PRESENCE_STOPPED;
1260 // Ensure that a filter is actually applied.
1261 if (resourceTypeName && cbNode->filterResourceType)
1263 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1264 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1270 OIC_LOG(INFO, TAG, "Before calling into application address space for presence");
1271 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1272 OIC_LOG(INFO, TAG, "After calling into application address space for presence");
1274 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1276 FindAndDeleteClientCB(cbNode);
1280 OCPayloadDestroy(response.payload);
1283 #endif // WITH_PRESENCE
1285 OCStackResult HandleBatchResponse(char *requestUri, OCRepPayload **payload)
1287 if (requestUri && *payload)
1289 char *interfaceName = NULL;
1290 char *rtTypeName = NULL;
1291 char *uriQuery = NULL;
1292 char *uriWithoutQuery = NULL;
1293 if (OC_STACK_OK == getQueryFromUri(requestUri, &uriQuery, &uriWithoutQuery))
1295 if (OC_STACK_OK == ExtractFiltersFromQuery(uriQuery, &interfaceName, &rtTypeName))
1297 if (interfaceName && (0 == strcmp(OC_RSRVD_INTERFACE_BATCH, interfaceName)))
1299 char *uri = (*payload)->uri;
1300 if (uri && 0 != strcmp(uriWithoutQuery, uri))
1302 OCRepPayload *newPayload = OCRepPayloadCreate();
1305 OCRepPayloadSetUri(newPayload, uri);
1306 newPayload->next = *payload;
1307 *payload = newPayload;
1314 OICFree(interfaceName);
1315 OICFree(rtTypeName);
1317 OICFree(uriWithoutQuery);
1320 return OC_STACK_INVALID_PARAM;
1323 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1325 OIC_TRACE_MARK(%s:OCHandleResponse:%s, TAG, responseInfo->info.resourceUri);
1326 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1328 #ifdef WITH_PRESENCE
1329 if(responseInfo->info.resourceUri &&
1330 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1332 HandlePresenceResponse(endPoint, responseInfo);
1337 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1338 responseInfo->info.tokenLength, NULL, NULL);
1342 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1344 // check obs header option
1345 bool obsHeaderOpt = false;
1346 CAHeaderOption_t *options = responseInfo->info.options;
1347 for (uint8_t i = 0; i< responseInfo->info.numOptions; i++)
1349 if (options && options[i].protocolID == CA_COAP_ID &&
1350 options[i].optionID == COAP_OPTION_OBSERVE)
1352 obsHeaderOpt = true;
1357 if(responseInfo->result == CA_EMPTY)
1359 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1360 // We do not have a case for the client to receive a RESET
1361 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1363 //This is the case of receiving an ACK on a request to a slow resource!
1364 OIC_LOG(INFO, TAG, "This is a pure ACK");
1365 //TODO: should we inform the client
1366 // app that at least the request was received at the server?
1369 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1371 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1373 OCClientResponse response =
1374 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1375 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1376 FixUpClientResponse(&response);
1377 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1378 memcpy(response.identity.id, responseInfo->info.identity.id,
1379 sizeof (response.identity.id));
1380 response.identity.id_length = responseInfo->info.identity.id_length;
1382 response.result = CAResponseToOCStackResult(responseInfo->result);
1383 OIC_LOG(INFO, TAG, "Before calling into application address space for reTrans timeout");
1384 cbNode->callBack(cbNode->context,
1385 cbNode->handle, &response);
1386 OIC_LOG(INFO, TAG, "After calling into application address space for reTrans timeout");
1387 FindAndDeleteClientCB(cbNode);
1388 OICFree((void *)response.resourceUri);
1391 else if ((cbNode->method == OC_REST_OBSERVE || cbNode->method == OC_REST_OBSERVE_ALL)
1392 && (responseInfo->result == CA_CONTENT) && !obsHeaderOpt)
1394 OCClientResponse response =
1395 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1396 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1397 FixUpClientResponse(&response);
1398 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1399 memcpy(response.identity.id, responseInfo->info.identity.id,
1400 sizeof (response.identity.id));
1401 response.identity.id_length = responseInfo->info.identity.id_length;
1402 response.result = OC_STACK_UNAUTHORIZED_REQ;
1404 OIC_LOG(INFO, TAG, "Before calling into application address space for observe resp");
1405 cbNode->callBack(cbNode->context,
1408 OIC_LOG(INFO, TAG, "After calling into application address space for observe resp");
1410 FindAndDeleteClientCB(cbNode);
1411 OICFree(response.resourceUri);
1416 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1418 OCClientResponse response;
1419 memset(&response, 0, sizeof(OCClientResponse));
1420 response.devAddr.adapter = OC_DEFAULT_ADAPTER;
1422 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1423 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1424 FixUpClientResponse(&response);
1425 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1426 memcpy(response.identity.id, responseInfo->info.identity.id,
1427 sizeof (response.identity.id));
1428 response.identity.id_length = responseInfo->info.identity.id_length;
1430 response.result = CAResponseToOCStackResult(responseInfo->result);
1432 if(responseInfo->info.payload &&
1433 responseInfo->info.payloadSize)
1435 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1436 // check the security resource
1437 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1439 type = PAYLOAD_TYPE_SECURITY;
1441 else if (cbNode->method == OC_REST_DISCOVER)
1443 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1444 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1446 type = PAYLOAD_TYPE_DISCOVERY;
1449 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1451 type = PAYLOAD_TYPE_DISCOVERY;
1454 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1456 type = PAYLOAD_TYPE_REPRESENTATION;
1458 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1460 type = PAYLOAD_TYPE_REPRESENTATION;
1463 #ifdef ROUTING_GATEWAY
1464 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1466 type = PAYLOAD_TYPE_REPRESENTATION;
1469 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1471 type = PAYLOAD_TYPE_REPRESENTATION;
1474 else if (strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1476 type = PAYLOAD_TYPE_REPRESENTATION;
1481 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1482 cbNode->method, cbNode->requestUri);
1483 OICFree((void *)response.resourceUri);
1487 else if (cbNode->method == OC_REST_GET ||
1488 cbNode->method == OC_REST_PUT ||
1489 cbNode->method == OC_REST_POST ||
1490 cbNode->method == OC_REST_OBSERVE ||
1491 cbNode->method == OC_REST_OBSERVE_ALL ||
1492 cbNode->method == OC_REST_DELETE)
1494 if (cbNode->requestUri)
1496 if (0 == strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri))
1498 type = PAYLOAD_TYPE_REPRESENTATION;
1500 else if (0 == strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri))
1502 type = PAYLOAD_TYPE_REPRESENTATION;
1504 if (type == PAYLOAD_TYPE_INVALID)
1506 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1507 cbNode->method, cbNode->requestUri);
1508 type = PAYLOAD_TYPE_REPRESENTATION;
1513 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1514 type = PAYLOAD_TYPE_REPRESENTATION;
1519 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1520 cbNode->method, cbNode->requestUri);
1521 OICFree((void *)response.resourceUri);
1525 // In case of error, still want application to receive the error message.
1526 if (OCResultToSuccess(response.result) || PAYLOAD_TYPE_REPRESENTATION == type)
1528 if(OC_STACK_OK != OCParsePayload(&response.payload,
1530 responseInfo->info.payload,
1531 responseInfo->info.payloadSize))
1533 OIC_LOG(ERROR, TAG, "Error converting payload");
1534 OCPayloadDestroy(response.payload);
1535 OICFree((void *)response.resourceUri);
1541 OICFree((void *)response.resourceUri);
1542 response.resourceUri = OICStrdup(cbNode->requestUri);
1546 response.numRcvdVendorSpecificHeaderOptions = 0;
1547 if(responseInfo->info.numOptions > 0)
1550 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1551 if(responseInfo->info.options
1552 && responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1555 uint32_t observationOption;
1556 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1557 for (observationOption=0, i=0;
1558 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1562 (observationOption << 8) | optionData[i];
1564 response.sequenceNumber = observationOption;
1565 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1570 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1573 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1575 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1576 OCPayloadDestroy(response.payload);
1577 OICFree((void *)response.resourceUri);
1581 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1583 if(&(responseInfo->info.options[i]))
1585 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1586 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1591 if (cbNode->method == OC_REST_OBSERVE &&
1592 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1593 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1594 response.sequenceNumber <= cbNode->sequenceNumber)
1596 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1597 response.sequenceNumber);
1602 if (cbNode->requestUri)
1604 // if request uri is '/oic/rd', update ins value of resource.
1605 char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
1608 OCUpdateResourceInsWithResponse(cbNode->requestUri, &response);
1612 // set remoteID(device ID) into OCClientResponse callback parameter
1613 if (OC_REST_DISCOVER == cbNode->method)
1615 OIC_LOG(INFO, TAG, "cbNode method is OC_REST_DISCOVER");
1616 OCDiscoveryPayload *payload = (OCDiscoveryPayload*) response.payload;
1617 // Payload can be empty in case of error message.
1618 if (payload && payload->sid)
1620 OICStrcpy(response.devAddr.remoteId, sizeof(response.devAddr.remoteId),
1622 OIC_LOG_V(INFO_PRIVATE, TAG, "Device ID of response : %s",
1623 response.devAddr.remoteId);
1626 if(NULL == response.resourceUri)
1628 response.resourceUri = OICStrdup(cbNode->requestUri);
1632 if (cbNode->requestUri)
1634 OIC_LOG_V(INFO, TAG, "cbNode requestUri is %s", cbNode->requestUri);
1635 if (cbNode->method == OC_REST_POST &&
1636 strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1638 OCHandleKeepAliveResponse(endPoint, response.payload);
1642 if (response.payload && response.payload->type == PAYLOAD_TYPE_REPRESENTATION)
1644 OIC_LOG(INFO, TAG, "Handle batch response");
1645 HandleBatchResponse(cbNode->requestUri, (OCRepPayload **)&response.payload);
1648 OIC_LOG(INFO, TAG, "Before calling into application address space for handleResponse");
1649 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1652 OIC_LOG(INFO, TAG, "After calling into application address space for handleResponse");
1654 cbNode->sequenceNumber = response.sequenceNumber;
1656 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1658 FindAndDeleteClientCB(cbNode);
1662 // To keep discovery callbacks active.
1663 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1664 MILLISECONDS_PER_SECOND);
1668 //Need to send ACK when the response is CON
1669 if(responseInfo->info.type == CA_MSG_CONFIRM)
1671 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1673 OIC_LOG(INFO, TAG, "Received a confirmable message. Sending EMPTY");
1674 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1675 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1679 OICFree((void *)response.resourceUri);
1680 OCPayloadDestroy(response.payload);
1685 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1686 responseInfo->info.tokenLength);
1690 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1691 if(responseInfo->result == CA_EMPTY)
1693 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1694 if(responseInfo->info.type == CA_MSG_RESET)
1696 OIC_LOG(INFO, TAG, "This is a RESET");
1697 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1698 OC_OBSERVER_NOT_INTERESTED);
1700 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1702 OIC_LOG(INFO, TAG, "This is a pure ACK");
1703 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1704 OC_OBSERVER_STILL_INTERESTED);
1707 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1709 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1710 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1711 OC_OBSERVER_FAILED_COMM);
1714 FreeObserver(observer);
1718 if(!cbNode && !observer)
1720 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1721 || myStackMode == OC_GATEWAY)
1723 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1724 if(responseInfo->result == CA_EMPTY)
1726 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1730 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1732 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1733 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1734 CA_MSG_RESET, 0, NULL, NULL, 0, NULL,
1735 CA_RESPONSE_FOR_RES);
1740 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1741 || myStackMode == OC_GATEWAY)
1743 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1744 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1746 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1747 responseInfo->info.messageId);
1749 if (responseInfo->info.type == CA_MSG_RESET)
1751 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1752 responseInfo->info.messageId);
1760 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1762 VERIFY_NON_NULL_NR(endPoint, FATAL);
1763 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1765 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1766 OIC_TRACE_BEGIN(%s:HandleCAResponses, TAG);
1768 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1769 #ifdef ROUTING_GATEWAY
1770 bool needRIHandling = false;
1772 * Routing manager is going to update either of endpoint or response or both.
1773 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1774 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1777 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1779 if(ret != OC_STACK_OK || !needRIHandling)
1781 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1788 * Put source in sender endpoint so that the next packet from application can be routed to
1789 * proper destination and remove "RM" coap header option before passing request / response to
1790 * RI as this option will make no sense to either RI or application.
1792 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1793 (uint8_t *) &(responseInfo->info.numOptions),
1794 (CAEndpoint_t *) endPoint);
1797 OCHandleResponse(endPoint, responseInfo);
1799 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1803 * This function handles error response from CA
1804 * code shall be added to handle the errors
1806 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1808 VERIFY_NON_NULL_NR(endPoint, FATAL);
1809 VERIFY_NON_NULL_NR(errorInfo, FATAL);
1811 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1812 OIC_TRACE_BEGIN(%s:HandleCAErrorResponse, TAG);
1814 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1815 errorInfo->info.tokenLength, NULL, NULL);
1818 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1819 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1820 FixUpClientResponse(&response);
1821 response.resourceUri = errorInfo->info.resourceUri;
1822 memcpy(response.identity.id, errorInfo->info.identity.id,
1823 sizeof (response.identity.id));
1824 response.identity.id_length = errorInfo->info.identity.id_length;
1825 response.result = CAResultToOCResult(errorInfo->result);
1827 OIC_LOG(INFO, TAG, "Before calling into application address space for error response");
1828 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1829 OIC_LOG(INFO, TAG, "After calling into application address space for error response");
1832 ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1833 errorInfo->info.tokenLength);
1836 OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1837 OCStackResult result = CAResultToOCResult(errorInfo->result);
1838 if (OC_STACK_COMM_ERROR == result)
1840 OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1841 OC_OBSERVER_FAILED_COMM);
1845 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1850 * This function sends out Direct Stack Responses. These are responses that are not coming
1851 * from the application entity handler. These responses have no payload and are usually ACKs,
1852 * RESETs or some error conditions that were caught by the stack.
1854 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1855 const CAResponseResult_t responseResult, const CAMessageType_t type,
1856 const uint8_t numOptions, const CAHeaderOption_t *options,
1857 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1858 CADataType_t dataType)
1860 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1862 if (endPoint->flags & CA_MULTICAST)
1864 OIC_LOG(ERROR, TAG, "It is unnecessary to respond to a multicast request");
1868 CAResponseInfo_t respInfo = { .result = responseResult };
1869 respInfo.info.messageId = coapID;
1870 respInfo.info.numOptions = numOptions;
1872 if (respInfo.info.numOptions)
1874 respInfo.info.options =
1875 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1876 memcpy (respInfo.info.options, options,
1877 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1881 respInfo.info.payload = NULL;
1882 respInfo.info.token = token;
1883 respInfo.info.tokenLength = tokenLength;
1884 respInfo.info.type = type;
1885 respInfo.info.resourceUri = OICStrdup (resourceUri);
1886 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1887 respInfo.info.dataType = dataType;
1889 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1890 // Add the destination to route option from the endpoint->routeData.
1891 bool doPost = false;
1892 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1893 if(OC_STACK_OK != result)
1895 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1896 OICFree (respInfo.info.resourceUri);
1897 OICFree (respInfo.info.options);
1902 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1903 CARequestInfo_t reqInfo = {.method = CA_POST };
1904 /* The following initialization is not done in a single initializer block as in
1905 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1906 * does not have designated initalizers. This is a work-around for now.
1908 reqInfo.info.type = CA_MSG_NONCONFIRM;
1909 reqInfo.info.messageId = coapID;
1910 reqInfo.info.tokenLength = tokenLength;
1911 reqInfo.info.token = token;
1912 reqInfo.info.numOptions = respInfo.info.numOptions;
1913 reqInfo.info.payload = NULL;
1914 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1915 if (reqInfo.info.numOptions)
1917 reqInfo.info.options =
1918 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1919 if (NULL == reqInfo.info.options)
1921 OIC_LOG(ERROR, TAG, "Calloc failed");
1922 OICFree (reqInfo.info.resourceUri);
1923 OICFree (respInfo.info.resourceUri);
1924 OICFree (respInfo.info.options);
1925 return OC_STACK_NO_MEMORY;
1927 memcpy (reqInfo.info.options, respInfo.info.options,
1928 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1931 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1932 OICFree (reqInfo.info.resourceUri);
1933 OICFree (reqInfo.info.options);
1934 OICFree (respInfo.info.resourceUri);
1935 OICFree (respInfo.info.options);
1936 if (CA_STATUS_OK != caResult)
1938 OIC_LOG(ERROR, TAG, "CASendRequest error");
1939 return CAResultToOCResult(caResult);
1945 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1947 // resourceUri in the info field is cloned in the CA layer and
1948 // thus ownership is still here.
1949 OICFree (respInfo.info.resourceUri);
1950 OICFree (respInfo.info.options);
1951 if(CA_STATUS_OK != caResult)
1953 OIC_LOG(ERROR, TAG, "CASendResponse error");
1954 return CAResultToOCResult(caResult);
1957 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1961 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1963 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1964 OCStackResult result = OC_STACK_ERROR;
1965 if(!protocolRequest)
1967 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1968 return OC_STACK_INVALID_PARAM;
1971 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1972 protocolRequest->tokenLength);
1975 OIC_LOG(INFO, TAG, "This is a new Server Request");
1976 result = AddServerRequest(&request, protocolRequest->coapID,
1977 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1978 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1979 protocolRequest->observationOption, protocolRequest->qos,
1980 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1981 protocolRequest->payload, protocolRequest->requestToken,
1982 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1983 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1984 &protocolRequest->devAddr);
1985 if (OC_STACK_OK != result)
1987 OIC_LOG(ERROR, TAG, "Error adding server request");
1993 OIC_LOG(ERROR, TAG, "Out of Memory");
1994 return OC_STACK_NO_MEMORY;
1997 if(!protocolRequest->reqMorePacket)
1999 request->requestComplete = 1;
2004 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
2007 if(request->requestComplete)
2009 OIC_LOG(INFO, TAG, "This Server Request is complete");
2010 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2011 OCResource *resource = NULL;
2012 result = DetermineResourceHandling (request, &resHandling, &resource);
2013 if (result == OC_STACK_OK)
2015 result = ProcessRequest(resHandling, resource, request);
2020 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2021 result = OC_STACK_CONTINUE;
2026 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2028 OIC_TRACE_MARK(%s:OCHandleRequests:%s, TAG, requestInfo->info.resourceUri);
2029 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2031 OCStackResult requestResult = OC_STACK_ERROR;
2033 if(myStackMode == OC_CLIENT)
2035 //TODO: should the client be responding to requests?
2039 OCServerProtocolRequest serverRequest = {0};
2041 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2043 char * uriWithoutQuery = NULL;
2044 char * query = NULL;
2046 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2048 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2050 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2053 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2054 OIC_LOG_V(INFO, TAG, "Query : %s", query);
2056 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2058 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2059 OICFree(uriWithoutQuery);
2063 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2064 OICFree(uriWithoutQuery);
2071 if(strlen(query) < MAX_QUERY_LENGTH)
2073 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2078 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2084 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2086 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2087 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2088 if (!serverRequest.payload)
2090 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2093 memcpy (serverRequest.payload, requestInfo->info.payload,
2094 requestInfo->info.payloadSize);
2098 serverRequest.reqTotalSize = 0;
2101 switch (requestInfo->method)
2104 serverRequest.method = OC_REST_GET;
2107 serverRequest.method = OC_REST_PUT;
2110 serverRequest.method = OC_REST_POST;
2113 serverRequest.method = OC_REST_DELETE;
2116 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2117 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2118 requestInfo->info.type, requestInfo->info.numOptions,
2119 requestInfo->info.options, requestInfo->info.token,
2120 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2122 OICFree(serverRequest.payload);
2126 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2127 requestInfo->info.tokenLength);
2129 serverRequest.tokenLength = requestInfo->info.tokenLength;
2130 if (serverRequest.tokenLength) {
2132 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2134 if (!serverRequest.requestToken)
2136 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2137 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2138 requestInfo->info.type, requestInfo->info.numOptions,
2139 requestInfo->info.options, requestInfo->info.token,
2140 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2142 OICFree(serverRequest.payload);
2145 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2148 switch (requestInfo->info.acceptFormat)
2150 case CA_FORMAT_APPLICATION_CBOR:
2151 serverRequest.acceptFormat = OC_FORMAT_CBOR;
2153 case CA_FORMAT_UNDEFINED:
2154 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2157 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2160 if (requestInfo->info.type == CA_MSG_CONFIRM)
2162 serverRequest.qos = OC_HIGH_QOS;
2166 serverRequest.qos = OC_LOW_QOS;
2168 // CA does not need the following field
2169 // Are we sure CA does not need them? how is it responding to multicast
2170 serverRequest.delayedResNeeded = 0;
2172 serverRequest.coapID = requestInfo->info.messageId;
2174 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2176 // copy vendor specific header options
2177 uint8_t tempNum = (requestInfo->info.numOptions);
2179 // Assume no observation requested and it is a pure GET.
2180 // If obs registration/de-registration requested it'll be fetched from the
2181 // options in GetObserveHeaderOption()
2182 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2184 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2185 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2188 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2189 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2190 requestInfo->info.type, requestInfo->info.numOptions,
2191 requestInfo->info.options, requestInfo->info.token,
2192 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2194 OICFree(serverRequest.payload);
2195 OICFree(serverRequest.requestToken);
2198 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2199 if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2201 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
2202 sizeof(CAHeaderOption_t)*tempNum);
2205 requestResult = HandleStackRequests (&serverRequest);
2207 // Send ACK to client as precursor to slow response
2208 if (requestResult == OC_STACK_SLOW_RESOURCE)
2210 if (requestInfo->info.type == CA_MSG_CONFIRM)
2212 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2213 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2218 if (requestResult == OC_STACK_RESOURCE_ERROR
2219 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2221 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2224 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2226 if (requestResult == OC_STACK_RESOURCE_ERROR)
2228 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2230 else if (!OCResultToSuccess(requestResult))
2232 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2236 else if(!OCResultToSuccess(requestResult))
2238 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2240 CAResponseResult_t stackResponse =
2241 OCToCAStackResult(requestResult, serverRequest.method);
2243 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2244 requestInfo->info.type, requestInfo->info.numOptions,
2245 requestInfo->info.options, requestInfo->info.token,
2246 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2249 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2250 // The token is copied in there, and is thus still owned by this function.
2251 OICFree(serverRequest.payload);
2252 OICFree(serverRequest.requestToken);
2253 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2256 //This function will be called back by CA layer when a request is received
2257 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2259 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2260 OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2263 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2270 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2275 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2276 #ifdef ROUTING_GATEWAY
2277 bool needRIHandling = false;
2278 bool isEmptyMsg = false;
2280 * Routing manager is going to update either of endpoint or request or both.
2281 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2282 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2283 * destination. It can also remove "RM" coap header option before passing request / response to
2284 * RI as this option will make no sense to either RI or application.
2286 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2287 &needRIHandling, &isEmptyMsg);
2288 if(OC_STACK_OK != ret || !needRIHandling)
2290 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2297 * Put source in sender endpoint so that the next packet from application can be routed to
2298 * proper destination and remove RM header option.
2300 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2301 (uint8_t *) &(requestInfo->info.numOptions),
2302 (CAEndpoint_t *) endPoint);
2304 #ifdef ROUTING_GATEWAY
2308 * In Gateways, the MSGType in route option is used to check if the actual
2309 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2310 * EMPTY response is sent in the form of POST request which need to be changed
2311 * to a EMPTY response by RM. This translation is done in this part of the code.
2313 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2314 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2315 .info.messageId = requestInfo->info.messageId,
2316 .info.type = CA_MSG_ACKNOWLEDGE};
2317 OCHandleResponse(endPoint, &respInfo);
2323 // Normal handling of the packet
2324 OCHandleRequests(endPoint, requestInfo);
2326 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2330 //-----------------------------------------------------------------------------
2332 //-----------------------------------------------------------------------------
2334 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2337 !raInfo->username ||
2338 !raInfo->hostname ||
2339 !raInfo->xmpp_domain)
2342 return OC_STACK_INVALID_PARAM;
2344 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2345 gRASetInfo = (result == OC_STACK_OK)? true : false;
2351 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2355 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2358 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2360 OC_UNUSED(serverFlags);
2361 OC_UNUSED(clientFlags);
2363 OIC_LOG(DEBUG, TAG, "call OCInit1");
2364 return OCInit2(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS, OC_DEFAULT_ADAPTER);
2367 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2368 OCTransportAdapter transportType)
2370 if(stackState == OC_STACK_INITIALIZED)
2372 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2373 OCStop() between them are ignored.");
2377 #ifndef ROUTING_GATEWAY
2378 if (OC_GATEWAY == mode)
2380 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2381 return OC_STACK_INVALID_PARAM;
2388 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2389 return OC_STACK_ERROR;
2393 OCStackResult result = OC_STACK_ERROR;
2394 OIC_LOG(INFO, TAG, "Entering OCInit");
2397 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2398 || (mode == OC_GATEWAY)))
2400 OIC_LOG(ERROR, TAG, "Invalid mode");
2401 return OC_STACK_ERROR;
2405 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2407 caglobals.client = true;
2409 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2411 caglobals.server = true;
2414 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2415 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2417 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2419 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2420 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2422 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2425 defaultDeviceHandler = NULL;
2426 defaultDeviceHandlerCallbackParameter = NULL;
2428 result = InitializeScheduleResourceList();
2429 VERIFY_SUCCESS(result, OC_STACK_OK);
2431 result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2432 VERIFY_SUCCESS(result, OC_STACK_OK);
2434 result = CAResultToOCResult(OCSelectNetwork(transportType));
2435 VERIFY_SUCCESS(result, OC_STACK_OK);
2437 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2438 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2439 VERIFY_SUCCESS(result, OC_STACK_OK);
2441 switch (myStackMode)
2444 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2445 result = CAResultToOCResult(CAStartDiscoveryServer());
2446 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2449 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2450 result = CAResultToOCResult(CAStartListeningServer());
2451 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2453 case OC_CLIENT_SERVER:
2455 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2456 result = CAResultToOCResult(CAStartListeningServer());
2457 if(result == OC_STACK_OK)
2459 result = CAResultToOCResult(CAStartDiscoveryServer());
2463 VERIFY_SUCCESS(result, OC_STACK_OK);
2466 CARegisterKeepAliveHandler(OCHandleKeepAliveConnCB);
2469 #ifdef WITH_PRESENCE
2470 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2471 #endif // WITH_PRESENCE
2473 //Update Stack state to initialized
2474 stackState = OC_STACK_INITIALIZED;
2476 // Initialize resource
2477 if(myStackMode != OC_CLIENT)
2479 result = initResources();
2482 // Initialize the SRM Policy Engine
2483 if(result == OC_STACK_OK)
2485 result = SRMInitPolicyEngine();
2486 // TODO after BeachHead delivery: consolidate into single SRMInit()
2488 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2489 RMSetStackMode(mode);
2490 #ifdef ROUTING_GATEWAY
2491 if (OC_GATEWAY == myStackMode)
2493 result = RMInitialize();
2499 if (result == OC_STACK_OK)
2501 result = OCInitializeKeepAlive(myStackMode);
2505 InitializeObseverList();
2508 if(result != OC_STACK_OK)
2510 OIC_LOG(ERROR, TAG, "Stack initialization error");
2511 TerminateScheduleResourceList();
2512 deleteAllResources();
2514 stackState = OC_STACK_UNINITIALIZED;
2519 OCStackResult OCStop()
2521 OIC_LOG(INFO, TAG, "Entering OCStop");
2523 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2525 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2528 else if (stackState != OC_STACK_INITIALIZED)
2530 OIC_LOG(INFO, TAG, "Stack not initialized");
2531 return OC_STACK_ERROR;
2534 // unset cautil config
2535 CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2536 CAUtilSetBTConfigure(configs);
2538 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2540 CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2541 OCDefaultConnectionStateChangedHandler);
2543 #ifdef WITH_PRESENCE
2544 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2545 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2546 presenceResource.presenceTTL = 0;
2547 presenceState = OC_PRESENCE_UNINITIALIZED;
2548 #endif // WITH_PRESENCE
2550 #ifdef ROUTING_GATEWAY
2551 if (OC_GATEWAY == myStackMode)
2558 OCTerminateKeepAlive(myStackMode);
2561 TerminateScheduleResourceList();
2562 // Remove all observers
2563 TerminateObserverList();
2564 // Free memory dynamically allocated for resources
2565 deleteAllResources();
2566 // Remove all the client callbacks
2567 DeleteClientCBList();
2568 // Terminate connectivity-abstraction layer.
2571 // De-init the SRM Policy Engine
2572 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2573 SRMDeInitPolicyEngine();
2575 stackState = OC_STACK_UNINITIALIZED;
2579 OCStackResult OCStartMulticastServer()
2581 if(stackState != OC_STACK_INITIALIZED)
2583 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2584 return OC_STACK_ERROR;
2586 CAResult_t ret = CAStartListeningServer();
2587 if (CA_STATUS_OK != ret)
2589 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2590 return OC_STACK_ERROR;
2595 OCStackResult OCStopMulticastServer()
2597 CAResult_t ret = CAStopListeningServer();
2598 if (CA_STATUS_OK != ret)
2600 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2601 return OC_STACK_ERROR;
2606 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2611 return CA_MSG_CONFIRM;
2616 return CA_MSG_NONCONFIRM;
2620 OCStackResult ParseRequestUri(const char *fullUri,
2621 OCTransportAdapter adapter,
2622 OCTransportFlags flags,
2623 OCDevAddr **devAddr,
2625 char **resourceType)
2627 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2629 OCStackResult result = OC_STACK_OK;
2630 OCDevAddr *da = NULL;
2634 // provide defaults for all returned values
2641 *resourceUri = NULL;
2645 *resourceType = NULL;
2648 // delimit url prefix, if any
2649 const char *start = fullUri;
2650 char *slash2 = strstr(start, "//");
2655 char *slash = strchr(start, '/');
2658 return OC_STACK_INVALID_URI;
2661 // process url scheme
2662 size_t prefixLen = slash2 - fullUri;
2666 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2667 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2673 // TODO: this logic should come in with unit tests exercising the various strings
2674 // processs url prefix, if any
2675 size_t urlLen = slash - start;
2679 if (urlLen && devAddr)
2680 { // construct OCDevAddr
2681 if (start[0] == '[')
2683 char *close = strchr(++start, ']');
2684 if (!close || close > slash)
2686 return OC_STACK_INVALID_URI;
2689 if (close[1] == ':')
2696 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2700 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2702 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2706 char *dot = strchr(start, '.');
2707 if (dot && dot < slash)
2709 colon = strchr(start, ':');
2710 end = (colon && colon < slash) ? colon : slash;
2715 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2719 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2721 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2729 if (len >= sizeof(da->addr))
2731 return OC_STACK_INVALID_URI;
2733 // collect port, if any
2734 if (colon && colon < slash)
2736 for (colon++; colon < slash; colon++)
2739 if (c < '0' || c > '9')
2741 return OC_STACK_INVALID_URI;
2743 port = 10 * port + c - '0';
2748 if (len >= sizeof(da->addr))
2750 return OC_STACK_INVALID_URI;
2753 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2756 return OC_STACK_NO_MEMORY;
2759 // Decode address per RFC 6874.
2760 result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2761 if (result != OC_STACK_OK)
2768 da->adapter = adapter;
2770 if (!strncmp(fullUri, "coaps", 5))
2772 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2777 // process resource uri, if any
2779 { // request uri and query
2780 size_t ulen = strlen(slash); // resource uri length
2781 size_t tlen = 0; // resource type length
2784 static const char strPresence[] = "/oic/ad?rt=";
2785 static const size_t lenPresence = sizeof(strPresence) - 1;
2786 if (!strncmp(slash, strPresence, lenPresence))
2788 type = slash + lenPresence;
2789 tlen = ulen - lenPresence;
2794 *resourceUri = (char *)OICMalloc(ulen + 1);
2797 result = OC_STACK_NO_MEMORY;
2800 OICStrcpy(*resourceUri, (ulen + 1), slash);
2803 if (type && resourceType)
2805 *resourceType = (char *)OICMalloc(tlen + 1);
2808 result = OC_STACK_NO_MEMORY;
2812 OICStrcpy(*resourceType, (tlen+1), type);
2819 // free all returned values
2826 OICFree(*resourceUri);
2830 OICFree(*resourceType);
2835 #ifdef WITH_PRESENCE
2836 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2840 char uri[CA_MAX_URI_LENGTH];
2842 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2844 *requestUri = OICStrdup(uri);
2847 return OC_STACK_NO_MEMORY;
2852 #endif // WITH_PRESENCE
2855 * Discover or Perform requests on a specified resource
2857 OCStackResult OCDoResource(OCDoHandle *handle,
2859 const char *requestUri,
2860 const OCDevAddr *destination,
2862 OCConnectivityType connectivityType,
2863 OCQualityOfService qos,
2864 OCCallbackData *cbData,
2865 OCHeaderOption *options,
2868 OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
2869 connectivityType, qos, cbData, options, numOptions);
2871 // This is the owner of the payload object, so we free it
2872 OCPayloadDestroy(payload);
2877 * Discover or Perform requests on a specified resource
2879 OCStackResult OCDoRequest(OCDoHandle *handle,
2881 const char *requestUri,
2882 const OCDevAddr *destination,
2884 OCConnectivityType connectivityType,
2885 OCQualityOfService qos,
2886 OCCallbackData *cbData,
2887 OCHeaderOption *options,
2890 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2891 OIC_TRACE_BEGIN(%s:OCDoRequest, TAG);
2893 // Validate input parameters
2894 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2895 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2897 OCStackResult result = OC_STACK_ERROR;
2898 CAResult_t caResult;
2899 CAToken_t token = NULL;
2900 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2901 ClientCB *clientCB = NULL;
2902 OCDoHandle resHandle = NULL;
2903 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2904 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2906 OCTransportAdapter adapter;
2907 OCTransportFlags flags;
2908 // the request contents are put here
2909 CARequestInfo_t requestInfo = {.method = CA_GET};
2910 // requestUri will be parsed into the following three variables
2911 OCDevAddr *devAddr = NULL;
2912 char *resourceUri = NULL;
2913 char *resourceType = NULL;
2916 * Support original behavior with address on resourceUri argument.
2918 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2919 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2923 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2924 if (result != OC_STACK_OK)
2926 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2930 else if (!checkProxyUri(options, numOptions))
2932 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2939 case OC_REST_OBSERVE:
2940 case OC_REST_OBSERVE_ALL:
2941 requestInfo.method = CA_GET;
2944 requestInfo.method = CA_PUT;
2947 requestInfo.method = CA_POST;
2949 case OC_REST_DELETE:
2950 requestInfo.method = CA_DELETE;
2952 case OC_REST_DISCOVER:
2953 #ifdef WITH_PRESENCE
2954 case OC_REST_PRESENCE:
2956 if (destination || devAddr)
2958 requestInfo.isMulticast = false;
2962 tmpDevAddr.adapter = adapter;
2963 tmpDevAddr.flags = flags;
2964 destination = &tmpDevAddr;
2965 requestInfo.isMulticast = true;
2968 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
2969 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
2970 // replacing method type with GET.
2971 requestInfo.method = CA_GET;
2974 result = OC_STACK_INVALID_METHOD;
2978 if (!devAddr && !destination)
2980 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2981 result = OC_STACK_INVALID_PARAM;
2985 /* If not original behavior, use destination argument */
2986 if (destination && !devAddr)
2988 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2991 result = OC_STACK_NO_MEMORY;
2994 OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
2995 *devAddr = *destination;
3000 OIC_LOG_V(INFO_PRIVATE, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
3001 if (!requestInfo.isMulticast)
3003 OIC_LOG_V(DEBUG, TAG, "remoteAddr of devAddr : [%s]:[%d]",
3004 devAddr->addr, devAddr->port);
3008 resHandle = GenerateInvocationHandle();
3011 result = OC_STACK_NO_MEMORY;
3015 caResult = CAGenerateToken(&token, tokenLength);
3016 if (caResult != CA_STATUS_OK)
3018 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3019 result= OC_STACK_ERROR;
3023 // fill in request data
3024 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3025 requestInfo.info.token = token;
3026 requestInfo.info.tokenLength = tokenLength;
3028 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3030 result = CreateObserveHeaderOption (&(requestInfo.info.options),
3031 options, numOptions, OC_OBSERVE_REGISTER);
3032 if (result != OC_STACK_OK)
3036 requestInfo.info.numOptions = numOptions + 1;
3040 requestInfo.info.numOptions = numOptions;
3041 requestInfo.info.options =
3042 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3043 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3044 numOptions * sizeof(CAHeaderOption_t));
3047 CopyDevAddrToEndpoint(devAddr, &endpoint);
3052 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3055 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3058 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3062 requestInfo.info.payload = NULL;
3063 requestInfo.info.payloadSize = 0;
3064 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3067 // prepare for response
3068 #ifdef WITH_PRESENCE
3069 if (method == OC_REST_PRESENCE)
3071 char *presenceUri = NULL;
3072 result = OCPreparePresence(&endpoint, &presenceUri,
3073 requestInfo.isMulticast);
3074 if (OC_STACK_OK != result)
3079 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3080 // Presence notification will form a canonical uri to
3081 // look for callbacks into the application.
3084 OICFree(resourceUri);
3086 resourceUri = presenceUri;
3090 // update resourceUri onto requestInfo after check presence uri
3091 requestInfo.info.resourceUri = resourceUri;
3093 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3094 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3095 method, devAddr, resourceUri, resourceType, ttl);
3096 if (OC_STACK_OK != result)
3101 devAddr = NULL; // Client CB list entry now owns it
3102 resourceUri = NULL; // Client CB list entry now owns it
3103 resourceType = NULL; // Client CB list entry now owns it
3105 #ifdef WITH_PRESENCE
3106 if (method == OC_REST_PRESENCE)
3108 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3112 *handle = resHandle;
3120 result = OCSendRequest(&endpoint, &requestInfo);
3121 if (OC_STACK_OK != result)
3128 *handle = resHandle;
3132 if (result != OC_STACK_OK)
3134 OIC_LOG(ERROR, TAG, "OCDoResource error");
3135 FindAndDeleteClientCB(clientCB);
3136 CADestroyToken(token);
3144 OICFree(requestInfo.info.payload);
3146 OICFree(resourceUri);
3147 OICFree(resourceType);
3148 OICFree(requestInfo.info.options);
3153 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3157 * This ftn is implemented one of two ways in the case of observation:
3159 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3160 * Remove the callback associated on client side.
3161 * When the next notification comes in from server,
3162 * reply with RESET message to server.
3163 * Keep in mind that the server will react to RESET only
3164 * if the last notification was sent as CON
3166 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3167 * and it is associated with an observe request
3168 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3169 * Send CON Observe request to server with
3170 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3171 * Remove the callback associated on client side.
3173 OCStackResult ret = OC_STACK_OK;
3174 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3175 CARequestInfo_t requestInfo = {.method = CA_GET};
3179 return OC_STACK_INVALID_PARAM;
3182 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3185 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3186 return OC_STACK_ERROR;
3189 switch (clientCB->method)
3191 case OC_REST_OBSERVE:
3192 case OC_REST_OBSERVE_ALL:
3194 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3196 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3198 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
3200 FindAndDeleteClientCB(clientCB);
3204 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3206 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3207 requestInfo.info.token = clientCB->token;
3208 requestInfo.info.tokenLength = clientCB->tokenLength;
3210 if (CreateObserveHeaderOption (&(requestInfo.info.options),
3211 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3213 return OC_STACK_ERROR;
3215 requestInfo.info.numOptions = numOptions + 1;
3216 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3219 ret = OCSendRequest(&endpoint, &requestInfo);
3221 if (requestInfo.info.options)
3223 OICFree (requestInfo.info.options);
3225 if (requestInfo.info.resourceUri)
3227 OICFree (requestInfo.info.resourceUri);
3232 case OC_REST_DISCOVER:
3233 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3234 clientCB->requestUri);
3235 FindAndDeleteClientCB(clientCB);
3238 #ifdef WITH_PRESENCE
3239 case OC_REST_PRESENCE:
3240 FindAndDeleteClientCB(clientCB);
3246 case OC_REST_DELETE:
3247 OIC_LOG_V(INFO, TAG, "Cancelling request callback for resource %s",
3248 clientCB->requestUri);
3249 FindAndDeleteClientCB(clientCB);
3253 ret = OC_STACK_INVALID_METHOD;
3261 * @brief Register Persistent storage callback.
3262 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3264 * OC_STACK_OK - No errors; Success
3265 * OC_STACK_INVALID_PARAM - Invalid parameter
3267 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3269 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3270 if(!persistentStorageHandler)
3272 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3273 return OC_STACK_INVALID_PARAM;
3277 if( !persistentStorageHandler->open ||
3278 !persistentStorageHandler->close ||
3279 !persistentStorageHandler->read ||
3280 !persistentStorageHandler->unlink ||
3281 !persistentStorageHandler->write)
3283 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3284 return OC_STACK_INVALID_PARAM;
3287 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3290 #ifdef WITH_PRESENCE
3292 OCStackResult OCProcessPresence()
3294 OCStackResult result = OC_STACK_OK;
3296 // the following line floods the log with messages that are irrelevant
3297 // to most purposes. Uncomment as needed.
3298 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3299 ClientCB* cbNode = NULL;
3300 OCClientResponse clientResponse;
3301 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3303 LL_FOREACH(cbList, cbNode)
3305 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3310 uint32_t now = GetTicks(0);
3311 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3312 cbNode->presence->TTLlevel);
3313 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3315 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3320 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3322 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3323 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3325 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3327 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3329 clientResponse.sequenceNumber = 0;
3330 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3331 clientResponse.devAddr = *cbNode->devAddr;
3332 FixUpClientResponse(&clientResponse);
3333 clientResponse.payload = NULL;
3335 // Increment the TTLLevel (going to a next state), so we don't keep
3336 // sending presence notification to client.
3337 cbNode->presence->TTLlevel++;
3338 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3339 cbNode->presence->TTLlevel);
3341 OIC_LOG(INFO, TAG, "Before calling into application address space for presence timeout");
3342 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3343 OIC_LOG(INFO, TAG, "After calling into application address space for presence timeout");
3345 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3347 FindAndDeleteClientCB(cbNode);
3351 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3356 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3357 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3358 CARequestInfo_t requestInfo = {.method = CA_GET};
3360 OIC_LOG(DEBUG, TAG, "time to test server presence");
3362 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3364 requestData.type = CA_MSG_NONCONFIRM;
3365 requestData.token = cbNode->token;
3366 requestData.tokenLength = cbNode->tokenLength;
3367 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3368 requestInfo.method = CA_GET;
3369 requestInfo.info = requestData;
3371 result = OCSendRequest(&endpoint, &requestInfo);
3372 if (OC_STACK_OK != result)
3377 cbNode->presence->TTLlevel++;
3378 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3381 if (result != OC_STACK_OK)
3383 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3388 #endif // WITH_PRESENCE
3390 OCStackResult OCProcess()
3392 if (stackState == OC_STACK_UNINITIALIZED)
3394 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3395 return OC_STACK_ERROR;
3397 #ifdef WITH_PRESENCE
3398 OCProcessPresence();
3400 CAHandleRequestResponse();
3402 #ifdef ROUTING_GATEWAY
3407 OCProcessKeepAlive();
3412 #ifdef WITH_PRESENCE
3413 OCStackResult OCStartPresence(const uint32_t ttl)
3415 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3416 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3417 OCChangeResourceProperty(
3418 &(((OCResource *)presenceResource.handle)->resourceProperties),
3421 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3423 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3424 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3428 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3429 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3433 presenceResource.presenceTTL = ttl;
3436 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3439 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3441 presenceState = OC_PRESENCE_INITIALIZED;
3443 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3445 CAToken_t caToken = NULL;
3446 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3447 if (caResult != CA_STATUS_OK)
3449 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3450 CADestroyToken(caToken);
3451 return OC_STACK_ERROR;
3454 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3455 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3456 CADestroyToken(caToken);
3459 // Each time OCStartPresence is called
3460 // a different random 32-bit integer number is used
3461 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3463 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3464 OC_PRESENCE_TRIGGER_CREATE);
3467 OCStackResult OCStopPresence()
3469 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3470 OCStackResult result = OC_STACK_ERROR;
3472 if(presenceResource.handle)
3474 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3476 // make resource inactive
3477 result = OCChangeResourceProperty(
3478 &(((OCResource *) presenceResource.handle)->resourceProperties),
3482 if(result != OC_STACK_OK)
3485 "Changing the presence resource properties to ACTIVE not successful");
3489 return SendStopNotification();
3493 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3494 void* callbackParameter)
3496 defaultDeviceHandler = entityHandler;
3497 defaultDeviceHandlerCallbackParameter = callbackParameter;
3502 OCStackResult OCCreateResource(OCResourceHandle *handle,
3503 const char *resourceTypeName,
3504 const char *resourceInterfaceName,
3505 const char *uri, OCEntityHandler entityHandler,
3506 void* callbackParam,
3507 uint8_t resourceProperties)
3510 OCResource *pointer = NULL;
3511 OCStackResult result = OC_STACK_ERROR;
3513 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3515 if(myStackMode == OC_CLIENT)
3517 return OC_STACK_INVALID_PARAM;
3519 // Validate parameters
3520 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3522 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3523 return OC_STACK_INVALID_URI;
3525 // Is it presented during resource discovery?
3526 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3528 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3529 return OC_STACK_INVALID_PARAM;
3532 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3534 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3538 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3540 // Make sure resourceProperties bitmask has allowed properties specified
3541 if (resourceProperties
3542 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3543 OC_EXPLICIT_DISCOVERABLE
3552 OIC_LOG(ERROR, TAG, "Invalid property");
3553 return OC_STACK_INVALID_PARAM;
3556 // If the headResource is NULL, then no resources have been created...
3557 pointer = headResource;
3560 // At least one resources is in the resource list, so we need to search for
3561 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3564 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3566 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3567 return OC_STACK_INVALID_PARAM;
3569 pointer = pointer->next;
3572 // Create the pointer and insert it into the resource list
3573 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3576 result = OC_STACK_NO_MEMORY;
3579 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3581 insertResource(pointer);
3584 pointer->uri = OICStrdup(uri);
3587 result = OC_STACK_NO_MEMORY;
3591 // Set properties. Set OC_ACTIVE
3592 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3595 // Add the resourcetype to the resource
3596 result = BindResourceTypeToResource(pointer, resourceTypeName);
3597 if (result != OC_STACK_OK)
3599 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3603 // Add the resourceinterface to the resource
3604 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3605 if (result != OC_STACK_OK)
3607 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3611 // If an entity handler has been passed, attach it to the newly created
3612 // resource. Otherwise, set the default entity handler.
3615 pointer->entityHandler = entityHandler;
3616 pointer->entityHandlerCallbackParam = callbackParam;
3620 pointer->entityHandler = defaultResourceEHandler;
3621 pointer->entityHandlerCallbackParam = NULL;
3624 // Initialize a pointer indicating child resources in case of collection
3625 pointer->rsrcChildResourcesHead = NULL;
3628 result = OC_STACK_OK;
3630 #ifdef WITH_PRESENCE
3631 if (presenceResource.handle)
3633 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3634 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3638 if (result != OC_STACK_OK)
3640 // Deep delete of resource and other dynamic elements that it contains
3641 deleteResource(pointer);
3646 OCStackResult OCBindResource(
3647 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3649 OCResource *resource = NULL;
3650 OCChildResource *tempChildResource = NULL;
3651 OCChildResource *newChildResource = NULL;
3653 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3655 // Validate parameters
3656 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3657 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3658 // Container cannot contain itself
3659 if (collectionHandle == resourceHandle)
3661 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3662 return OC_STACK_INVALID_PARAM;
3665 // Use the handle to find the resource in the resource linked list
3666 resource = findResource((OCResource *) collectionHandle);
3669 OIC_LOG(ERROR, TAG, "Collection handle not found");
3670 return OC_STACK_INVALID_PARAM;
3673 // Look for an open slot to add add the child resource.
3674 // If found, add it and return success
3676 tempChildResource = resource->rsrcChildResourcesHead;
3678 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3680 // TODO: what if one of child resource was deregistered without unbinding?
3681 tempChildResource = tempChildResource->next;
3684 // Do memory allocation for child resource
3685 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3686 if(!newChildResource)
3688 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3689 return OC_STACK_ERROR;
3692 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3693 newChildResource->next = NULL;
3695 if(!resource->rsrcChildResourcesHead)
3697 resource->rsrcChildResourcesHead = newChildResource;
3700 tempChildResource->next = newChildResource;
3703 OIC_LOG(INFO, TAG, "resource bound");
3705 #ifdef WITH_PRESENCE
3706 if (presenceResource.handle)
3708 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3709 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3710 OC_PRESENCE_TRIGGER_CHANGE);
3717 OCStackResult OCUnBindResource(
3718 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3720 OCResource *resource = NULL;
3721 OCChildResource *tempChildResource = NULL;
3722 OCChildResource *tempLastChildResource = NULL;
3724 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3726 // Validate parameters
3727 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3728 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3729 // Container cannot contain itself
3730 if (collectionHandle == resourceHandle)
3732 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3733 return OC_STACK_INVALID_PARAM;
3736 // Use the handle to find the resource in the resource linked list
3737 resource = findResource((OCResource *) collectionHandle);
3740 OIC_LOG(ERROR, TAG, "Collection handle not found");
3741 return OC_STACK_INVALID_PARAM;
3744 // Look for an open slot to add add the child resource.
3745 // If found, add it and return success
3746 if(!resource->rsrcChildResourcesHead)
3748 OIC_LOG(INFO, TAG, "resource not found in collection");
3750 // Unable to add resourceHandle, so return error
3751 return OC_STACK_ERROR;
3755 tempChildResource = resource->rsrcChildResourcesHead;
3757 while (tempChildResource)
3759 if(tempChildResource->rsrcResource == resourceHandle)
3761 // if resource going to be unbinded is the head one.
3762 if( tempChildResource == resource->rsrcChildResourcesHead )
3764 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3765 OICFree(resource->rsrcChildResourcesHead);
3766 resource->rsrcChildResourcesHead = temp;
3771 OCChildResource *temp = tempChildResource->next;
3772 OICFree(tempChildResource);
3773 if (tempLastChildResource)
3775 tempLastChildResource->next = temp;
3780 OIC_LOG(INFO, TAG, "resource unbound");
3782 // Send notification when resource is unbounded successfully.
3783 #ifdef WITH_PRESENCE
3784 if (presenceResource.handle)
3786 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3787 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3788 OC_PRESENCE_TRIGGER_CHANGE);
3791 tempChildResource = NULL;
3792 tempLastChildResource = NULL;
3798 tempLastChildResource = tempChildResource;
3799 tempChildResource = tempChildResource->next;
3802 OIC_LOG(INFO, TAG, "resource not found in collection");
3804 tempChildResource = NULL;
3805 tempLastChildResource = NULL;
3807 // Unable to add resourceHandle, so return error
3808 return OC_STACK_ERROR;
3811 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3813 if (!resourceItemName)
3817 // Per RFC 6690 only registered values must follow the first rule below.
3818 // At this point in time the only values registered begin with "core", and
3819 // all other values are specified as opaque strings where multiple values
3820 // are separated by a space.
3821 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3823 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3825 if (resourceItemName[index] != '.'
3826 && resourceItemName[index] != '-'
3827 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3828 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3836 for (size_t index = 0; resourceItemName[index]; ++index)
3838 if (resourceItemName[index] == ' '
3839 || resourceItemName[index] == '\t'
3840 || resourceItemName[index] == '\r'
3841 || resourceItemName[index] == '\n')
3851 OCStackResult BindResourceTypeToResource(OCResource* resource,
3852 const char *resourceTypeName)
3854 OCResourceType *pointer = NULL;
3856 OCStackResult result = OC_STACK_ERROR;
3858 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3860 if (!ValidateResourceTypeInterface(resourceTypeName))
3862 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3863 return OC_STACK_INVALID_PARAM;
3866 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3869 result = OC_STACK_NO_MEMORY;
3873 str = OICStrdup(resourceTypeName);
3876 result = OC_STACK_NO_MEMORY;
3879 pointer->resourcetypename = str;
3880 pointer->next = NULL;
3882 insertResourceType(resource, pointer);
3883 result = OC_STACK_OK;
3886 if (result != OC_STACK_OK)
3895 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3896 const char *resourceInterfaceName)
3898 OCResourceInterface *pointer = NULL;
3900 OCStackResult result = OC_STACK_ERROR;
3902 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3904 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3906 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3907 return OC_STACK_INVALID_PARAM;
3910 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3912 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3915 result = OC_STACK_NO_MEMORY;
3919 str = OICStrdup(resourceInterfaceName);
3922 result = OC_STACK_NO_MEMORY;
3925 pointer->name = str;
3927 // Bind the resourceinterface to the resource
3928 insertResourceInterface(resource, pointer);
3930 result = OC_STACK_OK;
3933 if (result != OC_STACK_OK)
3942 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3943 const char *resourceTypeName)
3946 OCStackResult result = OC_STACK_ERROR;
3947 OCResource *resource = NULL;
3949 resource = findResource((OCResource *) handle);
3952 OIC_LOG(ERROR, TAG, "Resource not found");
3953 return OC_STACK_ERROR;
3956 result = BindResourceTypeToResource(resource, resourceTypeName);
3958 #ifdef WITH_PRESENCE
3959 if(presenceResource.handle)
3961 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3962 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3969 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3970 const char *resourceInterfaceName)
3973 OCStackResult result = OC_STACK_ERROR;
3974 OCResource *resource = NULL;
3976 resource = findResource((OCResource *) handle);
3979 OIC_LOG(ERROR, TAG, "Resource not found");
3980 return OC_STACK_ERROR;
3983 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3985 #ifdef WITH_PRESENCE
3986 if (presenceResource.handle)
3988 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3989 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3996 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3998 OCResource *pointer = headResource;
4000 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
4004 *numResources = *numResources + 1;
4005 pointer = pointer->next;
4010 OCResourceHandle OCGetResourceHandle(uint8_t index)
4012 OCResource *pointer = headResource;
4014 for( uint8_t i = 0; i < index && pointer; ++i)
4016 pointer = pointer->next;
4018 return (OCResourceHandle) pointer;
4021 OCStackResult OCDeleteResource(OCResourceHandle handle)
4025 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4026 return OC_STACK_INVALID_PARAM;
4029 OCResource *resource = findResource((OCResource *) handle);
4030 if (resource == NULL)
4032 OIC_LOG(ERROR, TAG, "Resource not found");
4033 return OC_STACK_NO_RESOURCE;
4036 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4038 OIC_LOG(ERROR, TAG, "Error deleting resource");
4039 return OC_STACK_ERROR;
4045 const char *OCGetResourceUri(OCResourceHandle handle)
4047 OCResource *resource = NULL;
4049 resource = findResource((OCResource *) handle);
4052 return resource->uri;
4054 return (const char *) NULL;
4057 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4059 OCResource *resource = NULL;
4061 resource = findResource((OCResource *) handle);
4064 return resource->resourceProperties;
4066 return (OCResourceProperty)-1;
4069 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4070 uint8_t *numResourceTypes)
4072 OCResource *resource = NULL;
4073 OCResourceType *pointer = NULL;
4075 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4076 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4078 *numResourceTypes = 0;
4080 resource = findResource((OCResource *) handle);
4083 pointer = resource->rsrcType;
4086 *numResourceTypes = *numResourceTypes + 1;
4087 pointer = pointer->next;
4093 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4095 OCResourceType *resourceType = NULL;
4097 resourceType = findResourceTypeAtIndex(handle, index);
4100 return resourceType->resourcetypename;
4102 return (const char *) NULL;
4105 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4106 uint8_t *numResourceInterfaces)
4108 OCResourceInterface *pointer = NULL;
4109 OCResource *resource = NULL;
4111 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4112 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4114 *numResourceInterfaces = 0;
4115 resource = findResource((OCResource *) handle);
4118 pointer = resource->rsrcInterface;
4121 *numResourceInterfaces = *numResourceInterfaces + 1;
4122 pointer = pointer->next;
4128 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4130 OCResourceInterface *resourceInterface = NULL;
4132 resourceInterface = findResourceInterfaceAtIndex(handle, index);
4133 if (resourceInterface)
4135 return resourceInterface->name;
4137 return (const char *) NULL;
4140 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4143 OCResource *resource = NULL;
4144 OCChildResource *tempChildResource = NULL;
4147 resource = findResource((OCResource *) collectionHandle);
4153 tempChildResource = resource->rsrcChildResourcesHead;
4155 while(tempChildResource)
4159 return tempChildResource->rsrcResource;
4162 tempChildResource = tempChildResource->next;
4165 // In this case, the number of resource handles in the collection exceeds the index
4166 tempChildResource = NULL;
4170 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4171 OCEntityHandler entityHandler,
4172 void* callbackParam)
4174 OCResource *resource = NULL;
4176 // Validate parameters
4177 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4179 // Use the handle to find the resource in the resource linked list
4180 resource = findResource((OCResource *)handle);
4183 OIC_LOG(ERROR, TAG, "Resource not found");
4184 return OC_STACK_ERROR;
4188 resource->entityHandler = entityHandler;
4189 resource->entityHandlerCallbackParam = callbackParam;
4191 #ifdef WITH_PRESENCE
4192 if (presenceResource.handle)
4194 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4195 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4202 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4204 OCResource *resource = NULL;
4206 resource = findResource((OCResource *)handle);
4209 OIC_LOG(ERROR, TAG, "Resource not found");
4214 return resource->entityHandler;
4217 void incrementSequenceNumber(OCResource * resPtr)
4219 // Increment the sequence number
4220 resPtr->sequenceNum += 1;
4221 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4223 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4228 #ifdef WITH_PRESENCE
4229 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4230 OCPresenceTrigger trigger)
4232 OIC_LOG(INFO, TAG, "SendPresenceNotification");
4233 OCResource *resPtr = NULL;
4234 OCStackResult result = OC_STACK_ERROR;
4235 OCMethod method = OC_REST_PRESENCE;
4236 uint32_t maxAge = 0;
4237 resPtr = findResource((OCResource *) presenceResource.handle);
4240 return OC_STACK_NO_RESOURCE;
4243 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4245 maxAge = presenceResource.presenceTTL;
4247 result = SendAllObserverNotification(method, resPtr, maxAge,
4248 trigger, resourceType, OC_LOW_QOS);
4254 OCStackResult SendStopNotification()
4256 OIC_LOG(INFO, TAG, "SendStopNotification");
4257 OCResource *resPtr = NULL;
4258 OCStackResult result = OC_STACK_ERROR;
4259 OCMethod method = OC_REST_PRESENCE;
4260 resPtr = findResource((OCResource *) presenceResource.handle);
4263 return OC_STACK_NO_RESOURCE;
4266 // maxAge is 0. ResourceType is NULL.
4267 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4273 #endif // WITH_PRESENCE
4274 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4276 OCResource *resPtr = NULL;
4277 OCStackResult result = OC_STACK_ERROR;
4278 OCMethod method = OC_REST_NOMETHOD;
4279 uint32_t maxAge = 0;
4281 OIC_LOG(INFO, TAG, "Notifying all observers");
4282 #ifdef WITH_PRESENCE
4283 if(handle == presenceResource.handle)
4287 #endif // WITH_PRESENCE
4288 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4290 // Verify that the resource exists
4291 resPtr = findResource ((OCResource *) handle);
4294 return OC_STACK_NO_RESOURCE;
4298 //only increment in the case of regular observing (not presence)
4299 incrementSequenceNumber(resPtr);
4300 method = OC_REST_OBSERVE;
4301 maxAge = MAX_OBSERVE_AGE;
4302 #ifdef WITH_PRESENCE
4303 result = SendAllObserverNotification (method, resPtr, maxAge,
4304 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4306 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4313 OCNotifyListOfObservers (OCResourceHandle handle,
4314 OCObservationId *obsIdList,
4315 uint8_t numberOfIds,
4316 const OCRepPayload *payload,
4317 OCQualityOfService qos)
4319 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4321 OCResource *resPtr = NULL;
4322 //TODO: we should allow the server to define this
4323 uint32_t maxAge = MAX_OBSERVE_AGE;
4325 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4326 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4327 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4329 resPtr = findResource ((OCResource *) handle);
4330 if (NULL == resPtr || myStackMode == OC_CLIENT)
4332 return OC_STACK_NO_RESOURCE;
4336 incrementSequenceNumber(resPtr);
4338 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4339 payload, maxAge, qos));
4342 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4344 OIC_TRACE_BEGIN(%s:OCDoResponse, TAG);
4345 OCStackResult result = OC_STACK_ERROR;
4346 OCServerRequest *serverRequest = NULL;
4348 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4350 // Validate input parameters
4351 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4352 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4355 // Get pointer to request info
4356 serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
4359 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4360 result = serverRequest->ehResponseHandler(ehResponse);
4367 //#ifdef DIRECT_PAIRING
4368 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4370 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4371 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4373 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4377 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4380 const OCDPDev_t* OCGetDirectPairedDevices()
4382 return (const OCDPDev_t*)DPGetPairedDevices();
4385 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4386 OCDirectPairingCB resultCallback)
4388 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4389 if(NULL == peer || NULL == pinNumber)
4391 OIC_LOG(ERROR, TAG, "Invalid parameters");
4392 return OC_STACK_INVALID_PARAM;
4394 if (NULL == resultCallback)
4396 OIC_LOG(ERROR, TAG, "Invalid callback");
4397 return OC_STACK_INVALID_CALLBACK;
4400 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4401 pinNumber, (OCDirectPairingResultCB)resultCallback);
4403 //#endif // DIRECT_PAIRING
4405 //-----------------------------------------------------------------------------
4406 // Private internal function definitions
4407 //-----------------------------------------------------------------------------
4408 static OCDoHandle GenerateInvocationHandle()
4410 OCDoHandle handle = NULL;
4411 // Generate token here, it will be deleted when the transaction is deleted
4412 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4415 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4421 #ifdef WITH_PRESENCE
4422 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4423 OCResourceProperty resourceProperties, uint8_t enable)
4427 return OC_STACK_INVALID_PARAM;
4429 if (resourceProperties
4430 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4432 OIC_LOG(ERROR, TAG, "Invalid property");
4433 return OC_STACK_INVALID_PARAM;
4437 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4441 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4447 OCStackResult initResources()
4449 OCStackResult result = OC_STACK_OK;
4451 headResource = NULL;
4452 tailResource = NULL;
4453 // Init Virtual Resources
4454 #ifdef WITH_PRESENCE
4455 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4457 result = OCCreateResource(&presenceResource.handle,
4458 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4460 OC_RSRVD_PRESENCE_URI,
4464 //make resource inactive
4465 result = OCChangeResourceProperty(
4466 &(((OCResource *) presenceResource.handle)->resourceProperties),
4469 #ifndef WITH_ARDUINO
4470 if (result == OC_STACK_OK)
4472 result = SRMInitSecureResources();
4476 if(result == OC_STACK_OK)
4478 CreateResetProfile();
4479 result = OCCreateResource(&deviceResource,
4480 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4481 OC_RSRVD_INTERFACE_DEFAULT,
4482 OC_RSRVD_DEVICE_URI,
4486 if(result == OC_STACK_OK)
4488 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4489 OC_RSRVD_INTERFACE_READ);
4493 if(result == OC_STACK_OK)
4495 result = OCCreateResource(&platformResource,
4496 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4497 OC_RSRVD_INTERFACE_DEFAULT,
4498 OC_RSRVD_PLATFORM_URI,
4502 if(result == OC_STACK_OK)
4504 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4505 OC_RSRVD_INTERFACE_READ);
4512 void insertResource(OCResource *resource)
4516 headResource = resource;
4517 tailResource = resource;
4521 tailResource->next = resource;
4522 tailResource = resource;
4524 resource->next = NULL;
4527 OCResource *findResource(OCResource *resource)
4529 OCResource *pointer = headResource;
4533 if (pointer == resource)
4537 pointer = pointer->next;
4542 void deleteAllResources()
4544 OCResource *pointer = headResource;
4545 OCResource *temp = NULL;
4549 temp = pointer->next;
4550 #ifdef WITH_PRESENCE
4551 if (pointer != (OCResource *) presenceResource.handle)
4553 #endif // WITH_PRESENCE
4554 deleteResource(pointer);
4555 #ifdef WITH_PRESENCE
4557 #endif // WITH_PRESENCE
4560 memset(&platformResource, 0, sizeof(platformResource));
4561 memset(&deviceResource, 0, sizeof(deviceResource));
4563 memset(&brokerResource, 0, sizeof(brokerResource));
4566 SRMDeInitSecureResources();
4568 #ifdef WITH_PRESENCE
4569 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4570 // presence notification attributed to their deletion to be processed.
4571 deleteResource((OCResource *) presenceResource.handle);
4572 memset(&presenceResource, 0, sizeof(presenceResource));
4573 #endif // WITH_PRESENCE
4576 OCStackResult deleteResource(OCResource *resource)
4578 OCResource *prev = NULL;
4579 OCResource *temp = NULL;
4582 OIC_LOG(DEBUG,TAG,"resource is NULL");
4583 return OC_STACK_INVALID_PARAM;
4586 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4588 temp = headResource;
4591 if (temp == resource)
4593 // Invalidate all Resource Properties.
4594 resource->resourceProperties = (OCResourceProperty) 0;
4595 #ifdef WITH_PRESENCE
4596 if(resource != (OCResource *) presenceResource.handle)
4598 #endif // WITH_PRESENCE
4599 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4600 #ifdef WITH_PRESENCE
4603 if(presenceResource.handle)
4605 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4606 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4609 // Only resource in list.
4610 if (temp == headResource && temp == tailResource)
4612 headResource = NULL;
4613 tailResource = NULL;
4616 else if (temp == headResource)
4618 headResource = temp->next;
4621 else if (temp == tailResource && prev)
4623 tailResource = prev;
4624 tailResource->next = NULL;
4628 prev->next = temp->next;
4631 deleteResourceElements(temp);
4642 return OC_STACK_ERROR;
4645 void deleteResourceElements(OCResource *resource)
4654 OICFree(resource->uri);
4655 resource->uri = NULL;
4657 if (resource->rsrcType)
4659 deleteResourceType(resource->rsrcType);
4660 resource->rsrcType = NULL;
4662 if (resource->rsrcInterface)
4664 deleteResourceInterface(resource->rsrcInterface);
4665 resource->rsrcInterface = NULL;
4667 if (resource->rsrcChildResourcesHead)
4669 deleteResourceChild(resource->rsrcChildResourcesHead);
4670 resource->rsrcChildResourcesHead = NULL;
4672 if (resource->rsrcAttributes)
4674 OCDeleteResourceAttributes(resource->rsrcAttributes);
4675 resource->rsrcAttributes = NULL;
4680 void deleteResourceType(OCResourceType *resourceType)
4682 OCResourceType *next = NULL;
4684 for (OCResourceType *pointer = resourceType; pointer; pointer = next)
4686 next = pointer->next ? pointer->next : NULL;
4687 if (pointer->resourcetypename)
4689 OICFree(pointer->resourcetypename);
4690 pointer->resourcetypename = NULL;
4696 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4698 OCResourceInterface *next = NULL;
4699 for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
4701 next = pointer->next ? pointer->next : NULL;
4704 OICFree(pointer->name);
4705 pointer->name = NULL;
4711 void deleteResourceChild(OCChildResource *resourceChild)
4713 OCChildResource *next = NULL;
4714 for (OCChildResource *pointer = resourceChild; pointer; pointer = next)
4716 next = pointer->next ? pointer->next : NULL;
4717 if (pointer->rsrcResource)
4719 deleteResourceElements(pointer->rsrcResource);
4720 pointer->rsrcResource = NULL;
4726 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
4728 OCAttribute *next = NULL;
4729 for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
4731 next = pointer->next ? pointer->next : NULL;
4732 if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
4734 OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
4735 pointer->attrValue = NULL;
4737 else if (pointer->attrValue)
4739 OICFree(pointer->attrValue);
4740 pointer->attrValue = NULL;
4742 if (pointer->attrName)
4744 OICFree(pointer->attrName);
4745 pointer->attrName = NULL;
4751 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4753 OCResourceType *pointer = NULL;
4754 OCResourceType *previous = NULL;
4755 if (!resource || !resourceType)
4759 // resource type list is empty.
4760 else if (!resource->rsrcType)
4762 resource->rsrcType = resourceType;
4766 pointer = resource->rsrcType;
4770 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4772 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4773 OICFree(resourceType->resourcetypename);
4774 OICFree(resourceType);
4778 pointer = pointer->next;
4783 previous->next = resourceType;
4786 resourceType->next = NULL;
4788 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4791 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4793 OCResource *resource = NULL;
4794 OCResourceType *pointer = NULL;
4796 // Find the specified resource
4797 resource = findResource((OCResource *) handle);
4803 // Make sure a resource has a resourcetype
4804 if (!resource->rsrcType)
4809 // Iterate through the list
4810 pointer = resource->rsrcType;
4811 for(uint8_t i = 0; i< index && pointer; ++i)
4813 pointer = pointer->next;
4818 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4820 if(resourceTypeList && resourceTypeName)
4822 OCResourceType * rtPointer = resourceTypeList;
4823 while(resourceTypeName && rtPointer)
4825 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4826 if(rtPointer->resourcetypename &&
4827 strcmp(resourceTypeName, (const char *)
4828 (rtPointer->resourcetypename)) == 0)
4832 rtPointer = rtPointer->next;
4840 * Insert a new interface into interface linked list only if not already present.
4841 * If alredy present, 2nd arg is free'd.
4842 * Default interface will always be first if present.
4844 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4846 OCResourceInterface *pointer = NULL;
4847 OCResourceInterface *previous = NULL;
4849 newInterface->next = NULL;
4851 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4853 if (!*firstInterface)
4855 // If first interface is not oic.if.baseline, by default add it as first interface type.
4856 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4858 *firstInterface = newInterface;
4862 OCStackResult result = BindResourceInterfaceToResource(resource,
4863 OC_RSRVD_INTERFACE_DEFAULT);
4864 if (result != OC_STACK_OK)
4866 OICFree(newInterface->name);
4867 OICFree(newInterface);
4870 if (*firstInterface)
4872 (*firstInterface)->next = newInterface;
4876 // If once add oic.if.baseline, later too below code take care of freeing memory.
4877 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4879 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4881 OICFree(newInterface->name);
4882 OICFree(newInterface);
4885 // This code will not hit anymore, keeping
4888 newInterface->next = *firstInterface;
4889 *firstInterface = newInterface;
4894 pointer = *firstInterface;
4897 if (strcmp(newInterface->name, pointer->name) == 0)
4899 OICFree(newInterface->name);
4900 OICFree(newInterface);
4904 pointer = pointer->next;
4909 previous->next = newInterface;
4914 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4917 OCResource *resource = NULL;
4918 OCResourceInterface *pointer = NULL;
4920 // Find the specified resource
4921 resource = findResource((OCResource *) handle);
4927 // Make sure a resource has a resourceinterface
4928 if (!resource->rsrcInterface)
4933 // Iterate through the list
4934 pointer = resource->rsrcInterface;
4936 for (uint8_t i = 0; i < index && pointer; ++i)
4938 pointer = pointer->next;
4944 * This function splits the uri using the '?' delimiter.
4945 * "uriWithoutQuery" is the block of characters between the beginning
4946 * till the delimiter or '\0' which ever comes first.
4947 * "query" is whatever is to the right of the delimiter if present.
4948 * No delimiter sets the query to NULL.
4949 * If either are present, they will be malloc'ed into the params 2, 3.
4950 * The first param, *uri is left untouched.
4952 * NOTE: This function does not account for whitespace at the end of the uri NOR
4953 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4954 * part of the query.
4956 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4960 return OC_STACK_INVALID_URI;
4962 if(!query || !uriWithoutQuery)
4964 return OC_STACK_INVALID_PARAM;
4968 *uriWithoutQuery = NULL;
4970 size_t uriWithoutQueryLen = 0;
4971 size_t queryLen = 0;
4972 size_t uriLen = strlen(uri);
4974 char *pointerToDelimiter = strstr(uri, "?");
4976 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4977 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4979 if (uriWithoutQueryLen)
4981 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4982 if (!*uriWithoutQuery)
4986 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4990 *query = (char *) OICCalloc(queryLen + 1, 1);
4993 OICFree(*uriWithoutQuery);
4994 *uriWithoutQuery = NULL;
4997 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5003 return OC_STACK_NO_MEMORY;
5006 const char* OCGetServerInstanceIDString(void)
5008 static char sidStr[UUID_STRING_SIZE];
5010 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5012 OIC_LOG(FATAL, TAG, "GetDoxmDeviceID failed!");
5016 if (OCConvertUuidToString(sid.id, sidStr) != RAND_UUID_OK)
5018 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5025 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5027 OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5028 CAResult_t retResult = CA_STATUS_FAILED;
5029 CAResult_t caResult = CA_STATUS_OK;
5031 CATransportAdapter_t connTypes[] = {
5033 CA_ADAPTER_RFCOMM_BTEDR,
5034 CA_ADAPTER_GATT_BTLE,
5037 ,CA_ADAPTER_REMOTE_ACCESS
5044 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5046 for(int i = 0; i < numConnTypes; i++)
5048 // If CA status is not initialized, CASelectNetwork() will not be called.
5049 if (caResult != CA_STATUS_NOT_INITIALIZED)
5051 if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5053 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5054 caResult = CASelectNetwork(connTypes[i]);
5055 if (caResult == CA_STATUS_OK)
5057 retResult = CA_STATUS_OK;
5062 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5067 if (retResult != CA_STATUS_OK)
5069 return caResult; // Returns error of appropriate transport that failed fatally.
5075 OCStackResult CAResultToOCResult(CAResult_t caResult)
5081 case CA_STATUS_INVALID_PARAM:
5082 return OC_STACK_INVALID_PARAM;
5083 case CA_ADAPTER_NOT_ENABLED:
5084 return OC_STACK_ADAPTER_NOT_ENABLED;
5085 case CA_SERVER_STARTED_ALREADY:
5087 case CA_SERVER_NOT_STARTED:
5088 return OC_STACK_ERROR;
5089 case CA_DESTINATION_NOT_REACHABLE:
5090 return OC_STACK_COMM_ERROR;
5091 case CA_SOCKET_OPERATION_FAILED:
5092 return OC_STACK_COMM_ERROR;
5093 case CA_SEND_FAILED:
5094 return OC_STACK_COMM_ERROR;
5095 case CA_RECEIVE_FAILED:
5096 return OC_STACK_COMM_ERROR;
5097 case CA_MEMORY_ALLOC_FAILED:
5098 return OC_STACK_NO_MEMORY;
5099 case CA_REQUEST_TIMEOUT:
5100 return OC_STACK_TIMEOUT;
5101 case CA_DESTINATION_DISCONNECTED:
5102 return OC_STACK_COMM_ERROR;
5103 case CA_STATUS_FAILED:
5104 return OC_STACK_ERROR;
5105 case CA_NOT_SUPPORTED:
5106 return OC_STACK_NOTIMPL;
5108 return OC_STACK_ERROR;
5112 bool OCResultToSuccess(OCStackResult ocResult)
5117 case OC_STACK_RESOURCE_CREATED:
5118 case OC_STACK_RESOURCE_DELETED:
5119 case OC_STACK_CONTINUE:
5120 case OC_STACK_RESOURCE_CHANGED:
5121 case OC_STACK_SLOW_RESOURCE:
5129 OCStackResult OCSetProxyURI(const char *uri)
5131 return CAResultToOCResult(CASetProxyUri(uri));
5135 #if defined(RD_CLIENT) || defined(RD_SERVER)
5136 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5138 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5140 OCResource *resource = NULL;
5142 resource = findResource((OCResource *) handle);
5145 OIC_LOG(ERROR, TAG, "Resource not found");
5146 return OC_STACK_ERROR;
5149 resource->ins = ins;
5155 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5156 const OCClientResponse *response)
5158 // Validate input parameters
5159 VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5160 VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5162 char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5165 return OC_STACK_NO_MEMORY;
5167 strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5169 if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5171 OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5173 char rdPubUri[MAX_URI_LENGTH] = { 0 };
5174 snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5175 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5177 if (strcmp(rdPubUri, targetUri) == 0)
5179 // Update resource unique id in stack.
5182 if (response->payload)
5184 OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5185 OCRepPayload **links = NULL;
5186 size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5187 if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5188 &links, dimensions))
5191 for (; i < dimensions[0]; i++)
5194 if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5196 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5198 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5200 OCBindResourceInsToResource(handle, ins);
5209 size_t count = calcDimTotal(dimensions);
5210 for (size_t k = 0; k < count; k++)
5212 OCRepPayloadDestroy(links[k]);
5220 else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5222 OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5224 uint8_t numResources = 0;
5225 OCGetNumberOfResources(&numResources);
5227 char *ins = strstr(targetUri, OC_RSRVD_INS);
5230 for (uint8_t i = 0; i < numResources; i++)
5232 OCResourceHandle resHandle = OCGetResourceHandle(i);
5235 OCBindResourceInsToResource(resHandle, 0);
5241 const char *token = "&";
5242 char *iterTokenPtr = NULL;
5243 char *start = strtok_r(targetUri, token, &iterTokenPtr);
5245 while (start != NULL)
5247 char *query = start;
5248 query = strstr(query, OC_RSRVD_INS);
5251 int64_t queryIns = atoi(query + 4);
5252 for (uint8_t i = 0; i < numResources; i++)
5254 OCResourceHandle resHandle = OCGetResourceHandle(i);
5258 OCGetResourceIns(resHandle, &resIns);
5259 if (queryIns && queryIns == resIns)
5261 OCBindResourceInsToResource(resHandle, 0);
5267 start = strtok_r(NULL, token, &iterTokenPtr);
5276 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5280 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5284 OCResource *pointer = headResource;
5288 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5290 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5293 pointer = pointer->next;
5298 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t *ins)
5300 OCResource *resource = NULL;
5302 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5303 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5305 resource = findResource((OCResource *) handle);
5308 *ins = resource->ins;
5311 return OC_STACK_ERROR;
5315 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5316 void* optionData, size_t optionDataLength)
5320 OIC_LOG (INFO, TAG, "Header options are NULL");
5321 return OC_STACK_INVALID_PARAM;
5326 OIC_LOG (INFO, TAG, "optionData are NULL");
5327 return OC_STACK_INVALID_PARAM;
5332 OIC_LOG (INFO, TAG, "numOptions is NULL");
5333 return OC_STACK_INVALID_PARAM;
5336 if (*numOptions >= MAX_HEADER_OPTIONS)
5338 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5339 return OC_STACK_NO_MEMORY;
5342 ocHdrOpt += *numOptions;
5343 ocHdrOpt->protocolID = OC_COAP_ID;
5344 ocHdrOpt->optionID = optionID;
5345 ocHdrOpt->optionLength =
5346 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
5347 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5348 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5354 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5355 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5357 if (!ocHdrOpt || !numOptions)
5359 OIC_LOG (INFO, TAG, "No options present");
5365 OIC_LOG (INFO, TAG, "optionData are NULL");
5366 return OC_STACK_INVALID_PARAM;
5369 if (!receivedDataLength)
5371 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5372 return OC_STACK_INVALID_PARAM;
5375 for (uint8_t i = 0; i < numOptions; i++)
5377 if (ocHdrOpt[i].optionID == optionID)
5379 if (optionDataLength >= ocHdrOpt->optionLength)
5381 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5382 *receivedDataLength = ocHdrOpt->optionLength;
5387 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5388 return OC_STACK_ERROR;
5395 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5397 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5398 if (g_adapterHandler)
5400 g_adapterHandler(adapter, enabled);
5404 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5406 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5407 if (g_connectionHandler)
5409 g_connectionHandler(info, isConnected);
5413 * If the client observes one or more resources over a reliable connection,
5414 * then the CoAP server (or intermediary in the role of the CoAP server)
5415 * MUST remove all entries associated with the client endpoint from the lists
5416 * of observers when the connection is either closed or times out.
5420 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5421 CopyEndpointToDevAddr(info, &devAddr);
5423 // remove observer list with remote device address.
5424 DeleteObserverUsingDevAddr(&devAddr);
5428 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5431 OCStackResult ret = OC_STACK_ERROR;
5433 ret = GetDoxmDeviceID(&oicUuid);
5434 if (OC_STACK_OK == ret)
5436 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5440 OIC_LOG(ERROR, TAG, "Device ID Get error");
5445 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5448 OCStackResult ret = OC_STACK_ERROR;
5450 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5451 for (int i = 0; i < UUID_LENGTH; i++)
5453 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5455 ret = SetDoxmDeviceID(&oicUuid);
5459 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5461 bool isDeviceOwned = true;
5462 OCStackResult ret = OC_STACK_ERROR;
5464 ret = GetDoxmIsOwned(&isDeviceOwned);
5465 if (OC_STACK_OK == ret)
5467 *isOwned = isDeviceOwned;
5471 OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5476 void OCClearCallBackList()
5478 DeleteClientCBList();
5481 void OCClearObserverlist()
5483 DeleteObserverList();
5486 int OCEncrypt(const unsigned char *pt, size_t pt_len,
5487 unsigned char **ct, size_t *ct_len)
5489 #ifndef __SECURE_PSI__
5490 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5493 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5495 return psiEncrypt(pt, pt_len, ct, ct_len);
5496 #endif // __SECURE_PSI__
5499 int OCDecrypt(const unsigned char *ct, size_t ct_len,
5500 unsigned char **pt, size_t *pt_len)
5502 #ifndef __SECURE_PSI__
5503 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5506 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5508 return psiDecrypt(ct, ct_len, pt, pt_len);
5509 #endif // __SECURE_PSI__
5512 OCStackResult OCSetKey(const unsigned char* key)
5514 #ifndef __SECURE_PSI__
5515 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5518 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5520 return psiSetKey(key);
5521 #endif // __SECURE_PSI__
5524 OCStackResult OCGetKey(unsigned char* key)
5526 #ifndef __SECURE_PSI__
5527 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5530 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5532 return psiGetKey(key);
5533 #endif // __SECURE_PSI__
5536 OCStackResult OCSetSecurePSI(const unsigned char *key, const OCPersistentStorage *psPlain,
5537 const OCPersistentStorage *psEnc, const OCPersistentStorage *psRescue)
5539 #ifndef __SECURE_PSI__
5540 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5543 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5545 return setSecurePSI(key, psPlain, psEnc, psRescue);
5546 #endif // __SECURE_PSI__
5549 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5550 static void OtmEventHandler(const char *addr, uint16_t port, const char *uuid, int event)
5552 if (g_otmEventHandler.cb)
5554 g_otmEventHandler.cb(g_otmEventHandler.ctx, addr, port, uuid, event);
5559 * It is already declared in srmutility.h.
5560 * We can't include the header file, because of "redefined VERIFY_NON_NULL"
5562 typedef void (*OicSecOtmEventHandler_t)(const char* addr, uint16_t port,
5563 const char* uuid, int event);
5564 void SetOtmEventHandler(OicSecOtmEventHandler_t otmEventHandler);
5567 OCStackResult OCSetOtmEventHandler(void *ctx, OCOtmEventHandler cb)
5569 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5570 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5572 g_otmEventHandler.cb = cb;
5573 g_otmEventHandler.ctx = ctx;
5575 if (g_otmEventHandler.cb)
5577 OIC_LOG(DEBUG, TAG, "SET OCOtmEventHandler");
5578 SetOtmEventHandler(OtmEventHandler);
5582 OIC_LOG(DEBUG, TAG, "UNSET OCOtmEventHandler");
5583 SetOtmEventHandler(NULL);
5586 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);