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 * Unbind all child resources.
277 * @param resourceChild Specified binded resource head is deleted from parent.
279 static void unbindChildResources(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_TOO_MANY_REQUESTS:
726 ret = OC_STACK_TOO_MANY_REQUESTS;
728 case CA_INTERNAL_SERVER_ERROR:
729 ret = OC_STACK_INTERNAL_SERVER_ERROR;
731 case CA_NOT_IMPLEMENTED:
732 ret = OC_STACK_NOT_IMPLEMENTED;
735 ret = OC_STACK_BAD_GATEWAY;
737 case CA_SERVICE_UNAVAILABLE:
738 ret = OC_STACK_SERVICE_UNAVAILABLE;
740 case CA_RETRANSMIT_TIMEOUT:
741 ret = OC_STACK_GATEWAY_TIMEOUT;
743 case CA_PROXY_NOT_SUPPORTED:
744 ret = OC_STACK_PROXY_NOT_SUPPORTED;
752 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
754 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
763 // This Response Code is like HTTP 204 "No Content" but only used in
764 // response to POST and PUT requests.
768 // This Response Code is like HTTP 200 "OK" but only used in response to
773 // This should not happen but,
774 // give it a value just in case but output an error
776 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
780 case OC_STACK_RESOURCE_CREATED:
783 case OC_STACK_RESOURCE_DELETED:
786 case OC_STACK_RESOURCE_CHANGED:
789 case OC_STACK_INVALID_QUERY:
792 case OC_STACK_INVALID_OPTION:
795 case OC_STACK_NO_RESOURCE:
798 case OC_STACK_COMM_ERROR:
799 ret = CA_RETRANSMIT_TIMEOUT;
801 case OC_STACK_METHOD_NOT_ALLOWED:
802 ret = CA_METHOD_NOT_ALLOWED;
804 case OC_STACK_NOT_ACCEPTABLE:
805 ret = CA_NOT_ACCEPTABLE;
807 case OC_STACK_UNAUTHORIZED_REQ:
808 ret = CA_UNAUTHORIZED_REQ;
810 case OC_STACK_FORBIDDEN_REQ:
811 ret = CA_FORBIDDEN_REQ;
813 case OC_STACK_TOO_MANY_REQUESTS:
814 ret = CA_TOO_MANY_REQUESTS;
816 case OC_STACK_INTERNAL_SERVER_ERROR:
817 ret = CA_INTERNAL_SERVER_ERROR;
819 case OC_STACK_NOT_IMPLEMENTED:
820 ret = CA_NOT_IMPLEMENTED;
822 case OC_STACK_BAD_GATEWAY:
823 ret = CA_BAD_GATEWAY;
825 case OC_STACK_SERVICE_UNAVAILABLE:
826 ret = CA_SERVICE_UNAVAILABLE;
828 case OC_STACK_GATEWAY_TIMEOUT:
829 ret = CA_RETRANSMIT_TIMEOUT;
831 case OC_STACK_PROXY_NOT_SUPPORTED:
832 ret = CA_PROXY_NOT_SUPPORTED;
840 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
842 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
844 // supply default behavior.
845 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
847 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
849 if ((caFlags & OC_MASK_SCOPE) == 0)
851 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
856 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
858 return (OCTransportFlags)caFlags;
862 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
864 uint32_t lowerBound = 0;
865 uint32_t higherBound = 0;
867 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
869 return OC_STACK_INVALID_PARAM;
872 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
874 cbNode->presence->TTL = maxAgeSeconds;
876 for (int index = 0; index < PresenceTimeOutSize; index++)
878 // Guard against overflow
879 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
882 lowerBound = GetTicks((PresenceTimeOut[index] *
883 cbNode->presence->TTL *
884 MILLISECONDS_PER_SECOND)/100);
888 lowerBound = GetTicks(UINT32_MAX);
891 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
894 higherBound = GetTicks((PresenceTimeOut[index + 1] *
895 cbNode->presence->TTL *
896 MILLISECONDS_PER_SECOND)/100);
900 higherBound = GetTicks(UINT32_MAX);
903 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
905 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
906 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
907 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
910 cbNode->presence->TTLlevel = 0;
912 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
916 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
918 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
920 return OC_RSRVD_TRIGGER_CREATE;
922 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
924 return OC_RSRVD_TRIGGER_CHANGE;
928 return OC_RSRVD_TRIGGER_DELETE;
932 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
936 return OC_PRESENCE_TRIGGER_CREATE;
938 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
940 return OC_PRESENCE_TRIGGER_CREATE;
942 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
944 return OC_PRESENCE_TRIGGER_CHANGE;
948 return OC_PRESENCE_TRIGGER_DELETE;
951 #endif // WITH_PRESENCE
953 OCStackResult OCEncodeAddressForRFC6874(char *outputAddress,
955 const char *inputAddress)
957 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
958 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
960 size_t inputLength = strnlen(inputAddress, outputSize);
962 // inputSize includes the null terminator
963 size_t inputSize = inputLength + 1;
965 if (inputSize > outputSize)
967 OIC_LOG_V(ERROR, TAG,
968 "OCEncodeAddressForRFC6874 failed: "
969 "outputSize (%zu) < inputSize (%zu)",
970 outputSize, inputSize);
972 return OC_STACK_ERROR;
975 char* percentChar = strchr(inputAddress, '%');
977 // If there is no '%' character, then no change is required to the string.
978 if (NULL == percentChar)
980 OICStrcpy(outputAddress, outputSize, inputAddress);
984 const char* addressPart = &inputAddress[0];
985 const char* scopeIdPart = percentChar + 1;
987 // Sanity check to make sure this string doesn't have more '%' characters
988 if (NULL != strchr(scopeIdPart, '%'))
990 return OC_STACK_ERROR;
993 // If no string follows the first '%', then the input was invalid.
994 if (scopeIdPart[0] == '\0')
996 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
997 return OC_STACK_ERROR;
1000 // Check to see if the string is already encoded
1001 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
1003 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Input string is already encoded");
1004 return OC_STACK_ERROR;
1007 // Fail if we don't have room for encoded string's two additional chars
1008 if (outputSize < (inputSize + 2))
1010 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: encoded output will not fit!");
1011 return OC_STACK_ERROR;
1014 // Restore the null terminator with an escaped '%' character, per RFC 6874
1015 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
1016 OICStrcat(outputAddress, outputSize, "%25");
1017 OICStrcat(outputAddress, outputSize, scopeIdPart);
1022 OCStackResult OCDecodeAddressForRFC6874(char *outputAddress,
1024 const char *inputAddress,
1027 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
1028 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
1032 end = inputAddress + strlen(inputAddress);
1034 size_t inputLength = end - inputAddress;
1036 const char *percent = strchr(inputAddress, '%');
1037 if (!percent || (percent > end))
1039 OICStrcpyPartial(outputAddress, outputSize, inputAddress, inputLength);
1043 if (percent[1] != '2' || percent[2] != '5')
1045 return OC_STACK_INVALID_URI;
1048 int addrlen = percent - inputAddress + 1;
1049 OICStrcpyPartial(outputAddress, outputSize, inputAddress, addrlen);
1050 OICStrcpyPartial(outputAddress + addrlen, outputSize - addrlen,
1051 percent + 3, end - percent - 3);
1057 #ifdef WITH_PRESENCE
1059 * The cononical presence allows constructed URIs to be string compared.
1061 * requestUri must be a char array of size CA_MAX_URI_LENGTH
1063 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
1064 char *presenceUri, bool isMulticast)
1066 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
1067 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1071 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1072 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1075 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1076 if (ep->adapter == CA_ADAPTER_IP)
1078 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1080 if ('\0' == ep->addr[0]) // multicast
1082 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1086 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1088 OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1089 sizeof(addressEncoded),
1092 if (OC_STACK_OK != result)
1097 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1098 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1103 if ('\0' == ep->addr[0]) // multicast
1105 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1106 ep->port = OC_MULTICAST_PORT;
1108 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1109 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1113 // might work for other adapters (untested, but better than nothing)
1114 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1115 OC_RSRVD_PRESENCE_URI);
1119 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1120 const CAResponseInfo_t *responseInfo)
1122 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1123 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1125 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1126 ClientCB * cbNode = NULL;
1127 char *resourceTypeName = NULL;
1128 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1129 OCStackResult result = OC_STACK_ERROR;
1130 uint32_t maxAge = 0;
1132 char presenceUri[CA_MAX_URI_LENGTH];
1134 int presenceSubscribe = 0;
1135 int multicastPresenceSubscribe = 0;
1137 if (responseInfo->result != CA_CONTENT)
1139 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1140 return OC_STACK_ERROR;
1143 response.payload = NULL;
1144 response.result = OC_STACK_OK;
1146 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1147 FixUpClientResponse(&response);
1149 if (responseInfo->info.payload)
1151 result = OCParsePayload(&response.payload,
1152 PAYLOAD_TYPE_PRESENCE,
1153 responseInfo->info.payload,
1154 responseInfo->info.payloadSize);
1156 if(result != OC_STACK_OK)
1158 OIC_LOG(ERROR, TAG, "Presence parse failed");
1161 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1163 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1164 result = OC_STACK_ERROR;
1167 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1168 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1169 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1172 // check for unicast presence
1173 uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1174 responseInfo->isMulticast);
1175 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1177 return OC_STACK_INVALID_URI;
1179 OIC_LOG(INFO, TAG, "check for unicast presence");
1180 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1183 presenceSubscribe = 1;
1187 // check for multicast presence
1188 OIC_LOG(INFO, TAG, "check for multicast presence");
1189 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1192 multicastPresenceSubscribe = 1;
1196 if (!presenceSubscribe && !multicastPresenceSubscribe)
1198 OIC_LOG(INFO, TAG, "Received a presence notification, "
1199 "but need to register presence callback, ignoring");
1203 if (presenceSubscribe)
1205 if(cbNode->sequenceNumber == response.sequenceNumber)
1207 OIC_LOG(INFO, TAG, "No presence change");
1208 ResetPresenceTTL(cbNode, maxAge);
1209 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1215 OIC_LOG(INFO, TAG, "Stopping presence");
1216 response.result = OC_STACK_PRESENCE_STOPPED;
1217 if(cbNode->presence)
1219 OICFree(cbNode->presence->timeOut);
1220 OICFree(cbNode->presence);
1221 cbNode->presence = NULL;
1226 if(!cbNode->presence)
1228 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1230 if(!(cbNode->presence))
1232 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1233 result = OC_STACK_NO_MEMORY;
1237 VERIFY_NON_NULL_V(cbNode->presence);
1238 cbNode->presence->timeOut = NULL;
1239 cbNode->presence->timeOut = (uint32_t *)
1240 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1241 if(!(cbNode->presence->timeOut)){
1243 "Could not allocate memory for cbNode->presence->timeOut");
1244 OICFree(cbNode->presence);
1245 result = OC_STACK_NO_MEMORY;
1250 ResetPresenceTTL(cbNode, maxAge);
1252 cbNode->sequenceNumber = response.sequenceNumber;
1257 // This is the multicast case
1258 OIC_LOG(INFO, TAG, "this is the multicast presence");
1261 OIC_LOG(INFO, TAG, "Stopping presence");
1262 response.result = OC_STACK_PRESENCE_STOPPED;
1266 // Ensure that a filter is actually applied.
1267 if (resourceTypeName && cbNode->filterResourceType)
1269 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1270 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1276 OIC_LOG(INFO, TAG, "Before calling into application address space for presence");
1277 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1278 OIC_LOG(INFO, TAG, "After calling into application address space for presence");
1280 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1282 FindAndDeleteClientCB(cbNode);
1286 OCPayloadDestroy(response.payload);
1289 #endif // WITH_PRESENCE
1291 OCStackResult HandleBatchResponse(char *requestUri, OCRepPayload **payload)
1293 if (requestUri && *payload)
1295 char *interfaceName = NULL;
1296 char *rtTypeName = NULL;
1297 char *uriQuery = NULL;
1298 char *uriWithoutQuery = NULL;
1299 if (OC_STACK_OK == getQueryFromUri(requestUri, &uriQuery, &uriWithoutQuery))
1301 if (OC_STACK_OK == ExtractFiltersFromQuery(uriQuery, &interfaceName, &rtTypeName))
1303 if (interfaceName && (0 == strcmp(OC_RSRVD_INTERFACE_BATCH, interfaceName)))
1305 char *uri = (*payload)->uri;
1306 if (uri && 0 != strcmp(uriWithoutQuery, uri))
1308 OCRepPayload *newPayload = OCRepPayloadCreate();
1311 OCRepPayloadSetUri(newPayload, uri);
1312 newPayload->next = *payload;
1313 *payload = newPayload;
1320 OICFree(interfaceName);
1321 OICFree(rtTypeName);
1323 OICFree(uriWithoutQuery);
1326 return OC_STACK_INVALID_PARAM;
1329 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1331 OIC_TRACE_MARK(%s:OCHandleResponse:%s, TAG, responseInfo->info.resourceUri);
1332 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1334 #ifdef WITH_PRESENCE
1335 if(responseInfo->info.resourceUri &&
1336 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1338 HandlePresenceResponse(endPoint, responseInfo);
1343 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1344 responseInfo->info.tokenLength, NULL, NULL);
1348 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1350 // check obs header option
1351 bool obsHeaderOpt = false;
1352 CAHeaderOption_t *options = responseInfo->info.options;
1353 for (uint8_t i = 0; i< responseInfo->info.numOptions; i++)
1355 if (options && options[i].protocolID == CA_COAP_ID &&
1356 options[i].optionID == COAP_OPTION_OBSERVE)
1358 obsHeaderOpt = true;
1363 if(responseInfo->result == CA_EMPTY)
1365 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1366 // We do not have a case for the client to receive a RESET
1367 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1369 //This is the case of receiving an ACK on a request to a slow resource!
1370 OIC_LOG(INFO, TAG, "This is a pure ACK");
1371 //TODO: should we inform the client
1372 // app that at least the request was received at the server?
1375 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1377 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1379 OCClientResponse response =
1380 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1381 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1382 FixUpClientResponse(&response);
1383 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1384 memcpy(response.identity.id, responseInfo->info.identity.id,
1385 sizeof (response.identity.id));
1386 response.identity.id_length = responseInfo->info.identity.id_length;
1388 response.result = CAResponseToOCStackResult(responseInfo->result);
1389 OIC_LOG(INFO, TAG, "Before calling into application address space for reTrans timeout");
1390 cbNode->callBack(cbNode->context,
1391 cbNode->handle, &response);
1392 OIC_LOG(INFO, TAG, "After calling into application address space for reTrans timeout");
1393 FindAndDeleteClientCB(cbNode);
1394 OICFree((void *)response.resourceUri);
1397 else if ((cbNode->method == OC_REST_OBSERVE || cbNode->method == OC_REST_OBSERVE_ALL)
1398 && (responseInfo->result == CA_CONTENT) && !obsHeaderOpt)
1400 OCClientResponse response =
1401 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1402 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1403 FixUpClientResponse(&response);
1404 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1405 memcpy(response.identity.id, responseInfo->info.identity.id,
1406 sizeof (response.identity.id));
1407 response.identity.id_length = responseInfo->info.identity.id_length;
1408 response.result = OC_STACK_UNAUTHORIZED_REQ;
1410 OIC_LOG(INFO, TAG, "Before calling into application address space for observe resp");
1411 cbNode->callBack(cbNode->context,
1414 OIC_LOG(INFO, TAG, "After calling into application address space for observe resp");
1416 FindAndDeleteClientCB(cbNode);
1417 OICFree(response.resourceUri);
1422 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1424 OCClientResponse response;
1425 memset(&response, 0, sizeof(OCClientResponse));
1426 response.devAddr.adapter = OC_DEFAULT_ADAPTER;
1428 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1429 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1430 FixUpClientResponse(&response);
1431 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1432 memcpy(response.identity.id, responseInfo->info.identity.id,
1433 sizeof (response.identity.id));
1434 response.identity.id_length = responseInfo->info.identity.id_length;
1436 response.result = CAResponseToOCStackResult(responseInfo->result);
1438 if(responseInfo->info.payload &&
1439 responseInfo->info.payloadSize)
1441 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1442 // check the security resource
1443 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1445 type = PAYLOAD_TYPE_SECURITY;
1447 else if (cbNode->method == OC_REST_DISCOVER)
1449 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1450 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1452 type = PAYLOAD_TYPE_DISCOVERY;
1455 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1457 type = PAYLOAD_TYPE_DISCOVERY;
1460 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1462 type = PAYLOAD_TYPE_REPRESENTATION;
1464 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1466 type = PAYLOAD_TYPE_REPRESENTATION;
1469 #ifdef ROUTING_GATEWAY
1470 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1472 type = PAYLOAD_TYPE_REPRESENTATION;
1475 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1477 type = PAYLOAD_TYPE_REPRESENTATION;
1480 else if (strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1482 type = PAYLOAD_TYPE_REPRESENTATION;
1487 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1488 cbNode->method, cbNode->requestUri);
1489 OICFree((void *)response.resourceUri);
1493 else if (cbNode->method == OC_REST_GET ||
1494 cbNode->method == OC_REST_PUT ||
1495 cbNode->method == OC_REST_POST ||
1496 cbNode->method == OC_REST_OBSERVE ||
1497 cbNode->method == OC_REST_OBSERVE_ALL ||
1498 cbNode->method == OC_REST_DELETE)
1500 if (cbNode->requestUri)
1502 if (0 == strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri))
1504 type = PAYLOAD_TYPE_REPRESENTATION;
1506 else if (0 == strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri))
1508 type = PAYLOAD_TYPE_REPRESENTATION;
1510 if (type == PAYLOAD_TYPE_INVALID)
1512 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1513 cbNode->method, cbNode->requestUri);
1514 type = PAYLOAD_TYPE_REPRESENTATION;
1519 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1520 type = PAYLOAD_TYPE_REPRESENTATION;
1525 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1526 cbNode->method, cbNode->requestUri);
1527 OICFree((void *)response.resourceUri);
1531 // In case of error, still want application to receive the error message.
1532 if (OCResultToSuccess(response.result) || PAYLOAD_TYPE_REPRESENTATION == type)
1534 if(OC_STACK_OK != OCParsePayload(&response.payload,
1536 responseInfo->info.payload,
1537 responseInfo->info.payloadSize))
1539 OIC_LOG(ERROR, TAG, "Error converting payload");
1540 OCPayloadDestroy(response.payload);
1541 OICFree((void *)response.resourceUri);
1547 OICFree((void *)response.resourceUri);
1548 response.resourceUri = OICStrdup(cbNode->requestUri);
1552 response.numRcvdVendorSpecificHeaderOptions = 0;
1553 if(responseInfo->info.numOptions > 0)
1556 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1557 if(responseInfo->info.options
1558 && responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1561 uint32_t observationOption;
1562 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1563 for (observationOption=0, i=0;
1564 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1568 (observationOption << 8) | optionData[i];
1570 response.sequenceNumber = observationOption;
1571 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1576 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1579 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1581 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1582 OCPayloadDestroy(response.payload);
1583 OICFree((void *)response.resourceUri);
1587 if (response.numRcvdVendorSpecificHeaderOptions > 0)
1589 response.rcvdVendorSpecificHeaderOptions =
1590 (OCHeaderOption *) OICCalloc(response.numRcvdVendorSpecificHeaderOptions, sizeof(OCHeaderOption));
1591 if (NULL == response.rcvdVendorSpecificHeaderOptions)
1593 OIC_LOG(ERROR, TAG, "Failed to allocate memory for vendor header options");
1594 OCPayloadDestroy(response.payload);
1595 OICFree((void *)response.resourceUri);
1599 memcpy(response.rcvdVendorSpecificHeaderOptions, responseInfo->info.options + start,
1600 response.numRcvdVendorSpecificHeaderOptions*sizeof(OCHeaderOption));
1604 if (cbNode->method == OC_REST_OBSERVE &&
1605 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1606 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1607 response.sequenceNumber <= cbNode->sequenceNumber)
1609 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1610 response.sequenceNumber);
1615 if (cbNode->requestUri)
1617 // if request uri is '/oic/rd', update ins value of resource.
1618 char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
1621 OCUpdateResourceInsWithResponse(cbNode->requestUri, &response);
1625 // set remoteID(device ID) into OCClientResponse callback parameter
1626 if (OC_REST_DISCOVER == cbNode->method)
1628 OIC_LOG(INFO, TAG, "cbNode method is OC_REST_DISCOVER");
1629 OCDiscoveryPayload *payload = (OCDiscoveryPayload*) response.payload;
1630 // Payload can be empty in case of error message.
1631 if (payload && payload->sid)
1633 OICStrcpy(response.devAddr.remoteId, sizeof(response.devAddr.remoteId),
1635 OIC_LOG_V(INFO_PRIVATE, TAG, "Device ID of response : %s",
1636 response.devAddr.remoteId);
1639 if(NULL == response.resourceUri)
1641 response.resourceUri = OICStrdup(cbNode->requestUri);
1645 if (cbNode->requestUri)
1647 OIC_LOG_V(INFO, TAG, "cbNode requestUri is %s", cbNode->requestUri);
1648 if (cbNode->method == OC_REST_POST &&
1649 strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1651 OCHandleKeepAliveResponse(endPoint, response.payload);
1655 if (response.payload && response.payload->type == PAYLOAD_TYPE_REPRESENTATION)
1657 OIC_LOG(INFO, TAG, "Handle batch response");
1658 HandleBatchResponse(cbNode->requestUri, (OCRepPayload **)&response.payload);
1661 OIC_LOG(INFO, TAG, "Before calling into application address space for handleResponse");
1662 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1665 OIC_LOG(INFO, TAG, "After calling into application address space for handleResponse");
1667 cbNode->sequenceNumber = response.sequenceNumber;
1669 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1671 FindAndDeleteClientCB(cbNode);
1675 // To keep discovery callbacks active.
1676 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1677 MILLISECONDS_PER_SECOND);
1681 //Need to send ACK when the response is CON
1682 if(responseInfo->info.type == CA_MSG_CONFIRM)
1684 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1686 OIC_LOG(INFO, TAG, "Received a confirmable message. Sending EMPTY");
1687 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1688 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1692 OICFree((void *)response.resourceUri);
1693 OCPayloadDestroy(response.payload);
1694 OICFree(response.rcvdVendorSpecificHeaderOptions);
1699 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1700 responseInfo->info.tokenLength);
1704 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1705 if(responseInfo->result == CA_EMPTY)
1707 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1708 if(responseInfo->info.type == CA_MSG_RESET)
1710 OIC_LOG(INFO, TAG, "This is a RESET");
1711 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1712 OC_OBSERVER_NOT_INTERESTED);
1714 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1716 OIC_LOG(INFO, TAG, "This is a pure ACK");
1717 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1718 OC_OBSERVER_STILL_INTERESTED);
1721 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1723 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1724 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1725 OC_OBSERVER_FAILED_COMM);
1728 FreeObserver(observer);
1732 if(!cbNode && !observer)
1734 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1735 || myStackMode == OC_GATEWAY)
1737 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1738 if(responseInfo->result == CA_EMPTY)
1740 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1744 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1746 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1747 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1748 CA_MSG_RESET, 0, NULL, NULL, 0, NULL,
1749 CA_RESPONSE_FOR_RES);
1754 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1755 || myStackMode == OC_GATEWAY)
1757 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1758 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1760 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1761 responseInfo->info.messageId);
1763 if (responseInfo->info.type == CA_MSG_RESET)
1765 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1766 responseInfo->info.messageId);
1774 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1776 VERIFY_NON_NULL_NR(endPoint, FATAL);
1777 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1779 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1780 OIC_TRACE_BEGIN(%s:HandleCAResponses, TAG);
1782 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1783 #ifdef ROUTING_GATEWAY
1784 bool needRIHandling = false;
1786 * Routing manager is going to update either of endpoint or response or both.
1787 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1788 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1791 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1793 if(ret != OC_STACK_OK || !needRIHandling)
1795 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1802 * Put source in sender endpoint so that the next packet from application can be routed to
1803 * proper destination and remove "RM" coap header option before passing request / response to
1804 * RI as this option will make no sense to either RI or application.
1806 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1807 (uint8_t *) &(responseInfo->info.numOptions),
1808 (CAEndpoint_t *) endPoint);
1811 OCHandleResponse(endPoint, responseInfo);
1813 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1817 * This function handles error response from CA
1818 * code shall be added to handle the errors
1820 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1822 VERIFY_NON_NULL_NR(endPoint, FATAL);
1823 VERIFY_NON_NULL_NR(errorInfo, FATAL);
1825 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1826 OIC_TRACE_BEGIN(%s:HandleCAErrorResponse, TAG);
1828 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1829 errorInfo->info.tokenLength, NULL, NULL);
1832 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1833 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1834 FixUpClientResponse(&response);
1835 response.resourceUri = errorInfo->info.resourceUri;
1836 memcpy(response.identity.id, errorInfo->info.identity.id,
1837 sizeof (response.identity.id));
1838 response.identity.id_length = errorInfo->info.identity.id_length;
1839 response.result = CAResultToOCResult(errorInfo->result);
1841 OIC_LOG(INFO, TAG, "Before calling into application address space for error response");
1842 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1843 OIC_LOG(INFO, TAG, "After calling into application address space for error response");
1846 ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1847 errorInfo->info.tokenLength);
1850 OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1851 OCStackResult result = CAResultToOCResult(errorInfo->result);
1852 if (OC_STACK_COMM_ERROR == result)
1854 OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1855 OC_OBSERVER_FAILED_COMM);
1859 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1864 * This function sends out Direct Stack Responses. These are responses that are not coming
1865 * from the application entity handler. These responses have no payload and are usually ACKs,
1866 * RESETs or some error conditions that were caught by the stack.
1868 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1869 const CAResponseResult_t responseResult, const CAMessageType_t type,
1870 const uint8_t numOptions, const CAHeaderOption_t *options,
1871 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1872 CADataType_t dataType)
1874 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1876 if (endPoint->flags & CA_MULTICAST)
1878 OIC_LOG(ERROR, TAG, "It is unnecessary to respond to a multicast request");
1882 CAResponseInfo_t respInfo = { .result = responseResult };
1883 respInfo.info.messageId = coapID;
1884 respInfo.info.numOptions = numOptions;
1886 if (respInfo.info.numOptions)
1888 respInfo.info.options =
1889 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1890 memcpy (respInfo.info.options, options,
1891 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1895 respInfo.info.payload = NULL;
1896 respInfo.info.token = token;
1897 respInfo.info.tokenLength = tokenLength;
1898 respInfo.info.type = type;
1899 respInfo.info.resourceUri = OICStrdup (resourceUri);
1900 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1901 respInfo.info.dataType = dataType;
1903 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1904 // Add the destination to route option from the endpoint->routeData.
1905 bool doPost = false;
1906 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1907 if(OC_STACK_OK != result)
1909 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1910 OICFree (respInfo.info.resourceUri);
1911 OICFree (respInfo.info.options);
1916 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1917 CARequestInfo_t reqInfo = {.method = CA_POST };
1918 /* The following initialization is not done in a single initializer block as in
1919 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1920 * does not have designated initalizers. This is a work-around for now.
1922 reqInfo.info.type = CA_MSG_NONCONFIRM;
1923 reqInfo.info.messageId = coapID;
1924 reqInfo.info.tokenLength = tokenLength;
1925 reqInfo.info.token = token;
1926 reqInfo.info.numOptions = respInfo.info.numOptions;
1927 reqInfo.info.payload = NULL;
1928 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1929 if (reqInfo.info.numOptions)
1931 reqInfo.info.options =
1932 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1933 if (NULL == reqInfo.info.options)
1935 OIC_LOG(ERROR, TAG, "Calloc failed");
1936 OICFree (reqInfo.info.resourceUri);
1937 OICFree (respInfo.info.resourceUri);
1938 OICFree (respInfo.info.options);
1939 return OC_STACK_NO_MEMORY;
1941 memcpy (reqInfo.info.options, respInfo.info.options,
1942 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1945 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1946 OICFree (reqInfo.info.resourceUri);
1947 OICFree (reqInfo.info.options);
1948 OICFree (respInfo.info.resourceUri);
1949 OICFree (respInfo.info.options);
1950 if (CA_STATUS_OK != caResult)
1952 OIC_LOG(ERROR, TAG, "CASendRequest error");
1953 return CAResultToOCResult(caResult);
1959 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1961 // resourceUri in the info field is cloned in the CA layer and
1962 // thus ownership is still here.
1963 OICFree (respInfo.info.resourceUri);
1964 OICFree (respInfo.info.options);
1965 if(CA_STATUS_OK != caResult)
1967 OIC_LOG(ERROR, TAG, "CASendResponse error");
1968 return CAResultToOCResult(caResult);
1971 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1975 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1977 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1978 OCStackResult result = OC_STACK_ERROR;
1979 if(!protocolRequest)
1981 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1982 return OC_STACK_INVALID_PARAM;
1985 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1986 protocolRequest->tokenLength);
1989 OIC_LOG(INFO, TAG, "This is a new Server Request");
1990 result = AddServerRequest(&request, protocolRequest->coapID,
1991 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1992 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1993 protocolRequest->observationOption, protocolRequest->qos,
1994 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1995 protocolRequest->payload, protocolRequest->requestToken,
1996 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1997 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1998 &protocolRequest->devAddr);
1999 if (OC_STACK_OK != result)
2001 OIC_LOG(ERROR, TAG, "Error adding server request");
2007 OIC_LOG(ERROR, TAG, "Out of Memory");
2008 return OC_STACK_NO_MEMORY;
2011 if(!protocolRequest->reqMorePacket)
2013 request->requestComplete = 1;
2018 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
2021 if(request->requestComplete)
2023 OIC_LOG(INFO, TAG, "This Server Request is complete");
2024 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2025 OCResource *resource = NULL;
2026 result = DetermineResourceHandling (request, &resHandling, &resource);
2027 if (result == OC_STACK_OK)
2029 result = ProcessRequest(resHandling, resource, request);
2034 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2035 result = OC_STACK_CONTINUE;
2040 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2042 OIC_TRACE_MARK(%s:OCHandleRequests:%s, TAG, requestInfo->info.resourceUri);
2043 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2045 OCStackResult requestResult = OC_STACK_ERROR;
2047 if(myStackMode == OC_CLIENT)
2049 //TODO: should the client be responding to requests?
2053 OCServerProtocolRequest serverRequest = {0};
2055 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2057 char * uriWithoutQuery = NULL;
2058 char * query = NULL;
2060 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2062 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2064 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2067 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2068 OIC_LOG_V(INFO, TAG, "Query : %s", query);
2070 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2072 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2073 OICFree(uriWithoutQuery);
2077 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2078 OICFree(uriWithoutQuery);
2085 if(strlen(query) < MAX_QUERY_LENGTH)
2087 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2092 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2098 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2100 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2101 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2102 if (!serverRequest.payload)
2104 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2107 memcpy (serverRequest.payload, requestInfo->info.payload,
2108 requestInfo->info.payloadSize);
2112 serverRequest.reqTotalSize = 0;
2115 switch (requestInfo->method)
2118 serverRequest.method = OC_REST_GET;
2121 serverRequest.method = OC_REST_PUT;
2124 serverRequest.method = OC_REST_POST;
2127 serverRequest.method = OC_REST_DELETE;
2130 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2131 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2132 requestInfo->info.type, requestInfo->info.numOptions,
2133 requestInfo->info.options, requestInfo->info.token,
2134 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2136 OICFree(serverRequest.payload);
2140 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2141 requestInfo->info.tokenLength);
2143 serverRequest.tokenLength = requestInfo->info.tokenLength;
2144 if (serverRequest.tokenLength) {
2146 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2148 if (!serverRequest.requestToken)
2150 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2151 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2152 requestInfo->info.type, requestInfo->info.numOptions,
2153 requestInfo->info.options, requestInfo->info.token,
2154 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2156 OICFree(serverRequest.payload);
2159 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2162 switch (requestInfo->info.acceptFormat)
2164 case CA_FORMAT_APPLICATION_CBOR:
2165 serverRequest.acceptFormat = OC_FORMAT_CBOR;
2167 case CA_FORMAT_UNDEFINED:
2168 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2171 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2174 if (requestInfo->info.type == CA_MSG_CONFIRM)
2176 serverRequest.qos = OC_HIGH_QOS;
2180 serverRequest.qos = OC_LOW_QOS;
2182 // CA does not need the following field
2183 // Are we sure CA does not need them? how is it responding to multicast
2184 serverRequest.delayedResNeeded = 0;
2186 serverRequest.coapID = requestInfo->info.messageId;
2188 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2190 // copy vendor specific header options
2191 uint8_t tempNum = (requestInfo->info.numOptions);
2193 // Assume no observation requested and it is a pure GET.
2194 // If obs registration/de-registration requested it'll be fetched from the
2195 // options in GetObserveHeaderOption()
2196 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2198 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2199 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2202 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2203 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2204 requestInfo->info.type, requestInfo->info.numOptions,
2205 requestInfo->info.options, requestInfo->info.token,
2206 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2208 OICFree(serverRequest.payload);
2209 OICFree(serverRequest.requestToken);
2213 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2214 if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2216 serverRequest.rcvdVendorSpecificHeaderOptions = (OCHeaderOption*) OICCalloc(tempNum, sizeof(OCHeaderOption));
2217 if (NULL == serverRequest.rcvdVendorSpecificHeaderOptions)
2219 OIC_LOG(ERROR, TAG, "Failed to allocated memory to vnd header options!");
2220 OICFree(serverRequest.payload);
2221 OICFree(serverRequest.requestToken);
2225 memcpy (serverRequest.rcvdVendorSpecificHeaderOptions, requestInfo->info.options,
2226 sizeof(CAHeaderOption_t)*tempNum);
2229 requestResult = HandleStackRequests (&serverRequest);
2231 // Send ACK to client as precursor to slow response
2232 if (requestResult == OC_STACK_SLOW_RESOURCE)
2234 if (requestInfo->info.type == CA_MSG_CONFIRM)
2236 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2237 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2242 if (requestResult == OC_STACK_RESOURCE_ERROR
2243 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2245 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2248 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2250 if (requestResult == OC_STACK_RESOURCE_ERROR)
2252 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2254 else if (!OCResultToSuccess(requestResult))
2256 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2260 else if(!OCResultToSuccess(requestResult))
2262 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2264 // Delete observer node if it is OBSERVE failure from app
2265 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2267 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2270 CAResponseResult_t stackResponse =
2271 OCToCAStackResult(requestResult, serverRequest.method);
2273 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2274 requestInfo->info.type, requestInfo->info.numOptions,
2275 requestInfo->info.options, requestInfo->info.token,
2276 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2279 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2280 // The token is copied in there, and is thus still owned by this function.
2281 OICFree(serverRequest.payload);
2282 OICFree(serverRequest.requestToken);
2283 OICFree(serverRequest.rcvdVendorSpecificHeaderOptions);
2284 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2287 //This function will be called back by CA layer when a request is received
2288 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2290 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2291 OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2294 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2301 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2306 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2307 #ifdef ROUTING_GATEWAY
2308 bool needRIHandling = false;
2309 bool isEmptyMsg = false;
2311 * Routing manager is going to update either of endpoint or request or both.
2312 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2313 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2314 * destination. It can also remove "RM" coap header option before passing request / response to
2315 * RI as this option will make no sense to either RI or application.
2317 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2318 &needRIHandling, &isEmptyMsg);
2319 if(OC_STACK_OK != ret || !needRIHandling)
2321 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2328 * Put source in sender endpoint so that the next packet from application can be routed to
2329 * proper destination and remove RM header option.
2331 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2332 (uint8_t *) &(requestInfo->info.numOptions),
2333 (CAEndpoint_t *) endPoint);
2335 #ifdef ROUTING_GATEWAY
2339 * In Gateways, the MSGType in route option is used to check if the actual
2340 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2341 * EMPTY response is sent in the form of POST request which need to be changed
2342 * to a EMPTY response by RM. This translation is done in this part of the code.
2344 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2345 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2346 .info.messageId = requestInfo->info.messageId,
2347 .info.type = CA_MSG_ACKNOWLEDGE};
2348 OCHandleResponse(endPoint, &respInfo);
2354 // Normal handling of the packet
2355 OCHandleRequests(endPoint, requestInfo);
2357 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2361 //-----------------------------------------------------------------------------
2363 //-----------------------------------------------------------------------------
2365 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2368 !raInfo->username ||
2369 !raInfo->hostname ||
2370 !raInfo->xmpp_domain)
2373 return OC_STACK_INVALID_PARAM;
2375 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2376 gRASetInfo = (result == OC_STACK_OK)? true : false;
2382 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2386 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2389 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2391 OC_UNUSED(serverFlags);
2392 OC_UNUSED(clientFlags);
2394 OIC_LOG(DEBUG, TAG, "call OCInit1");
2395 return OCInit2(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS, OC_DEFAULT_ADAPTER);
2398 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2399 OCTransportAdapter transportType)
2401 if(stackState == OC_STACK_INITIALIZED)
2403 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2404 OCStop() between them are ignored.");
2408 #ifndef ROUTING_GATEWAY
2409 if (OC_GATEWAY == mode)
2411 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2412 return OC_STACK_INVALID_PARAM;
2419 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2420 return OC_STACK_ERROR;
2424 OCStackResult result = OC_STACK_ERROR;
2425 OIC_LOG(INFO, TAG, "Entering OCInit");
2428 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2429 || (mode == OC_GATEWAY)))
2431 OIC_LOG(ERROR, TAG, "Invalid mode");
2432 return OC_STACK_ERROR;
2436 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2438 caglobals.client = true;
2440 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2442 caglobals.server = true;
2445 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2446 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2448 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2450 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2451 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2453 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2456 defaultDeviceHandler = NULL;
2457 defaultDeviceHandlerCallbackParameter = NULL;
2459 result = InitializeScheduleResourceList();
2460 VERIFY_SUCCESS(result, OC_STACK_OK);
2462 result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2463 VERIFY_SUCCESS(result, OC_STACK_OK);
2465 result = CAResultToOCResult(OCSelectNetwork(transportType));
2466 VERIFY_SUCCESS(result, OC_STACK_OK);
2468 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2469 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2470 VERIFY_SUCCESS(result, OC_STACK_OK);
2472 switch (myStackMode)
2475 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2476 result = CAResultToOCResult(CAStartDiscoveryServer());
2477 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2480 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2481 result = CAResultToOCResult(CAStartListeningServer());
2482 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2484 case OC_CLIENT_SERVER:
2486 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2487 result = CAResultToOCResult(CAStartListeningServer());
2488 if(result == OC_STACK_OK)
2490 result = CAResultToOCResult(CAStartDiscoveryServer());
2494 VERIFY_SUCCESS(result, OC_STACK_OK);
2497 CARegisterKeepAliveHandler(OCHandleKeepAliveConnCB);
2500 #ifdef WITH_PRESENCE
2501 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2502 #endif // WITH_PRESENCE
2504 //Update Stack state to initialized
2505 stackState = OC_STACK_INITIALIZED;
2507 // Initialize resource
2508 if(myStackMode != OC_CLIENT)
2510 result = initResources();
2513 // Initialize the SRM Policy Engine
2514 if(result == OC_STACK_OK)
2516 result = SRMInitPolicyEngine();
2517 // TODO after BeachHead delivery: consolidate into single SRMInit()
2519 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2520 RMSetStackMode(mode);
2521 #ifdef ROUTING_GATEWAY
2522 if (OC_GATEWAY == myStackMode)
2524 result = RMInitialize();
2530 if (result == OC_STACK_OK)
2532 result = OCInitializeKeepAlive(myStackMode);
2536 InitializeObserverList();
2539 if(result != OC_STACK_OK)
2541 OIC_LOG(ERROR, TAG, "Stack initialization error");
2542 TerminateScheduleResourceList();
2543 deleteAllResources();
2545 stackState = OC_STACK_UNINITIALIZED;
2550 OCStackResult OCStop()
2552 OIC_LOG(INFO, TAG, "Entering OCStop");
2554 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2556 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2559 else if (stackState != OC_STACK_INITIALIZED)
2561 OIC_LOG(INFO, TAG, "Stack not initialized");
2562 return OC_STACK_ERROR;
2565 // unset cautil config
2566 CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2567 CAUtilSetBTConfigure(configs);
2569 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2571 CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2572 OCDefaultConnectionStateChangedHandler);
2574 #ifdef WITH_PRESENCE
2575 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2576 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2577 presenceResource.presenceTTL = 0;
2578 presenceState = OC_PRESENCE_UNINITIALIZED;
2579 #endif // WITH_PRESENCE
2581 #ifdef ROUTING_GATEWAY
2582 if (OC_GATEWAY == myStackMode)
2589 OCTerminateKeepAlive(myStackMode);
2592 TerminateScheduleResourceList();
2593 // Remove all observers
2594 DeleteObserverList();
2595 // Free memory dynamically allocated for resources
2596 deleteAllResources();
2597 // Remove all the client callbacks
2598 DeleteClientCBList();
2599 // Terminate connectivity-abstraction layer.
2602 // De-init the SRM Policy Engine
2603 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2604 SRMDeInitPolicyEngine();
2606 // Destroy Observer List Mutex
2607 TerminateObserverList();
2609 stackState = OC_STACK_UNINITIALIZED;
2613 OCStackResult OCStartMulticastServer()
2615 if(stackState != OC_STACK_INITIALIZED)
2617 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2618 return OC_STACK_ERROR;
2620 CAResult_t ret = CAStartListeningServer();
2621 if (CA_STATUS_OK != ret)
2623 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2624 return OC_STACK_ERROR;
2629 OCStackResult OCStopMulticastServer()
2631 CAResult_t ret = CAStopListeningServer();
2632 if (CA_STATUS_OK != ret)
2634 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2635 return OC_STACK_ERROR;
2640 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2645 return CA_MSG_CONFIRM;
2650 return CA_MSG_NONCONFIRM;
2654 OCStackResult ParseRequestUri(const char *fullUri,
2655 OCTransportAdapter adapter,
2656 OCTransportFlags flags,
2657 OCDevAddr **devAddr,
2659 char **resourceType)
2661 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2663 OCStackResult result = OC_STACK_OK;
2664 OCDevAddr *da = NULL;
2668 // provide defaults for all returned values
2675 *resourceUri = NULL;
2679 *resourceType = NULL;
2682 // delimit url prefix, if any
2683 const char *start = fullUri;
2684 char *slash2 = strstr(start, "//");
2689 char *slash = strchr(start, '/');
2692 return OC_STACK_INVALID_URI;
2695 // process url scheme
2696 size_t prefixLen = slash2 - fullUri;
2700 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2701 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2707 // TODO: this logic should come in with unit tests exercising the various strings
2708 // processs url prefix, if any
2709 size_t urlLen = slash - start;
2713 if (urlLen && devAddr)
2714 { // construct OCDevAddr
2715 if (start[0] == '[')
2717 char *close = strchr(++start, ']');
2718 if (!close || close > slash)
2720 return OC_STACK_INVALID_URI;
2723 if (close[1] == ':')
2730 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2734 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2736 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2740 char *dot = strchr(start, '.');
2741 if (dot && dot < slash)
2743 colon = strchr(start, ':');
2744 end = (colon && colon < slash) ? colon : slash;
2749 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2753 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2755 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2763 if (len >= sizeof(da->addr))
2765 return OC_STACK_INVALID_URI;
2767 // collect port, if any
2768 if (colon && colon < slash)
2770 for (colon++; colon < slash; colon++)
2773 if (c < '0' || c > '9')
2775 return OC_STACK_INVALID_URI;
2777 port = 10 * port + c - '0';
2782 if (len >= sizeof(da->addr))
2784 return OC_STACK_INVALID_URI;
2787 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2790 return OC_STACK_NO_MEMORY;
2793 // Decode address per RFC 6874.
2794 result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2795 if (result != OC_STACK_OK)
2802 da->adapter = adapter;
2804 if (!strncmp(fullUri, "coaps", 5))
2806 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2811 // process resource uri, if any
2813 { // request uri and query
2814 size_t ulen = strlen(slash); // resource uri length
2815 size_t tlen = 0; // resource type length
2818 static const char strPresence[] = "/oic/ad?rt=";
2819 static const size_t lenPresence = sizeof(strPresence) - 1;
2820 if (!strncmp(slash, strPresence, lenPresence))
2822 type = slash + lenPresence;
2823 tlen = ulen - lenPresence;
2828 *resourceUri = (char *)OICMalloc(ulen + 1);
2831 result = OC_STACK_NO_MEMORY;
2834 OICStrcpy(*resourceUri, (ulen + 1), slash);
2837 if (type && resourceType)
2839 *resourceType = (char *)OICMalloc(tlen + 1);
2842 result = OC_STACK_NO_MEMORY;
2846 OICStrcpy(*resourceType, (tlen+1), type);
2853 // free all returned values
2860 OICFree(*resourceUri);
2864 OICFree(*resourceType);
2869 #ifdef WITH_PRESENCE
2870 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2874 char uri[CA_MAX_URI_LENGTH];
2876 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2878 *requestUri = OICStrdup(uri);
2881 return OC_STACK_NO_MEMORY;
2886 #endif // WITH_PRESENCE
2889 * Discover or Perform requests on a specified resource
2891 OCStackResult OCDoResource(OCDoHandle *handle,
2893 const char *requestUri,
2894 const OCDevAddr *destination,
2896 OCConnectivityType connectivityType,
2897 OCQualityOfService qos,
2898 OCCallbackData *cbData,
2899 OCHeaderOption *options,
2902 OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
2903 connectivityType, qos, cbData, options, numOptions);
2905 // This is the owner of the payload object, so we free it
2906 OCPayloadDestroy(payload);
2911 * Discover or Perform requests on a specified resource
2913 OCStackResult OCDoRequest(OCDoHandle *handle,
2915 const char *requestUri,
2916 const OCDevAddr *destination,
2918 OCConnectivityType connectivityType,
2919 OCQualityOfService qos,
2920 OCCallbackData *cbData,
2921 OCHeaderOption *options,
2924 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2925 OIC_TRACE_BEGIN(%s:OCDoRequest, TAG);
2927 // Validate input parameters
2928 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2929 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2931 OCStackResult result = OC_STACK_ERROR;
2932 CAResult_t caResult;
2933 CAToken_t token = NULL;
2934 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2935 ClientCB *clientCB = NULL;
2936 OCDoHandle resHandle = NULL;
2937 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2938 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2940 OCTransportAdapter adapter;
2941 OCTransportFlags flags;
2942 // the request contents are put here
2943 CARequestInfo_t requestInfo = {.method = CA_GET};
2944 // requestUri will be parsed into the following three variables
2945 OCDevAddr *devAddr = NULL;
2946 char *resourceUri = NULL;
2947 char *resourceType = NULL;
2950 * Support original behavior with address on resourceUri argument.
2952 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2953 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2957 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2958 if (result != OC_STACK_OK)
2960 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2964 else if (!checkProxyUri(options, numOptions))
2966 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2973 case OC_REST_OBSERVE:
2974 case OC_REST_OBSERVE_ALL:
2975 requestInfo.method = CA_GET;
2978 requestInfo.method = CA_PUT;
2981 requestInfo.method = CA_POST;
2983 case OC_REST_DELETE:
2984 requestInfo.method = CA_DELETE;
2986 case OC_REST_DISCOVER:
2987 #ifdef WITH_PRESENCE
2988 case OC_REST_PRESENCE:
2990 if (destination || devAddr)
2992 requestInfo.isMulticast = false;
2996 tmpDevAddr.adapter = adapter;
2997 tmpDevAddr.flags = flags;
2998 destination = &tmpDevAddr;
2999 requestInfo.isMulticast = true;
3002 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
3003 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
3004 // replacing method type with GET.
3005 requestInfo.method = CA_GET;
3008 result = OC_STACK_INVALID_METHOD;
3012 if (!devAddr && !destination)
3014 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
3015 result = OC_STACK_INVALID_PARAM;
3019 /* If not original behavior, use destination argument */
3020 if (destination && !devAddr)
3022 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
3025 result = OC_STACK_NO_MEMORY;
3028 OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
3029 *devAddr = *destination;
3034 OIC_LOG_V(INFO_PRIVATE, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
3035 if (!requestInfo.isMulticast)
3037 OIC_LOG_V(DEBUG, TAG, "remoteAddr of devAddr : [%s]:[%d]",
3038 devAddr->addr, devAddr->port);
3042 resHandle = GenerateInvocationHandle();
3045 result = OC_STACK_NO_MEMORY;
3049 caResult = CAGenerateToken(&token, tokenLength);
3050 if (caResult != CA_STATUS_OK)
3052 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3053 result= OC_STACK_ERROR;
3057 // fill in request data
3058 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3059 requestInfo.info.token = token;
3060 requestInfo.info.tokenLength = tokenLength;
3062 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3064 result = CreateObserveHeaderOption (&(requestInfo.info.options),
3065 options, numOptions, OC_OBSERVE_REGISTER);
3066 if (result != OC_STACK_OK)
3070 requestInfo.info.numOptions = numOptions + 1;
3074 requestInfo.info.numOptions = numOptions;
3075 requestInfo.info.options =
3076 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3077 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3078 numOptions * sizeof(CAHeaderOption_t));
3081 CopyDevAddrToEndpoint(devAddr, &endpoint);
3086 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3089 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3092 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3096 requestInfo.info.payload = NULL;
3097 requestInfo.info.payloadSize = 0;
3098 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3101 // prepare for response
3102 #ifdef WITH_PRESENCE
3103 if (method == OC_REST_PRESENCE)
3105 char *presenceUri = NULL;
3106 result = OCPreparePresence(&endpoint, &presenceUri,
3107 requestInfo.isMulticast);
3108 if (OC_STACK_OK != result)
3113 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3114 // Presence notification will form a canonical uri to
3115 // look for callbacks into the application.
3118 OICFree(resourceUri);
3120 resourceUri = presenceUri;
3124 // update resourceUri onto requestInfo after check presence uri
3125 requestInfo.info.resourceUri = resourceUri;
3127 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3128 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3129 method, devAddr, resourceUri, resourceType, ttl);
3130 if (OC_STACK_OK != result)
3135 cbData = NULL; // Client CB list entry now owns it
3136 token = NULL; // Client CB list entry now owns it
3137 devAddr = NULL; // Client CB list entry now owns it
3138 resourceUri = NULL; // Client CB list entry now owns it
3139 resourceType = NULL; // Client CB list entry now owns it
3141 #ifdef WITH_PRESENCE
3142 if (method == OC_REST_PRESENCE)
3144 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3148 *handle = resHandle;
3156 result = OCSendRequest(&endpoint, &requestInfo);
3157 if (OC_STACK_OK != result)
3164 *handle = resHandle;
3168 if (result != OC_STACK_OK)
3170 OIC_LOG(ERROR, TAG, "OCDoResource error");
3171 if (NULL != cbData && NULL != cbData->cd)
3173 cbData->cd(cbData->context);
3175 FindAndDeleteClientCB(clientCB);
3176 CADestroyToken(token);
3184 OICFree(requestInfo.info.payload);
3186 OICFree(resourceUri);
3187 OICFree(resourceType);
3188 OICFree(requestInfo.info.options);
3193 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3197 * This ftn is implemented one of two ways in the case of observation:
3199 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3200 * Remove the callback associated on client side.
3201 * When the next notification comes in from server,
3202 * reply with RESET message to server.
3203 * Keep in mind that the server will react to RESET only
3204 * if the last notification was sent as CON
3206 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3207 * and it is associated with an observe request
3208 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3209 * Send CON Observe request to server with
3210 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3211 * Remove the callback associated on client side.
3213 OCStackResult ret = OC_STACK_OK;
3214 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3215 CARequestInfo_t requestInfo = {.method = CA_GET};
3219 return OC_STACK_INVALID_PARAM;
3222 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3225 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3226 return OC_STACK_ERROR;
3229 switch (clientCB->method)
3231 case OC_REST_OBSERVE:
3232 case OC_REST_OBSERVE_ALL:
3234 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3236 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3238 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
3240 FindAndDeleteClientCB(clientCB);
3244 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3246 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3247 requestInfo.info.token = clientCB->token;
3248 requestInfo.info.tokenLength = clientCB->tokenLength;
3250 if (CreateObserveHeaderOption (&(requestInfo.info.options),
3251 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3253 return OC_STACK_ERROR;
3255 requestInfo.info.numOptions = numOptions + 1;
3256 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3259 ret = OCSendRequest(&endpoint, &requestInfo);
3261 if (requestInfo.info.options)
3263 OICFree (requestInfo.info.options);
3265 if (requestInfo.info.resourceUri)
3267 OICFree (requestInfo.info.resourceUri);
3272 case OC_REST_DISCOVER:
3273 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3274 clientCB->requestUri);
3275 FindAndDeleteClientCB(clientCB);
3278 #ifdef WITH_PRESENCE
3279 case OC_REST_PRESENCE:
3280 FindAndDeleteClientCB(clientCB);
3286 case OC_REST_DELETE:
3287 OIC_LOG_V(INFO, TAG, "Cancelling request callback for resource %s",
3288 clientCB->requestUri);
3289 FindAndDeleteClientCB(clientCB);
3293 ret = OC_STACK_INVALID_METHOD;
3301 * @brief Register Persistent storage callback.
3302 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3304 * OC_STACK_OK - No errors; Success
3305 * OC_STACK_INVALID_PARAM - Invalid parameter
3307 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3309 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3310 if(!persistentStorageHandler)
3312 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3313 return OC_STACK_INVALID_PARAM;
3317 if( !persistentStorageHandler->open ||
3318 !persistentStorageHandler->close ||
3319 !persistentStorageHandler->read ||
3320 !persistentStorageHandler->unlink ||
3321 !persistentStorageHandler->write)
3323 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3324 return OC_STACK_INVALID_PARAM;
3327 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3330 #ifdef WITH_PRESENCE
3332 OCStackResult OCProcessPresence()
3334 OCStackResult result = OC_STACK_OK;
3336 // the following line floods the log with messages that are irrelevant
3337 // to most purposes. Uncomment as needed.
3338 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3339 ClientCB* cbNode = NULL;
3340 OCClientResponse clientResponse;
3341 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3343 LL_FOREACH(cbList, cbNode)
3345 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3350 uint32_t now = GetTicks(0);
3351 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3352 cbNode->presence->TTLlevel);
3353 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3355 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3360 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3362 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3363 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3365 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3367 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3369 clientResponse.sequenceNumber = 0;
3370 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3371 clientResponse.devAddr = *cbNode->devAddr;
3372 FixUpClientResponse(&clientResponse);
3373 clientResponse.payload = NULL;
3375 // Increment the TTLLevel (going to a next state), so we don't keep
3376 // sending presence notification to client.
3377 cbNode->presence->TTLlevel++;
3378 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3379 cbNode->presence->TTLlevel);
3381 OIC_LOG(INFO, TAG, "Before calling into application address space for presence timeout");
3382 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3383 OIC_LOG(INFO, TAG, "After calling into application address space for presence timeout");
3385 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3387 FindAndDeleteClientCB(cbNode);
3391 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3396 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3397 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3398 CARequestInfo_t requestInfo = {.method = CA_GET};
3400 OIC_LOG(DEBUG, TAG, "time to test server presence");
3402 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3404 requestData.type = CA_MSG_NONCONFIRM;
3405 requestData.token = cbNode->token;
3406 requestData.tokenLength = cbNode->tokenLength;
3407 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3408 requestInfo.method = CA_GET;
3409 requestInfo.info = requestData;
3411 result = OCSendRequest(&endpoint, &requestInfo);
3412 if (OC_STACK_OK != result)
3417 cbNode->presence->TTLlevel++;
3418 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3421 if (result != OC_STACK_OK)
3423 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3428 #endif // WITH_PRESENCE
3430 OCStackResult OCProcess()
3432 if (stackState == OC_STACK_UNINITIALIZED)
3434 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3435 return OC_STACK_ERROR;
3437 #ifdef WITH_PRESENCE
3438 OCProcessPresence();
3440 CAHandleRequestResponse();
3442 #ifdef ROUTING_GATEWAY
3447 OCProcessKeepAlive();
3452 #ifdef WITH_PRESENCE
3453 OCStackResult OCStartPresence(const uint32_t ttl)
3455 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3456 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3457 OCChangeResourceProperty(
3458 &(((OCResource *)presenceResource.handle)->resourceProperties),
3461 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3463 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3464 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3468 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3469 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3473 presenceResource.presenceTTL = ttl;
3476 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3479 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3481 presenceState = OC_PRESENCE_INITIALIZED;
3483 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3485 CAToken_t caToken = NULL;
3486 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3487 if (caResult != CA_STATUS_OK)
3489 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3490 CADestroyToken(caToken);
3491 return OC_STACK_ERROR;
3494 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3495 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3496 CADestroyToken(caToken);
3499 // Each time OCStartPresence is called
3500 // a different random 32-bit integer number is used
3501 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3503 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3504 OC_PRESENCE_TRIGGER_CREATE);
3507 OCStackResult OCStopPresence()
3509 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3510 OCStackResult result = OC_STACK_ERROR;
3512 if(presenceResource.handle)
3514 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3516 // make resource inactive
3517 result = OCChangeResourceProperty(
3518 &(((OCResource *) presenceResource.handle)->resourceProperties),
3522 if(result != OC_STACK_OK)
3525 "Changing the presence resource properties to ACTIVE not successful");
3529 return SendStopNotification();
3533 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3534 void* callbackParameter)
3536 defaultDeviceHandler = entityHandler;
3537 defaultDeviceHandlerCallbackParameter = callbackParameter;
3542 OCStackResult OCCreateResource(OCResourceHandle *handle,
3543 const char *resourceTypeName,
3544 const char *resourceInterfaceName,
3545 const char *uri, OCEntityHandler entityHandler,
3546 void* callbackParam,
3547 uint8_t resourceProperties)
3550 OCResource *pointer = NULL;
3551 OCStackResult result = OC_STACK_ERROR;
3553 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3555 if(myStackMode == OC_CLIENT)
3557 return OC_STACK_INVALID_PARAM;
3559 // Validate parameters
3560 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3562 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3563 return OC_STACK_INVALID_URI;
3565 // Is it presented during resource discovery?
3566 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3568 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3569 return OC_STACK_INVALID_PARAM;
3572 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3574 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3578 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3580 // Make sure resourceProperties bitmask has allowed properties specified
3581 if (resourceProperties
3582 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3583 OC_EXPLICIT_DISCOVERABLE
3592 OIC_LOG(ERROR, TAG, "Invalid property");
3593 return OC_STACK_INVALID_PARAM;
3596 // If the headResource is NULL, then no resources have been created...
3597 pointer = headResource;
3600 // At least one resources is in the resource list, so we need to search for
3601 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3604 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3606 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3607 return OC_STACK_INVALID_PARAM;
3609 pointer = pointer->next;
3612 // Create the pointer and insert it into the resource list
3613 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3616 result = OC_STACK_NO_MEMORY;
3619 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3621 insertResource(pointer);
3624 pointer->uri = OICStrdup(uri);
3627 result = OC_STACK_NO_MEMORY;
3631 // Set properties. Set OC_ACTIVE
3632 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3635 // Add the resourcetype to the resource
3636 result = BindResourceTypeToResource(pointer, resourceTypeName);
3637 if (result != OC_STACK_OK)
3639 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3643 // Add the resourceinterface to the resource
3644 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3645 if (result != OC_STACK_OK)
3647 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3651 // If an entity handler has been passed, attach it to the newly created
3652 // resource. Otherwise, set the default entity handler.
3655 pointer->entityHandler = entityHandler;
3656 pointer->entityHandlerCallbackParam = callbackParam;
3660 pointer->entityHandler = defaultResourceEHandler;
3661 pointer->entityHandlerCallbackParam = NULL;
3664 // Initialize a pointer indicating child resources in case of collection
3665 pointer->rsrcChildResourcesHead = NULL;
3668 result = OC_STACK_OK;
3670 #ifdef WITH_PRESENCE
3671 if (presenceResource.handle)
3673 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3674 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3678 if (result != OC_STACK_OK)
3680 // Deep delete of resource and other dynamic elements that it contains
3681 deleteResource(pointer);
3686 OCStackResult OCBindResource(
3687 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3689 OCResource *resource = NULL;
3690 OCChildResource *tempChildResource = NULL;
3691 OCChildResource *newChildResource = NULL;
3693 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3695 // Validate parameters
3696 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3697 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3698 // Container cannot contain itself
3699 if (collectionHandle == resourceHandle)
3701 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3702 return OC_STACK_INVALID_PARAM;
3705 // Use the handle to find the resource in the resource linked list
3706 resource = findResource((OCResource *) collectionHandle);
3709 OIC_LOG(ERROR, TAG, "Collection handle not found");
3710 return OC_STACK_INVALID_PARAM;
3713 // Look for an open slot to add add the child resource.
3714 // If found, add it and return success
3716 tempChildResource = resource->rsrcChildResourcesHead;
3718 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3720 // TODO: what if one of child resource was deregistered without unbinding?
3721 tempChildResource = tempChildResource->next;
3724 // Do memory allocation for child resource
3725 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3726 if(!newChildResource)
3728 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3729 return OC_STACK_ERROR;
3732 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3733 newChildResource->next = NULL;
3735 if(!resource->rsrcChildResourcesHead)
3737 resource->rsrcChildResourcesHead = newChildResource;
3740 tempChildResource->next = newChildResource;
3743 OIC_LOG(INFO, TAG, "resource bound");
3745 #ifdef WITH_PRESENCE
3746 if (presenceResource.handle)
3748 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3749 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3750 OC_PRESENCE_TRIGGER_CHANGE);
3757 OCStackResult OCUnBindResource(
3758 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3760 OCResource *resource = NULL;
3761 OCChildResource *tempChildResource = NULL;
3762 OCChildResource *tempLastChildResource = NULL;
3764 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3766 // Validate parameters
3767 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3768 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3769 // Container cannot contain itself
3770 if (collectionHandle == resourceHandle)
3772 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3773 return OC_STACK_INVALID_PARAM;
3776 // Use the handle to find the resource in the resource linked list
3777 resource = findResource((OCResource *) collectionHandle);
3780 OIC_LOG(ERROR, TAG, "Collection handle not found");
3781 return OC_STACK_INVALID_PARAM;
3784 // Look for an open slot to add add the child resource.
3785 // If found, add it and return success
3786 if(!resource->rsrcChildResourcesHead)
3788 OIC_LOG(INFO, TAG, "resource not found in collection");
3790 // Unable to add resourceHandle, so return error
3791 return OC_STACK_ERROR;
3795 tempChildResource = resource->rsrcChildResourcesHead;
3797 while (tempChildResource)
3799 if(tempChildResource->rsrcResource == resourceHandle)
3801 // if resource going to be unbinded is the head one.
3802 if( tempChildResource == resource->rsrcChildResourcesHead )
3804 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3805 OICFree(resource->rsrcChildResourcesHead);
3806 resource->rsrcChildResourcesHead = temp;
3811 OCChildResource *temp = tempChildResource->next;
3812 OICFree(tempChildResource);
3813 if (tempLastChildResource)
3815 tempLastChildResource->next = temp;
3820 OIC_LOG(INFO, TAG, "resource unbound");
3822 // Send notification when resource is unbounded successfully.
3823 #ifdef WITH_PRESENCE
3824 if (presenceResource.handle)
3826 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3827 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3828 OC_PRESENCE_TRIGGER_CHANGE);
3831 tempChildResource = NULL;
3832 tempLastChildResource = NULL;
3838 tempLastChildResource = tempChildResource;
3839 tempChildResource = tempChildResource->next;
3842 OIC_LOG(INFO, TAG, "resource not found in collection");
3844 tempChildResource = NULL;
3845 tempLastChildResource = NULL;
3847 // Unable to add resourceHandle, so return error
3848 return OC_STACK_ERROR;
3851 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3853 if (!resourceItemName)
3857 // Per RFC 6690 only registered values must follow the first rule below.
3858 // At this point in time the only values registered begin with "core", and
3859 // all other values are specified as opaque strings where multiple values
3860 // are separated by a space.
3861 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3863 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3865 if (resourceItemName[index] != '.'
3866 && resourceItemName[index] != '-'
3867 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3868 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3876 for (size_t index = 0; resourceItemName[index]; ++index)
3878 if (resourceItemName[index] == ' '
3879 || resourceItemName[index] == '\t'
3880 || resourceItemName[index] == '\r'
3881 || resourceItemName[index] == '\n')
3891 OCStackResult BindResourceTypeToResource(OCResource* resource,
3892 const char *resourceTypeName)
3894 OCResourceType *pointer = NULL;
3896 OCStackResult result = OC_STACK_ERROR;
3898 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3900 if (!ValidateResourceTypeInterface(resourceTypeName))
3902 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3903 return OC_STACK_INVALID_PARAM;
3906 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3909 result = OC_STACK_NO_MEMORY;
3913 str = OICStrdup(resourceTypeName);
3916 result = OC_STACK_NO_MEMORY;
3919 pointer->resourcetypename = str;
3920 pointer->next = NULL;
3922 insertResourceType(resource, pointer);
3923 result = OC_STACK_OK;
3926 if (result != OC_STACK_OK)
3935 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3936 const char *resourceInterfaceName)
3938 OCResourceInterface *pointer = NULL;
3940 OCStackResult result = OC_STACK_ERROR;
3942 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3944 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3946 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3947 return OC_STACK_INVALID_PARAM;
3950 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3952 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3955 result = OC_STACK_NO_MEMORY;
3959 str = OICStrdup(resourceInterfaceName);
3962 result = OC_STACK_NO_MEMORY;
3965 pointer->name = str;
3967 // Bind the resourceinterface to the resource
3968 insertResourceInterface(resource, pointer);
3970 result = OC_STACK_OK;
3973 if (result != OC_STACK_OK)
3982 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3983 const char *resourceTypeName)
3986 OCStackResult result = OC_STACK_ERROR;
3987 OCResource *resource = NULL;
3989 resource = findResource((OCResource *) handle);
3992 OIC_LOG(ERROR, TAG, "Resource not found");
3993 return OC_STACK_ERROR;
3996 result = BindResourceTypeToResource(resource, resourceTypeName);
3998 #ifdef WITH_PRESENCE
3999 if(presenceResource.handle)
4001 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4002 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4009 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
4010 const char *resourceInterfaceName)
4013 OCStackResult result = OC_STACK_ERROR;
4014 OCResource *resource = NULL;
4016 resource = findResource((OCResource *) handle);
4019 OIC_LOG(ERROR, TAG, "Resource not found");
4020 return OC_STACK_ERROR;
4023 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
4025 #ifdef WITH_PRESENCE
4026 if (presenceResource.handle)
4028 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4029 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4036 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
4038 OCResource *pointer = headResource;
4040 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
4044 *numResources = *numResources + 1;
4045 pointer = pointer->next;
4050 OCResourceHandle OCGetResourceHandle(uint8_t index)
4052 OCResource *pointer = headResource;
4054 for( uint8_t i = 0; i < index && pointer; ++i)
4056 pointer = pointer->next;
4058 return (OCResourceHandle) pointer;
4061 OCStackResult OCDeleteResource(OCResourceHandle handle)
4065 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4066 return OC_STACK_INVALID_PARAM;
4069 OCResource *resource = findResource((OCResource *) handle);
4070 if (resource == NULL)
4072 OIC_LOG(ERROR, TAG, "Resource not found");
4073 return OC_STACK_NO_RESOURCE;
4076 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4078 OIC_LOG(ERROR, TAG, "Error deleting resource");
4079 return OC_STACK_ERROR;
4085 const char *OCGetResourceUri(OCResourceHandle handle)
4087 OCResource *resource = NULL;
4089 resource = findResource((OCResource *) handle);
4092 return resource->uri;
4094 return (const char *) NULL;
4097 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4099 OCResource *resource = NULL;
4101 resource = findResource((OCResource *) handle);
4104 return resource->resourceProperties;
4106 return (OCResourceProperty)-1;
4109 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4110 uint8_t *numResourceTypes)
4112 OCResource *resource = NULL;
4113 OCResourceType *pointer = NULL;
4115 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4116 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4118 *numResourceTypes = 0;
4120 resource = findResource((OCResource *) handle);
4123 pointer = resource->rsrcType;
4126 *numResourceTypes = *numResourceTypes + 1;
4127 pointer = pointer->next;
4133 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4135 OCResourceType *resourceType = NULL;
4137 resourceType = findResourceTypeAtIndex(handle, index);
4140 return resourceType->resourcetypename;
4142 return (const char *) NULL;
4145 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4146 uint8_t *numResourceInterfaces)
4148 OCResourceInterface *pointer = NULL;
4149 OCResource *resource = NULL;
4151 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4152 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4154 *numResourceInterfaces = 0;
4155 resource = findResource((OCResource *) handle);
4158 pointer = resource->rsrcInterface;
4161 *numResourceInterfaces = *numResourceInterfaces + 1;
4162 pointer = pointer->next;
4168 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4170 OCResourceInterface *resourceInterface = NULL;
4172 resourceInterface = findResourceInterfaceAtIndex(handle, index);
4173 if (resourceInterface)
4175 return resourceInterface->name;
4177 return (const char *) NULL;
4180 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4183 OCResource *resource = NULL;
4184 OCChildResource *tempChildResource = NULL;
4187 resource = findResource((OCResource *) collectionHandle);
4193 tempChildResource = resource->rsrcChildResourcesHead;
4195 while(tempChildResource)
4199 return tempChildResource->rsrcResource;
4202 tempChildResource = tempChildResource->next;
4205 // In this case, the number of resource handles in the collection exceeds the index
4206 tempChildResource = NULL;
4210 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4211 OCEntityHandler entityHandler,
4212 void* callbackParam)
4214 OCResource *resource = NULL;
4216 // Validate parameters
4217 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4219 // Use the handle to find the resource in the resource linked list
4220 resource = findResource((OCResource *)handle);
4223 OIC_LOG(ERROR, TAG, "Resource not found");
4224 return OC_STACK_ERROR;
4228 resource->entityHandler = entityHandler;
4229 resource->entityHandlerCallbackParam = callbackParam;
4231 #ifdef WITH_PRESENCE
4232 if (presenceResource.handle)
4234 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4235 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4242 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4244 OCResource *resource = NULL;
4246 resource = findResource((OCResource *)handle);
4249 OIC_LOG(ERROR, TAG, "Resource not found");
4254 return resource->entityHandler;
4257 void incrementSequenceNumber(OCResource * resPtr)
4259 // Increment the sequence number
4260 resPtr->sequenceNum += 1;
4261 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4263 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4268 #ifdef WITH_PRESENCE
4269 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4270 OCPresenceTrigger trigger)
4272 OIC_LOG(INFO, TAG, "SendPresenceNotification");
4273 OCResource *resPtr = NULL;
4274 OCStackResult result = OC_STACK_ERROR;
4275 OCMethod method = OC_REST_PRESENCE;
4276 uint32_t maxAge = 0;
4277 resPtr = findResource((OCResource *) presenceResource.handle);
4280 return OC_STACK_NO_RESOURCE;
4283 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4285 maxAge = presenceResource.presenceTTL;
4287 result = SendAllObserverNotification(method, resPtr, maxAge,
4288 trigger, resourceType, OC_LOW_QOS);
4294 OCStackResult SendStopNotification()
4296 OIC_LOG(INFO, TAG, "SendStopNotification");
4297 OCResource *resPtr = NULL;
4298 OCStackResult result = OC_STACK_ERROR;
4299 OCMethod method = OC_REST_PRESENCE;
4300 resPtr = findResource((OCResource *) presenceResource.handle);
4303 return OC_STACK_NO_RESOURCE;
4306 // maxAge is 0. ResourceType is NULL.
4307 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4313 #endif // WITH_PRESENCE
4314 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4316 OCResource *resPtr = NULL;
4317 OCStackResult result = OC_STACK_ERROR;
4318 OCMethod method = OC_REST_NOMETHOD;
4319 uint32_t maxAge = 0;
4321 OIC_LOG(INFO, TAG, "Notifying all observers");
4322 #ifdef WITH_PRESENCE
4323 if(handle == presenceResource.handle)
4327 #endif // WITH_PRESENCE
4328 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4330 // Verify that the resource exists
4331 resPtr = findResource ((OCResource *) handle);
4334 return OC_STACK_NO_RESOURCE;
4338 //only increment in the case of regular observing (not presence)
4339 incrementSequenceNumber(resPtr);
4340 method = OC_REST_OBSERVE;
4341 maxAge = MAX_OBSERVE_AGE;
4342 #ifdef WITH_PRESENCE
4343 result = SendAllObserverNotification (method, resPtr, maxAge,
4344 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4346 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4353 OCNotifyListOfObservers (OCResourceHandle handle,
4354 OCObservationId *obsIdList,
4355 uint8_t numberOfIds,
4356 const OCRepPayload *payload,
4357 OCQualityOfService qos)
4359 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4361 OCResource *resPtr = NULL;
4362 //TODO: we should allow the server to define this
4363 uint32_t maxAge = MAX_OBSERVE_AGE;
4365 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4366 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4367 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4369 resPtr = findResource ((OCResource *) handle);
4370 if (NULL == resPtr || myStackMode == OC_CLIENT)
4372 return OC_STACK_NO_RESOURCE;
4376 incrementSequenceNumber(resPtr);
4378 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4379 payload, maxAge, qos));
4382 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4384 OIC_TRACE_BEGIN(%s:OCDoResponse, TAG);
4385 OCStackResult result = OC_STACK_ERROR;
4386 OCServerRequest *serverRequest = NULL;
4388 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4390 // Validate input parameters
4391 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4392 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4395 // Get pointer to request info
4396 serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
4399 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4400 result = serverRequest->ehResponseHandler(ehResponse);
4407 //#ifdef DIRECT_PAIRING
4408 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4410 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4411 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4413 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4417 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4420 const OCDPDev_t* OCGetDirectPairedDevices()
4422 return (const OCDPDev_t*)DPGetPairedDevices();
4425 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4426 OCDirectPairingCB resultCallback)
4428 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4429 if(NULL == peer || NULL == pinNumber)
4431 OIC_LOG(ERROR, TAG, "Invalid parameters");
4432 return OC_STACK_INVALID_PARAM;
4434 if (NULL == resultCallback)
4436 OIC_LOG(ERROR, TAG, "Invalid callback");
4437 return OC_STACK_INVALID_CALLBACK;
4440 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4441 pinNumber, (OCDirectPairingResultCB)resultCallback);
4443 //#endif // DIRECT_PAIRING
4445 //-----------------------------------------------------------------------------
4446 // Private internal function definitions
4447 //-----------------------------------------------------------------------------
4448 static OCDoHandle GenerateInvocationHandle()
4450 OCDoHandle handle = NULL;
4451 // Generate token here, it will be deleted when the transaction is deleted
4452 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4455 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4461 #ifdef WITH_PRESENCE
4462 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4463 OCResourceProperty resourceProperties, uint8_t enable)
4467 return OC_STACK_INVALID_PARAM;
4469 if (resourceProperties
4470 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4472 OIC_LOG(ERROR, TAG, "Invalid property");
4473 return OC_STACK_INVALID_PARAM;
4477 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4481 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4487 OCStackResult initResources()
4489 OCStackResult result = OC_STACK_OK;
4491 headResource = NULL;
4492 tailResource = NULL;
4493 // Init Virtual Resources
4494 #ifdef WITH_PRESENCE
4495 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4497 result = OCCreateResource(&presenceResource.handle,
4498 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4500 OC_RSRVD_PRESENCE_URI,
4504 //make resource inactive
4505 result = OCChangeResourceProperty(
4506 &(((OCResource *) presenceResource.handle)->resourceProperties),
4509 #ifndef WITH_ARDUINO
4510 if (result == OC_STACK_OK)
4512 result = SRMInitSecureResources();
4516 if(result == OC_STACK_OK)
4518 CreateResetProfile();
4519 result = OCCreateResource(&deviceResource,
4520 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4521 OC_RSRVD_INTERFACE_DEFAULT,
4522 OC_RSRVD_DEVICE_URI,
4526 if(result == OC_STACK_OK)
4528 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4529 OC_RSRVD_INTERFACE_READ);
4533 if(result == OC_STACK_OK)
4535 result = OCCreateResource(&platformResource,
4536 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4537 OC_RSRVD_INTERFACE_DEFAULT,
4538 OC_RSRVD_PLATFORM_URI,
4542 if(result == OC_STACK_OK)
4544 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4545 OC_RSRVD_INTERFACE_READ);
4552 void insertResource(OCResource *resource)
4556 headResource = resource;
4557 tailResource = resource;
4561 tailResource->next = resource;
4562 tailResource = resource;
4564 resource->next = NULL;
4567 OCResource *findResource(OCResource *resource)
4569 OCResource *pointer = headResource;
4573 if (pointer == resource)
4577 pointer = pointer->next;
4582 void deleteAllResources()
4584 OCResource *pointer = headResource;
4585 OCResource *temp = NULL;
4589 temp = pointer->next;
4590 #ifdef WITH_PRESENCE
4591 if (pointer != (OCResource *) presenceResource.handle)
4593 #endif // WITH_PRESENCE
4594 deleteResource(pointer);
4595 #ifdef WITH_PRESENCE
4597 #endif // WITH_PRESENCE
4600 memset(&platformResource, 0, sizeof(platformResource));
4601 memset(&deviceResource, 0, sizeof(deviceResource));
4603 memset(&brokerResource, 0, sizeof(brokerResource));
4606 SRMDeInitSecureResources();
4608 #ifdef WITH_PRESENCE
4609 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4610 // presence notification attributed to their deletion to be processed.
4611 deleteResource((OCResource *) presenceResource.handle);
4612 memset(&presenceResource, 0, sizeof(presenceResource));
4613 #endif // WITH_PRESENCE
4616 OCStackResult deleteResource(OCResource *resource)
4618 OCResource *prev = NULL;
4619 OCResource *temp = NULL;
4622 OIC_LOG(DEBUG,TAG,"resource is NULL");
4623 return OC_STACK_INVALID_PARAM;
4626 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4628 temp = headResource;
4631 if (temp == resource)
4633 // Invalidate all Resource Properties.
4634 resource->resourceProperties = (OCResourceProperty) 0;
4635 #ifdef WITH_PRESENCE
4636 if(resource != (OCResource *) presenceResource.handle)
4638 #endif // WITH_PRESENCE
4639 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4640 #ifdef WITH_PRESENCE
4643 if(presenceResource.handle)
4645 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4646 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4649 // Only resource in list.
4650 if (temp == headResource && temp == tailResource)
4652 headResource = NULL;
4653 tailResource = NULL;
4656 else if (temp == headResource)
4658 headResource = temp->next;
4661 else if (temp == tailResource && prev)
4663 tailResource = prev;
4664 tailResource->next = NULL;
4668 prev->next = temp->next;
4671 deleteResourceElements(temp);
4682 return OC_STACK_ERROR;
4685 void deleteResourceElements(OCResource *resource)
4694 OICFree(resource->uri);
4695 resource->uri = NULL;
4697 if (resource->rsrcType)
4699 deleteResourceType(resource->rsrcType);
4700 resource->rsrcType = NULL;
4702 if (resource->rsrcInterface)
4704 deleteResourceInterface(resource->rsrcInterface);
4705 resource->rsrcInterface = NULL;
4707 if (resource->rsrcChildResourcesHead)
4709 unbindChildResources(resource->rsrcChildResourcesHead);
4710 resource->rsrcChildResourcesHead = NULL;
4712 if (resource->rsrcAttributes)
4714 OCDeleteResourceAttributes(resource->rsrcAttributes);
4715 resource->rsrcAttributes = NULL;
4720 void deleteResourceType(OCResourceType *resourceType)
4722 OCResourceType *next = NULL;
4724 for (OCResourceType *pointer = resourceType; pointer; pointer = next)
4726 next = pointer->next ? pointer->next : NULL;
4727 if (pointer->resourcetypename)
4729 OICFree(pointer->resourcetypename);
4730 pointer->resourcetypename = NULL;
4736 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4738 OCResourceInterface *next = NULL;
4739 for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
4741 next = pointer->next ? pointer->next : NULL;
4744 OICFree(pointer->name);
4745 pointer->name = NULL;
4751 void unbindChildResources(OCChildResource *head)
4753 OCChildResource *next = NULL;
4754 for (OCChildResource *current = head; current; current = next)
4756 next = current->next;
4761 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
4763 OCAttribute *next = NULL;
4764 for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
4766 next = pointer->next ? pointer->next : NULL;
4767 if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
4769 OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
4770 pointer->attrValue = NULL;
4772 else if (pointer->attrValue)
4774 OICFree(pointer->attrValue);
4775 pointer->attrValue = NULL;
4777 if (pointer->attrName)
4779 OICFree(pointer->attrName);
4780 pointer->attrName = NULL;
4786 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4788 OCResourceType *pointer = NULL;
4789 OCResourceType *previous = NULL;
4790 if (!resource || !resourceType)
4794 // resource type list is empty.
4795 else if (!resource->rsrcType)
4797 resource->rsrcType = resourceType;
4801 pointer = resource->rsrcType;
4805 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4807 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4808 OICFree(resourceType->resourcetypename);
4809 OICFree(resourceType);
4813 pointer = pointer->next;
4818 previous->next = resourceType;
4821 resourceType->next = NULL;
4823 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4826 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4828 OCResource *resource = NULL;
4829 OCResourceType *pointer = NULL;
4831 // Find the specified resource
4832 resource = findResource((OCResource *) handle);
4838 // Make sure a resource has a resourcetype
4839 if (!resource->rsrcType)
4844 // Iterate through the list
4845 pointer = resource->rsrcType;
4846 for(uint8_t i = 0; i< index && pointer; ++i)
4848 pointer = pointer->next;
4853 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4855 if(resourceTypeList && resourceTypeName)
4857 OCResourceType * rtPointer = resourceTypeList;
4858 while(resourceTypeName && rtPointer)
4860 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4861 if(rtPointer->resourcetypename &&
4862 strcmp(resourceTypeName, (const char *)
4863 (rtPointer->resourcetypename)) == 0)
4867 rtPointer = rtPointer->next;
4875 * Insert a new interface into interface linked list only if not already present.
4876 * If alredy present, 2nd arg is free'd.
4877 * Default interface will always be first if present.
4879 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4881 OCResourceInterface *pointer = NULL;
4882 OCResourceInterface *previous = NULL;
4884 newInterface->next = NULL;
4886 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4888 if (!*firstInterface)
4890 // If first interface is not oic.if.baseline, by default add it as first interface type.
4891 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4893 *firstInterface = newInterface;
4897 OCStackResult result = BindResourceInterfaceToResource(resource,
4898 OC_RSRVD_INTERFACE_DEFAULT);
4899 if (result != OC_STACK_OK)
4901 OICFree(newInterface->name);
4902 OICFree(newInterface);
4905 if (*firstInterface)
4907 (*firstInterface)->next = newInterface;
4911 // If once add oic.if.baseline, later too below code take care of freeing memory.
4912 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4914 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4916 OICFree(newInterface->name);
4917 OICFree(newInterface);
4920 // This code will not hit anymore, keeping
4923 newInterface->next = *firstInterface;
4924 *firstInterface = newInterface;
4929 pointer = *firstInterface;
4932 if (strcmp(newInterface->name, pointer->name) == 0)
4934 OICFree(newInterface->name);
4935 OICFree(newInterface);
4939 pointer = pointer->next;
4944 previous->next = newInterface;
4949 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4952 OCResource *resource = NULL;
4953 OCResourceInterface *pointer = NULL;
4955 // Find the specified resource
4956 resource = findResource((OCResource *) handle);
4962 // Make sure a resource has a resourceinterface
4963 if (!resource->rsrcInterface)
4968 // Iterate through the list
4969 pointer = resource->rsrcInterface;
4971 for (uint8_t i = 0; i < index && pointer; ++i)
4973 pointer = pointer->next;
4979 * This function splits the uri using the '?' delimiter.
4980 * "uriWithoutQuery" is the block of characters between the beginning
4981 * till the delimiter or '\0' which ever comes first.
4982 * "query" is whatever is to the right of the delimiter if present.
4983 * No delimiter sets the query to NULL.
4984 * If either are present, they will be malloc'ed into the params 2, 3.
4985 * The first param, *uri is left untouched.
4987 * NOTE: This function does not account for whitespace at the end of the uri NOR
4988 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4989 * part of the query.
4991 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4995 return OC_STACK_INVALID_URI;
4997 if(!query || !uriWithoutQuery)
4999 return OC_STACK_INVALID_PARAM;
5003 *uriWithoutQuery = NULL;
5005 size_t uriWithoutQueryLen = 0;
5006 size_t queryLen = 0;
5007 size_t uriLen = strlen(uri);
5009 char *pointerToDelimiter = strstr(uri, "?");
5011 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
5012 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
5014 if (uriWithoutQueryLen)
5016 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
5017 if (!*uriWithoutQuery)
5021 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
5025 *query = (char *) OICCalloc(queryLen + 1, 1);
5028 OICFree(*uriWithoutQuery);
5029 *uriWithoutQuery = NULL;
5032 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5038 return OC_STACK_NO_MEMORY;
5041 const char* OCGetServerInstanceIDString(void)
5043 static char sidStr[UUID_STRING_SIZE];
5045 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5047 OIC_LOG(FATAL, TAG, "GetDoxmDeviceID failed!");
5051 if (OCConvertUuidToString(sid.id, sidStr) != RAND_UUID_OK)
5053 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5060 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5062 OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5063 CAResult_t retResult = CA_STATUS_FAILED;
5064 CAResult_t caResult = CA_STATUS_OK;
5066 CATransportAdapter_t connTypes[] = {
5068 CA_ADAPTER_RFCOMM_BTEDR,
5069 CA_ADAPTER_GATT_BTLE,
5072 ,CA_ADAPTER_REMOTE_ACCESS
5079 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5081 for(int i = 0; i < numConnTypes; i++)
5083 // If CA status is not initialized, CASelectNetwork() will not be called.
5084 if (caResult != CA_STATUS_NOT_INITIALIZED)
5086 if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5088 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5089 caResult = CASelectNetwork(connTypes[i]);
5090 if (caResult == CA_STATUS_OK)
5092 retResult = CA_STATUS_OK;
5097 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5102 if (retResult != CA_STATUS_OK)
5104 return caResult; // Returns error of appropriate transport that failed fatally.
5110 OCStackResult CAResultToOCResult(CAResult_t caResult)
5116 case CA_STATUS_INVALID_PARAM:
5117 return OC_STACK_INVALID_PARAM;
5118 case CA_ADAPTER_NOT_ENABLED:
5119 return OC_STACK_ADAPTER_NOT_ENABLED;
5120 case CA_SERVER_STARTED_ALREADY:
5122 case CA_SERVER_NOT_STARTED:
5123 return OC_STACK_ERROR;
5124 case CA_DESTINATION_NOT_REACHABLE:
5125 return OC_STACK_COMM_ERROR;
5126 case CA_SOCKET_OPERATION_FAILED:
5127 return OC_STACK_COMM_ERROR;
5128 case CA_SEND_FAILED:
5129 return OC_STACK_COMM_ERROR;
5130 case CA_RECEIVE_FAILED:
5131 return OC_STACK_COMM_ERROR;
5132 case CA_MEMORY_ALLOC_FAILED:
5133 return OC_STACK_NO_MEMORY;
5134 case CA_REQUEST_TIMEOUT:
5135 return OC_STACK_TIMEOUT;
5136 case CA_DESTINATION_DISCONNECTED:
5137 return OC_STACK_COMM_ERROR;
5138 case CA_STATUS_FAILED:
5139 return OC_STACK_ERROR;
5140 case CA_NOT_SUPPORTED:
5141 return OC_STACK_NOTIMPL;
5143 return OC_STACK_ERROR;
5147 bool OCResultToSuccess(OCStackResult ocResult)
5152 case OC_STACK_RESOURCE_CREATED:
5153 case OC_STACK_RESOURCE_DELETED:
5154 case OC_STACK_CONTINUE:
5155 case OC_STACK_RESOURCE_CHANGED:
5156 case OC_STACK_SLOW_RESOURCE:
5164 OCStackResult OCSetProxyURI(const char *uri)
5166 return CAResultToOCResult(CASetProxyUri(uri));
5170 #if defined(RD_CLIENT) || defined(RD_SERVER)
5171 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5173 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5175 OCResource *resource = NULL;
5177 resource = findResource((OCResource *) handle);
5180 OIC_LOG(ERROR, TAG, "Resource not found");
5181 return OC_STACK_ERROR;
5184 resource->ins = ins;
5190 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5191 const OCClientResponse *response)
5193 // Validate input parameters
5194 VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5195 VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5197 char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5200 return OC_STACK_NO_MEMORY;
5202 strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5204 if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5206 OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5208 char rdPubUri[MAX_URI_LENGTH] = { 0 };
5209 snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5210 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5212 if (strcmp(rdPubUri, targetUri) == 0)
5214 // Update resource unique id in stack.
5217 if (response->payload)
5219 OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5220 OCRepPayload **links = NULL;
5221 size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5222 if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5223 &links, dimensions))
5226 for (; i < dimensions[0]; i++)
5229 if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5231 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5233 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5235 OCBindResourceInsToResource(handle, ins);
5244 size_t count = calcDimTotal(dimensions);
5245 for (size_t k = 0; k < count; k++)
5247 OCRepPayloadDestroy(links[k]);
5255 else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5257 OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5259 uint8_t numResources = 0;
5260 OCGetNumberOfResources(&numResources);
5262 char *ins = strstr(targetUri, OC_RSRVD_INS);
5265 for (uint8_t i = 0; i < numResources; i++)
5267 OCResourceHandle resHandle = OCGetResourceHandle(i);
5270 OCBindResourceInsToResource(resHandle, 0);
5276 const char *token = "&";
5277 char *iterTokenPtr = NULL;
5278 char *start = strtok_r(targetUri, token, &iterTokenPtr);
5280 while (start != NULL)
5282 char *query = start;
5283 query = strstr(query, OC_RSRVD_INS);
5286 int64_t queryIns = atoi(query + 4);
5287 for (uint8_t i = 0; i < numResources; i++)
5289 OCResourceHandle resHandle = OCGetResourceHandle(i);
5293 OCGetResourceIns(resHandle, &resIns);
5294 if (queryIns && queryIns == resIns)
5296 OCBindResourceInsToResource(resHandle, 0);
5302 start = strtok_r(NULL, token, &iterTokenPtr);
5311 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5315 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5319 OCResource *pointer = headResource;
5323 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5325 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5328 pointer = pointer->next;
5333 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t *ins)
5335 OCResource *resource = NULL;
5337 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5338 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5340 resource = findResource((OCResource *) handle);
5343 *ins = resource->ins;
5346 return OC_STACK_ERROR;
5350 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5351 const void* optionData, size_t optionDataLength)
5355 OIC_LOG (INFO, TAG, "Header options are NULL");
5356 return OC_STACK_INVALID_PARAM;
5361 OIC_LOG (INFO, TAG, "optionData are NULL");
5362 return OC_STACK_INVALID_PARAM;
5367 OIC_LOG (INFO, TAG, "numOptions is NULL");
5368 return OC_STACK_INVALID_PARAM;
5371 if (*numOptions >= MAX_HEADER_OPTIONS)
5373 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5374 return OC_STACK_NO_MEMORY;
5377 ocHdrOpt += *numOptions;
5378 ocHdrOpt->protocolID = OC_COAP_ID;
5379 ocHdrOpt->optionID = optionID;
5380 ocHdrOpt->optionLength =
5381 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
5382 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5383 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5389 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5390 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5392 if (!ocHdrOpt || !numOptions)
5394 OIC_LOG (INFO, TAG, "No options present");
5400 OIC_LOG (INFO, TAG, "optionData are NULL");
5401 return OC_STACK_INVALID_PARAM;
5404 if (!receivedDataLength)
5406 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5407 return OC_STACK_INVALID_PARAM;
5410 for (uint8_t i = 0; i < numOptions; i++)
5412 if (ocHdrOpt[i].optionID == optionID)
5414 if (optionDataLength >= ocHdrOpt->optionLength)
5416 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5417 *receivedDataLength = ocHdrOpt->optionLength;
5422 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5423 return OC_STACK_ERROR;
5430 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5432 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5433 if (g_adapterHandler)
5435 g_adapterHandler(adapter, enabled);
5439 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5441 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5442 if (g_connectionHandler)
5444 g_connectionHandler(info, isConnected);
5448 * If the client observes one or more resources over a reliable connection,
5449 * then the CoAP server (or intermediary in the role of the CoAP server)
5450 * MUST remove all entries associated with the client endpoint from the lists
5451 * of observers when the connection is either closed or times out.
5455 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5456 CopyEndpointToDevAddr(info, &devAddr);
5458 // remove observer list with remote device address.
5459 DeleteObserverUsingDevAddr(&devAddr);
5463 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5466 OCStackResult ret = OC_STACK_ERROR;
5468 ret = GetDoxmDeviceID(&oicUuid);
5469 if (OC_STACK_OK == ret)
5471 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5475 OIC_LOG(ERROR, TAG, "Device ID Get error");
5480 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5483 OCStackResult ret = OC_STACK_ERROR;
5485 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5486 for (int i = 0; i < UUID_LENGTH; i++)
5488 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5490 ret = SetDoxmDeviceID(&oicUuid);
5494 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5496 bool isDeviceOwned = true;
5497 OCStackResult ret = OC_STACK_ERROR;
5499 ret = GetDoxmIsOwned(&isDeviceOwned);
5500 if (OC_STACK_OK == ret)
5502 *isOwned = isDeviceOwned;
5506 OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5511 void OCClearCallBackList()
5513 DeleteClientCBList();
5516 void OCClearObserverlist()
5518 DeleteObserverList();
5521 int OCEncrypt(const unsigned char *pt, size_t pt_len,
5522 unsigned char **ct, size_t *ct_len)
5524 #ifndef __SECURE_PSI__
5525 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5528 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5530 return psiEncrypt(pt, pt_len, ct, ct_len);
5531 #endif // __SECURE_PSI__
5534 int OCDecrypt(const unsigned char *ct, size_t ct_len,
5535 unsigned char **pt, size_t *pt_len)
5537 #ifndef __SECURE_PSI__
5538 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5541 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5543 return psiDecrypt(ct, ct_len, pt, pt_len);
5544 #endif // __SECURE_PSI__
5547 OCStackResult OCSetKey(const unsigned char* key)
5549 #ifndef __SECURE_PSI__
5550 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5553 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5555 return psiSetKey(key);
5556 #endif // __SECURE_PSI__
5559 OCStackResult OCGetKey(unsigned char* key)
5561 #ifndef __SECURE_PSI__
5562 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5565 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5567 return psiGetKey(key);
5568 #endif // __SECURE_PSI__
5571 OCStackResult OCSetSecurePSI(const unsigned char *key, const OCPersistentStorage *psPlain,
5572 const OCPersistentStorage *psEnc, const OCPersistentStorage *psRescue)
5574 #ifndef __SECURE_PSI__
5575 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5578 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5580 return setSecurePSI(key, psPlain, psEnc, psRescue);
5581 #endif // __SECURE_PSI__
5584 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5585 static void OtmEventHandler(const char *addr, uint16_t port, const char *uuid, int event)
5587 if (g_otmEventHandler.cb)
5589 g_otmEventHandler.cb(g_otmEventHandler.ctx, addr, port, uuid, event);
5594 * It is already declared in srmutility.h.
5595 * We can't include the header file, because of "redefined VERIFY_NON_NULL"
5597 typedef void (*OicSecOtmEventHandler_t)(const char* addr, uint16_t port,
5598 const char* uuid, int event);
5599 void SetOtmEventHandler(OicSecOtmEventHandler_t otmEventHandler);
5602 OCStackResult OCSetOtmEventHandler(void *ctx, OCOtmEventHandler cb)
5604 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5605 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5607 g_otmEventHandler.cb = cb;
5608 g_otmEventHandler.ctx = ctx;
5610 if (g_otmEventHandler.cb)
5612 OIC_LOG(DEBUG, TAG, "SET OCOtmEventHandler");
5613 SetOtmEventHandler(OtmEventHandler);
5617 OIC_LOG(DEBUG, TAG, "UNSET OCOtmEventHandler");
5618 SetOtmEventHandler(NULL);
5621 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);