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 token = NULL; // Client CB list entry now owns it
3136 devAddr = NULL; // Client CB list entry now owns it
3137 resourceUri = NULL; // Client CB list entry now owns it
3138 resourceType = NULL; // Client CB list entry now owns it
3140 #ifdef WITH_PRESENCE
3141 if (method == OC_REST_PRESENCE)
3143 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3147 *handle = resHandle;
3155 result = OCSendRequest(&endpoint, &requestInfo);
3156 if (OC_STACK_OK != result)
3163 *handle = resHandle;
3167 if (result != OC_STACK_OK)
3169 OIC_LOG(ERROR, TAG, "OCDoResource error");
3170 FindAndDeleteClientCB(clientCB);
3171 CADestroyToken(token);
3179 OICFree(requestInfo.info.payload);
3181 OICFree(resourceUri);
3182 OICFree(resourceType);
3183 OICFree(requestInfo.info.options);
3188 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3192 * This ftn is implemented one of two ways in the case of observation:
3194 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3195 * Remove the callback associated on client side.
3196 * When the next notification comes in from server,
3197 * reply with RESET message to server.
3198 * Keep in mind that the server will react to RESET only
3199 * if the last notification was sent as CON
3201 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3202 * and it is associated with an observe request
3203 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3204 * Send CON Observe request to server with
3205 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3206 * Remove the callback associated on client side.
3208 OCStackResult ret = OC_STACK_OK;
3209 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3210 CARequestInfo_t requestInfo = {.method = CA_GET};
3214 return OC_STACK_INVALID_PARAM;
3217 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3220 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3221 return OC_STACK_ERROR;
3224 switch (clientCB->method)
3226 case OC_REST_OBSERVE:
3227 case OC_REST_OBSERVE_ALL:
3229 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3231 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3233 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
3235 FindAndDeleteClientCB(clientCB);
3239 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3241 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3242 requestInfo.info.token = clientCB->token;
3243 requestInfo.info.tokenLength = clientCB->tokenLength;
3245 if (CreateObserveHeaderOption (&(requestInfo.info.options),
3246 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3248 return OC_STACK_ERROR;
3250 requestInfo.info.numOptions = numOptions + 1;
3251 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3254 ret = OCSendRequest(&endpoint, &requestInfo);
3256 if (requestInfo.info.options)
3258 OICFree (requestInfo.info.options);
3260 if (requestInfo.info.resourceUri)
3262 OICFree (requestInfo.info.resourceUri);
3267 case OC_REST_DISCOVER:
3268 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3269 clientCB->requestUri);
3270 FindAndDeleteClientCB(clientCB);
3273 #ifdef WITH_PRESENCE
3274 case OC_REST_PRESENCE:
3275 FindAndDeleteClientCB(clientCB);
3281 case OC_REST_DELETE:
3282 OIC_LOG_V(INFO, TAG, "Cancelling request callback for resource %s",
3283 clientCB->requestUri);
3284 FindAndDeleteClientCB(clientCB);
3288 ret = OC_STACK_INVALID_METHOD;
3296 * @brief Register Persistent storage callback.
3297 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3299 * OC_STACK_OK - No errors; Success
3300 * OC_STACK_INVALID_PARAM - Invalid parameter
3302 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3304 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3305 if(!persistentStorageHandler)
3307 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3308 return OC_STACK_INVALID_PARAM;
3312 if( !persistentStorageHandler->open ||
3313 !persistentStorageHandler->close ||
3314 !persistentStorageHandler->read ||
3315 !persistentStorageHandler->unlink ||
3316 !persistentStorageHandler->write)
3318 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3319 return OC_STACK_INVALID_PARAM;
3322 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3325 #ifdef WITH_PRESENCE
3327 OCStackResult OCProcessPresence()
3329 OCStackResult result = OC_STACK_OK;
3331 // the following line floods the log with messages that are irrelevant
3332 // to most purposes. Uncomment as needed.
3333 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3334 ClientCB* cbNode = NULL;
3335 OCClientResponse clientResponse;
3336 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3338 LL_FOREACH(cbList, cbNode)
3340 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3345 uint32_t now = GetTicks(0);
3346 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3347 cbNode->presence->TTLlevel);
3348 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3350 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3355 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3357 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3358 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3360 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3362 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3364 clientResponse.sequenceNumber = 0;
3365 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3366 clientResponse.devAddr = *cbNode->devAddr;
3367 FixUpClientResponse(&clientResponse);
3368 clientResponse.payload = NULL;
3370 // Increment the TTLLevel (going to a next state), so we don't keep
3371 // sending presence notification to client.
3372 cbNode->presence->TTLlevel++;
3373 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3374 cbNode->presence->TTLlevel);
3376 OIC_LOG(INFO, TAG, "Before calling into application address space for presence timeout");
3377 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3378 OIC_LOG(INFO, TAG, "After calling into application address space for presence timeout");
3380 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3382 FindAndDeleteClientCB(cbNode);
3386 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3391 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3392 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3393 CARequestInfo_t requestInfo = {.method = CA_GET};
3395 OIC_LOG(DEBUG, TAG, "time to test server presence");
3397 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3399 requestData.type = CA_MSG_NONCONFIRM;
3400 requestData.token = cbNode->token;
3401 requestData.tokenLength = cbNode->tokenLength;
3402 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3403 requestInfo.method = CA_GET;
3404 requestInfo.info = requestData;
3406 result = OCSendRequest(&endpoint, &requestInfo);
3407 if (OC_STACK_OK != result)
3412 cbNode->presence->TTLlevel++;
3413 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3416 if (result != OC_STACK_OK)
3418 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3423 #endif // WITH_PRESENCE
3425 OCStackResult OCProcess()
3427 if (stackState == OC_STACK_UNINITIALIZED)
3429 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3430 return OC_STACK_ERROR;
3432 #ifdef WITH_PRESENCE
3433 OCProcessPresence();
3435 CAHandleRequestResponse();
3437 #ifdef ROUTING_GATEWAY
3442 OCProcessKeepAlive();
3447 #ifdef WITH_PRESENCE
3448 OCStackResult OCStartPresence(const uint32_t ttl)
3450 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3451 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3452 OCChangeResourceProperty(
3453 &(((OCResource *)presenceResource.handle)->resourceProperties),
3456 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3458 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3459 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3463 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3464 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3468 presenceResource.presenceTTL = ttl;
3471 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3474 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3476 presenceState = OC_PRESENCE_INITIALIZED;
3478 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3480 CAToken_t caToken = NULL;
3481 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3482 if (caResult != CA_STATUS_OK)
3484 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3485 CADestroyToken(caToken);
3486 return OC_STACK_ERROR;
3489 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3490 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3491 CADestroyToken(caToken);
3494 // Each time OCStartPresence is called
3495 // a different random 32-bit integer number is used
3496 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3498 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3499 OC_PRESENCE_TRIGGER_CREATE);
3502 OCStackResult OCStopPresence()
3504 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3505 OCStackResult result = OC_STACK_ERROR;
3507 if(presenceResource.handle)
3509 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3511 // make resource inactive
3512 result = OCChangeResourceProperty(
3513 &(((OCResource *) presenceResource.handle)->resourceProperties),
3517 if(result != OC_STACK_OK)
3520 "Changing the presence resource properties to ACTIVE not successful");
3524 return SendStopNotification();
3528 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3529 void* callbackParameter)
3531 defaultDeviceHandler = entityHandler;
3532 defaultDeviceHandlerCallbackParameter = callbackParameter;
3537 OCStackResult OCCreateResource(OCResourceHandle *handle,
3538 const char *resourceTypeName,
3539 const char *resourceInterfaceName,
3540 const char *uri, OCEntityHandler entityHandler,
3541 void* callbackParam,
3542 uint8_t resourceProperties)
3545 OCResource *pointer = NULL;
3546 OCStackResult result = OC_STACK_ERROR;
3548 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3550 if(myStackMode == OC_CLIENT)
3552 return OC_STACK_INVALID_PARAM;
3554 // Validate parameters
3555 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3557 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3558 return OC_STACK_INVALID_URI;
3560 // Is it presented during resource discovery?
3561 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3563 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3564 return OC_STACK_INVALID_PARAM;
3567 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3569 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3573 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3575 // Make sure resourceProperties bitmask has allowed properties specified
3576 if (resourceProperties
3577 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3578 OC_EXPLICIT_DISCOVERABLE
3587 OIC_LOG(ERROR, TAG, "Invalid property");
3588 return OC_STACK_INVALID_PARAM;
3591 // If the headResource is NULL, then no resources have been created...
3592 pointer = headResource;
3595 // At least one resources is in the resource list, so we need to search for
3596 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3599 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3601 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3602 return OC_STACK_INVALID_PARAM;
3604 pointer = pointer->next;
3607 // Create the pointer and insert it into the resource list
3608 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3611 result = OC_STACK_NO_MEMORY;
3614 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3616 insertResource(pointer);
3619 pointer->uri = OICStrdup(uri);
3622 result = OC_STACK_NO_MEMORY;
3626 // Set properties. Set OC_ACTIVE
3627 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3630 // Add the resourcetype to the resource
3631 result = BindResourceTypeToResource(pointer, resourceTypeName);
3632 if (result != OC_STACK_OK)
3634 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3638 // Add the resourceinterface to the resource
3639 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3640 if (result != OC_STACK_OK)
3642 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3646 // If an entity handler has been passed, attach it to the newly created
3647 // resource. Otherwise, set the default entity handler.
3650 pointer->entityHandler = entityHandler;
3651 pointer->entityHandlerCallbackParam = callbackParam;
3655 pointer->entityHandler = defaultResourceEHandler;
3656 pointer->entityHandlerCallbackParam = NULL;
3659 // Initialize a pointer indicating child resources in case of collection
3660 pointer->rsrcChildResourcesHead = NULL;
3663 result = OC_STACK_OK;
3665 #ifdef WITH_PRESENCE
3666 if (presenceResource.handle)
3668 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3669 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3673 if (result != OC_STACK_OK)
3675 // Deep delete of resource and other dynamic elements that it contains
3676 deleteResource(pointer);
3681 OCStackResult OCBindResource(
3682 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3684 OCResource *resource = NULL;
3685 OCChildResource *tempChildResource = NULL;
3686 OCChildResource *newChildResource = NULL;
3688 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3690 // Validate parameters
3691 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3692 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3693 // Container cannot contain itself
3694 if (collectionHandle == resourceHandle)
3696 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3697 return OC_STACK_INVALID_PARAM;
3700 // Use the handle to find the resource in the resource linked list
3701 resource = findResource((OCResource *) collectionHandle);
3704 OIC_LOG(ERROR, TAG, "Collection handle not found");
3705 return OC_STACK_INVALID_PARAM;
3708 // Look for an open slot to add add the child resource.
3709 // If found, add it and return success
3711 tempChildResource = resource->rsrcChildResourcesHead;
3713 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3715 // TODO: what if one of child resource was deregistered without unbinding?
3716 tempChildResource = tempChildResource->next;
3719 // Do memory allocation for child resource
3720 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3721 if(!newChildResource)
3723 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3724 return OC_STACK_ERROR;
3727 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3728 newChildResource->next = NULL;
3730 if(!resource->rsrcChildResourcesHead)
3732 resource->rsrcChildResourcesHead = newChildResource;
3735 tempChildResource->next = newChildResource;
3738 OIC_LOG(INFO, TAG, "resource bound");
3740 #ifdef WITH_PRESENCE
3741 if (presenceResource.handle)
3743 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3744 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3745 OC_PRESENCE_TRIGGER_CHANGE);
3752 OCStackResult OCUnBindResource(
3753 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3755 OCResource *resource = NULL;
3756 OCChildResource *tempChildResource = NULL;
3757 OCChildResource *tempLastChildResource = NULL;
3759 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3761 // Validate parameters
3762 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3763 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3764 // Container cannot contain itself
3765 if (collectionHandle == resourceHandle)
3767 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3768 return OC_STACK_INVALID_PARAM;
3771 // Use the handle to find the resource in the resource linked list
3772 resource = findResource((OCResource *) collectionHandle);
3775 OIC_LOG(ERROR, TAG, "Collection handle not found");
3776 return OC_STACK_INVALID_PARAM;
3779 // Look for an open slot to add add the child resource.
3780 // If found, add it and return success
3781 if(!resource->rsrcChildResourcesHead)
3783 OIC_LOG(INFO, TAG, "resource not found in collection");
3785 // Unable to add resourceHandle, so return error
3786 return OC_STACK_ERROR;
3790 tempChildResource = resource->rsrcChildResourcesHead;
3792 while (tempChildResource)
3794 if(tempChildResource->rsrcResource == resourceHandle)
3796 // if resource going to be unbinded is the head one.
3797 if( tempChildResource == resource->rsrcChildResourcesHead )
3799 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3800 OICFree(resource->rsrcChildResourcesHead);
3801 resource->rsrcChildResourcesHead = temp;
3806 OCChildResource *temp = tempChildResource->next;
3807 OICFree(tempChildResource);
3808 if (tempLastChildResource)
3810 tempLastChildResource->next = temp;
3815 OIC_LOG(INFO, TAG, "resource unbound");
3817 // Send notification when resource is unbounded successfully.
3818 #ifdef WITH_PRESENCE
3819 if (presenceResource.handle)
3821 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3822 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3823 OC_PRESENCE_TRIGGER_CHANGE);
3826 tempChildResource = NULL;
3827 tempLastChildResource = NULL;
3833 tempLastChildResource = tempChildResource;
3834 tempChildResource = tempChildResource->next;
3837 OIC_LOG(INFO, TAG, "resource not found in collection");
3839 tempChildResource = NULL;
3840 tempLastChildResource = NULL;
3842 // Unable to add resourceHandle, so return error
3843 return OC_STACK_ERROR;
3846 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3848 if (!resourceItemName)
3852 // Per RFC 6690 only registered values must follow the first rule below.
3853 // At this point in time the only values registered begin with "core", and
3854 // all other values are specified as opaque strings where multiple values
3855 // are separated by a space.
3856 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3858 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3860 if (resourceItemName[index] != '.'
3861 && resourceItemName[index] != '-'
3862 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3863 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3871 for (size_t index = 0; resourceItemName[index]; ++index)
3873 if (resourceItemName[index] == ' '
3874 || resourceItemName[index] == '\t'
3875 || resourceItemName[index] == '\r'
3876 || resourceItemName[index] == '\n')
3886 OCStackResult BindResourceTypeToResource(OCResource* resource,
3887 const char *resourceTypeName)
3889 OCResourceType *pointer = NULL;
3891 OCStackResult result = OC_STACK_ERROR;
3893 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3895 if (!ValidateResourceTypeInterface(resourceTypeName))
3897 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3898 return OC_STACK_INVALID_PARAM;
3901 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3904 result = OC_STACK_NO_MEMORY;
3908 str = OICStrdup(resourceTypeName);
3911 result = OC_STACK_NO_MEMORY;
3914 pointer->resourcetypename = str;
3915 pointer->next = NULL;
3917 insertResourceType(resource, pointer);
3918 result = OC_STACK_OK;
3921 if (result != OC_STACK_OK)
3930 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3931 const char *resourceInterfaceName)
3933 OCResourceInterface *pointer = NULL;
3935 OCStackResult result = OC_STACK_ERROR;
3937 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3939 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3941 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3942 return OC_STACK_INVALID_PARAM;
3945 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3947 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3950 result = OC_STACK_NO_MEMORY;
3954 str = OICStrdup(resourceInterfaceName);
3957 result = OC_STACK_NO_MEMORY;
3960 pointer->name = str;
3962 // Bind the resourceinterface to the resource
3963 insertResourceInterface(resource, pointer);
3965 result = OC_STACK_OK;
3968 if (result != OC_STACK_OK)
3977 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3978 const char *resourceTypeName)
3981 OCStackResult result = OC_STACK_ERROR;
3982 OCResource *resource = NULL;
3984 resource = findResource((OCResource *) handle);
3987 OIC_LOG(ERROR, TAG, "Resource not found");
3988 return OC_STACK_ERROR;
3991 result = BindResourceTypeToResource(resource, resourceTypeName);
3993 #ifdef WITH_PRESENCE
3994 if(presenceResource.handle)
3996 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3997 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4004 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
4005 const char *resourceInterfaceName)
4008 OCStackResult result = OC_STACK_ERROR;
4009 OCResource *resource = NULL;
4011 resource = findResource((OCResource *) handle);
4014 OIC_LOG(ERROR, TAG, "Resource not found");
4015 return OC_STACK_ERROR;
4018 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
4020 #ifdef WITH_PRESENCE
4021 if (presenceResource.handle)
4023 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4024 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4031 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
4033 OCResource *pointer = headResource;
4035 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
4039 *numResources = *numResources + 1;
4040 pointer = pointer->next;
4045 OCResourceHandle OCGetResourceHandle(uint8_t index)
4047 OCResource *pointer = headResource;
4049 for( uint8_t i = 0; i < index && pointer; ++i)
4051 pointer = pointer->next;
4053 return (OCResourceHandle) pointer;
4056 OCStackResult OCDeleteResource(OCResourceHandle handle)
4060 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4061 return OC_STACK_INVALID_PARAM;
4064 OCResource *resource = findResource((OCResource *) handle);
4065 if (resource == NULL)
4067 OIC_LOG(ERROR, TAG, "Resource not found");
4068 return OC_STACK_NO_RESOURCE;
4071 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4073 OIC_LOG(ERROR, TAG, "Error deleting resource");
4074 return OC_STACK_ERROR;
4080 const char *OCGetResourceUri(OCResourceHandle handle)
4082 OCResource *resource = NULL;
4084 resource = findResource((OCResource *) handle);
4087 return resource->uri;
4089 return (const char *) NULL;
4092 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4094 OCResource *resource = NULL;
4096 resource = findResource((OCResource *) handle);
4099 return resource->resourceProperties;
4101 return (OCResourceProperty)-1;
4104 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4105 uint8_t *numResourceTypes)
4107 OCResource *resource = NULL;
4108 OCResourceType *pointer = NULL;
4110 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4111 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4113 *numResourceTypes = 0;
4115 resource = findResource((OCResource *) handle);
4118 pointer = resource->rsrcType;
4121 *numResourceTypes = *numResourceTypes + 1;
4122 pointer = pointer->next;
4128 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4130 OCResourceType *resourceType = NULL;
4132 resourceType = findResourceTypeAtIndex(handle, index);
4135 return resourceType->resourcetypename;
4137 return (const char *) NULL;
4140 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4141 uint8_t *numResourceInterfaces)
4143 OCResourceInterface *pointer = NULL;
4144 OCResource *resource = NULL;
4146 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4147 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4149 *numResourceInterfaces = 0;
4150 resource = findResource((OCResource *) handle);
4153 pointer = resource->rsrcInterface;
4156 *numResourceInterfaces = *numResourceInterfaces + 1;
4157 pointer = pointer->next;
4163 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4165 OCResourceInterface *resourceInterface = NULL;
4167 resourceInterface = findResourceInterfaceAtIndex(handle, index);
4168 if (resourceInterface)
4170 return resourceInterface->name;
4172 return (const char *) NULL;
4175 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4178 OCResource *resource = NULL;
4179 OCChildResource *tempChildResource = NULL;
4182 resource = findResource((OCResource *) collectionHandle);
4188 tempChildResource = resource->rsrcChildResourcesHead;
4190 while(tempChildResource)
4194 return tempChildResource->rsrcResource;
4197 tempChildResource = tempChildResource->next;
4200 // In this case, the number of resource handles in the collection exceeds the index
4201 tempChildResource = NULL;
4205 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4206 OCEntityHandler entityHandler,
4207 void* callbackParam)
4209 OCResource *resource = NULL;
4211 // Validate parameters
4212 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4214 // Use the handle to find the resource in the resource linked list
4215 resource = findResource((OCResource *)handle);
4218 OIC_LOG(ERROR, TAG, "Resource not found");
4219 return OC_STACK_ERROR;
4223 resource->entityHandler = entityHandler;
4224 resource->entityHandlerCallbackParam = callbackParam;
4226 #ifdef WITH_PRESENCE
4227 if (presenceResource.handle)
4229 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4230 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4237 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4239 OCResource *resource = NULL;
4241 resource = findResource((OCResource *)handle);
4244 OIC_LOG(ERROR, TAG, "Resource not found");
4249 return resource->entityHandler;
4252 void incrementSequenceNumber(OCResource * resPtr)
4254 // Increment the sequence number
4255 resPtr->sequenceNum += 1;
4256 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4258 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4263 #ifdef WITH_PRESENCE
4264 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4265 OCPresenceTrigger trigger)
4267 OIC_LOG(INFO, TAG, "SendPresenceNotification");
4268 OCResource *resPtr = NULL;
4269 OCStackResult result = OC_STACK_ERROR;
4270 OCMethod method = OC_REST_PRESENCE;
4271 uint32_t maxAge = 0;
4272 resPtr = findResource((OCResource *) presenceResource.handle);
4275 return OC_STACK_NO_RESOURCE;
4278 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4280 maxAge = presenceResource.presenceTTL;
4282 result = SendAllObserverNotification(method, resPtr, maxAge,
4283 trigger, resourceType, OC_LOW_QOS);
4289 OCStackResult SendStopNotification()
4291 OIC_LOG(INFO, TAG, "SendStopNotification");
4292 OCResource *resPtr = NULL;
4293 OCStackResult result = OC_STACK_ERROR;
4294 OCMethod method = OC_REST_PRESENCE;
4295 resPtr = findResource((OCResource *) presenceResource.handle);
4298 return OC_STACK_NO_RESOURCE;
4301 // maxAge is 0. ResourceType is NULL.
4302 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4308 #endif // WITH_PRESENCE
4309 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4311 OCResource *resPtr = NULL;
4312 OCStackResult result = OC_STACK_ERROR;
4313 OCMethod method = OC_REST_NOMETHOD;
4314 uint32_t maxAge = 0;
4316 OIC_LOG(INFO, TAG, "Notifying all observers");
4317 #ifdef WITH_PRESENCE
4318 if(handle == presenceResource.handle)
4322 #endif // WITH_PRESENCE
4323 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4325 // Verify that the resource exists
4326 resPtr = findResource ((OCResource *) handle);
4329 return OC_STACK_NO_RESOURCE;
4333 //only increment in the case of regular observing (not presence)
4334 incrementSequenceNumber(resPtr);
4335 method = OC_REST_OBSERVE;
4336 maxAge = MAX_OBSERVE_AGE;
4337 #ifdef WITH_PRESENCE
4338 result = SendAllObserverNotification (method, resPtr, maxAge,
4339 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4341 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4348 OCNotifyListOfObservers (OCResourceHandle handle,
4349 OCObservationId *obsIdList,
4350 uint8_t numberOfIds,
4351 const OCRepPayload *payload,
4352 OCQualityOfService qos)
4354 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4356 OCResource *resPtr = NULL;
4357 //TODO: we should allow the server to define this
4358 uint32_t maxAge = MAX_OBSERVE_AGE;
4360 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4361 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4362 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4364 resPtr = findResource ((OCResource *) handle);
4365 if (NULL == resPtr || myStackMode == OC_CLIENT)
4367 return OC_STACK_NO_RESOURCE;
4371 incrementSequenceNumber(resPtr);
4373 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4374 payload, maxAge, qos));
4377 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4379 OIC_TRACE_BEGIN(%s:OCDoResponse, TAG);
4380 OCStackResult result = OC_STACK_ERROR;
4381 OCServerRequest *serverRequest = NULL;
4383 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4385 // Validate input parameters
4386 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4387 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4390 // Get pointer to request info
4391 serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
4394 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4395 result = serverRequest->ehResponseHandler(ehResponse);
4402 //#ifdef DIRECT_PAIRING
4403 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4405 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4406 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4408 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4412 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4415 const OCDPDev_t* OCGetDirectPairedDevices()
4417 return (const OCDPDev_t*)DPGetPairedDevices();
4420 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4421 OCDirectPairingCB resultCallback)
4423 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4424 if(NULL == peer || NULL == pinNumber)
4426 OIC_LOG(ERROR, TAG, "Invalid parameters");
4427 return OC_STACK_INVALID_PARAM;
4429 if (NULL == resultCallback)
4431 OIC_LOG(ERROR, TAG, "Invalid callback");
4432 return OC_STACK_INVALID_CALLBACK;
4435 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4436 pinNumber, (OCDirectPairingResultCB)resultCallback);
4438 //#endif // DIRECT_PAIRING
4440 //-----------------------------------------------------------------------------
4441 // Private internal function definitions
4442 //-----------------------------------------------------------------------------
4443 static OCDoHandle GenerateInvocationHandle()
4445 OCDoHandle handle = NULL;
4446 // Generate token here, it will be deleted when the transaction is deleted
4447 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4450 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4456 #ifdef WITH_PRESENCE
4457 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4458 OCResourceProperty resourceProperties, uint8_t enable)
4462 return OC_STACK_INVALID_PARAM;
4464 if (resourceProperties
4465 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4467 OIC_LOG(ERROR, TAG, "Invalid property");
4468 return OC_STACK_INVALID_PARAM;
4472 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4476 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4482 OCStackResult initResources()
4484 OCStackResult result = OC_STACK_OK;
4486 headResource = NULL;
4487 tailResource = NULL;
4488 // Init Virtual Resources
4489 #ifdef WITH_PRESENCE
4490 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4492 result = OCCreateResource(&presenceResource.handle,
4493 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4495 OC_RSRVD_PRESENCE_URI,
4499 //make resource inactive
4500 result = OCChangeResourceProperty(
4501 &(((OCResource *) presenceResource.handle)->resourceProperties),
4504 #ifndef WITH_ARDUINO
4505 if (result == OC_STACK_OK)
4507 result = SRMInitSecureResources();
4511 if(result == OC_STACK_OK)
4513 CreateResetProfile();
4514 result = OCCreateResource(&deviceResource,
4515 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4516 OC_RSRVD_INTERFACE_DEFAULT,
4517 OC_RSRVD_DEVICE_URI,
4521 if(result == OC_STACK_OK)
4523 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4524 OC_RSRVD_INTERFACE_READ);
4528 if(result == OC_STACK_OK)
4530 result = OCCreateResource(&platformResource,
4531 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4532 OC_RSRVD_INTERFACE_DEFAULT,
4533 OC_RSRVD_PLATFORM_URI,
4537 if(result == OC_STACK_OK)
4539 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4540 OC_RSRVD_INTERFACE_READ);
4547 void insertResource(OCResource *resource)
4551 headResource = resource;
4552 tailResource = resource;
4556 tailResource->next = resource;
4557 tailResource = resource;
4559 resource->next = NULL;
4562 OCResource *findResource(OCResource *resource)
4564 OCResource *pointer = headResource;
4568 if (pointer == resource)
4572 pointer = pointer->next;
4577 void deleteAllResources()
4579 OCResource *pointer = headResource;
4580 OCResource *temp = NULL;
4584 temp = pointer->next;
4585 #ifdef WITH_PRESENCE
4586 if (pointer != (OCResource *) presenceResource.handle)
4588 #endif // WITH_PRESENCE
4589 deleteResource(pointer);
4590 #ifdef WITH_PRESENCE
4592 #endif // WITH_PRESENCE
4595 memset(&platformResource, 0, sizeof(platformResource));
4596 memset(&deviceResource, 0, sizeof(deviceResource));
4598 memset(&brokerResource, 0, sizeof(brokerResource));
4601 SRMDeInitSecureResources();
4603 #ifdef WITH_PRESENCE
4604 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4605 // presence notification attributed to their deletion to be processed.
4606 deleteResource((OCResource *) presenceResource.handle);
4607 memset(&presenceResource, 0, sizeof(presenceResource));
4608 #endif // WITH_PRESENCE
4611 OCStackResult deleteResource(OCResource *resource)
4613 OCResource *prev = NULL;
4614 OCResource *temp = NULL;
4617 OIC_LOG(DEBUG,TAG,"resource is NULL");
4618 return OC_STACK_INVALID_PARAM;
4621 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4623 temp = headResource;
4626 if (temp == resource)
4628 // Invalidate all Resource Properties.
4629 resource->resourceProperties = (OCResourceProperty) 0;
4630 #ifdef WITH_PRESENCE
4631 if(resource != (OCResource *) presenceResource.handle)
4633 #endif // WITH_PRESENCE
4634 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4635 #ifdef WITH_PRESENCE
4638 if(presenceResource.handle)
4640 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4641 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4644 // Only resource in list.
4645 if (temp == headResource && temp == tailResource)
4647 headResource = NULL;
4648 tailResource = NULL;
4651 else if (temp == headResource)
4653 headResource = temp->next;
4656 else if (temp == tailResource && prev)
4658 tailResource = prev;
4659 tailResource->next = NULL;
4663 prev->next = temp->next;
4666 deleteResourceElements(temp);
4677 return OC_STACK_ERROR;
4680 void deleteResourceElements(OCResource *resource)
4689 OICFree(resource->uri);
4690 resource->uri = NULL;
4692 if (resource->rsrcType)
4694 deleteResourceType(resource->rsrcType);
4695 resource->rsrcType = NULL;
4697 if (resource->rsrcInterface)
4699 deleteResourceInterface(resource->rsrcInterface);
4700 resource->rsrcInterface = NULL;
4702 if (resource->rsrcChildResourcesHead)
4704 unbindChildResources(resource->rsrcChildResourcesHead);
4705 resource->rsrcChildResourcesHead = NULL;
4707 if (resource->rsrcAttributes)
4709 OCDeleteResourceAttributes(resource->rsrcAttributes);
4710 resource->rsrcAttributes = NULL;
4715 void deleteResourceType(OCResourceType *resourceType)
4717 OCResourceType *next = NULL;
4719 for (OCResourceType *pointer = resourceType; pointer; pointer = next)
4721 next = pointer->next ? pointer->next : NULL;
4722 if (pointer->resourcetypename)
4724 OICFree(pointer->resourcetypename);
4725 pointer->resourcetypename = NULL;
4731 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4733 OCResourceInterface *next = NULL;
4734 for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
4736 next = pointer->next ? pointer->next : NULL;
4739 OICFree(pointer->name);
4740 pointer->name = NULL;
4746 void unbindChildResources(OCChildResource *head)
4748 OCChildResource *next = NULL;
4749 for (OCChildResource *current = head; current; current = next)
4751 next = current->next;
4756 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
4758 OCAttribute *next = NULL;
4759 for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
4761 next = pointer->next ? pointer->next : NULL;
4762 if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
4764 OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
4765 pointer->attrValue = NULL;
4767 else if (pointer->attrValue)
4769 OICFree(pointer->attrValue);
4770 pointer->attrValue = NULL;
4772 if (pointer->attrName)
4774 OICFree(pointer->attrName);
4775 pointer->attrName = NULL;
4781 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4783 OCResourceType *pointer = NULL;
4784 OCResourceType *previous = NULL;
4785 if (!resource || !resourceType)
4789 // resource type list is empty.
4790 else if (!resource->rsrcType)
4792 resource->rsrcType = resourceType;
4796 pointer = resource->rsrcType;
4800 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4802 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4803 OICFree(resourceType->resourcetypename);
4804 OICFree(resourceType);
4808 pointer = pointer->next;
4813 previous->next = resourceType;
4816 resourceType->next = NULL;
4818 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4821 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4823 OCResource *resource = NULL;
4824 OCResourceType *pointer = NULL;
4826 // Find the specified resource
4827 resource = findResource((OCResource *) handle);
4833 // Make sure a resource has a resourcetype
4834 if (!resource->rsrcType)
4839 // Iterate through the list
4840 pointer = resource->rsrcType;
4841 for(uint8_t i = 0; i< index && pointer; ++i)
4843 pointer = pointer->next;
4848 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4850 if(resourceTypeList && resourceTypeName)
4852 OCResourceType * rtPointer = resourceTypeList;
4853 while(resourceTypeName && rtPointer)
4855 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4856 if(rtPointer->resourcetypename &&
4857 strcmp(resourceTypeName, (const char *)
4858 (rtPointer->resourcetypename)) == 0)
4862 rtPointer = rtPointer->next;
4870 * Insert a new interface into interface linked list only if not already present.
4871 * If alredy present, 2nd arg is free'd.
4872 * Default interface will always be first if present.
4874 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4876 OCResourceInterface *pointer = NULL;
4877 OCResourceInterface *previous = NULL;
4879 newInterface->next = NULL;
4881 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4883 if (!*firstInterface)
4885 // If first interface is not oic.if.baseline, by default add it as first interface type.
4886 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4888 *firstInterface = newInterface;
4892 OCStackResult result = BindResourceInterfaceToResource(resource,
4893 OC_RSRVD_INTERFACE_DEFAULT);
4894 if (result != OC_STACK_OK)
4896 OICFree(newInterface->name);
4897 OICFree(newInterface);
4900 if (*firstInterface)
4902 (*firstInterface)->next = newInterface;
4906 // If once add oic.if.baseline, later too below code take care of freeing memory.
4907 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4909 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4911 OICFree(newInterface->name);
4912 OICFree(newInterface);
4915 // This code will not hit anymore, keeping
4918 newInterface->next = *firstInterface;
4919 *firstInterface = newInterface;
4924 pointer = *firstInterface;
4927 if (strcmp(newInterface->name, pointer->name) == 0)
4929 OICFree(newInterface->name);
4930 OICFree(newInterface);
4934 pointer = pointer->next;
4939 previous->next = newInterface;
4944 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4947 OCResource *resource = NULL;
4948 OCResourceInterface *pointer = NULL;
4950 // Find the specified resource
4951 resource = findResource((OCResource *) handle);
4957 // Make sure a resource has a resourceinterface
4958 if (!resource->rsrcInterface)
4963 // Iterate through the list
4964 pointer = resource->rsrcInterface;
4966 for (uint8_t i = 0; i < index && pointer; ++i)
4968 pointer = pointer->next;
4974 * This function splits the uri using the '?' delimiter.
4975 * "uriWithoutQuery" is the block of characters between the beginning
4976 * till the delimiter or '\0' which ever comes first.
4977 * "query" is whatever is to the right of the delimiter if present.
4978 * No delimiter sets the query to NULL.
4979 * If either are present, they will be malloc'ed into the params 2, 3.
4980 * The first param, *uri is left untouched.
4982 * NOTE: This function does not account for whitespace at the end of the uri NOR
4983 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4984 * part of the query.
4986 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4990 return OC_STACK_INVALID_URI;
4992 if(!query || !uriWithoutQuery)
4994 return OC_STACK_INVALID_PARAM;
4998 *uriWithoutQuery = NULL;
5000 size_t uriWithoutQueryLen = 0;
5001 size_t queryLen = 0;
5002 size_t uriLen = strlen(uri);
5004 char *pointerToDelimiter = strstr(uri, "?");
5006 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
5007 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
5009 if (uriWithoutQueryLen)
5011 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
5012 if (!*uriWithoutQuery)
5016 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
5020 *query = (char *) OICCalloc(queryLen + 1, 1);
5023 OICFree(*uriWithoutQuery);
5024 *uriWithoutQuery = NULL;
5027 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5033 return OC_STACK_NO_MEMORY;
5036 const char* OCGetServerInstanceIDString(void)
5038 static char sidStr[UUID_STRING_SIZE];
5040 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5042 OIC_LOG(FATAL, TAG, "GetDoxmDeviceID failed!");
5046 if (OCConvertUuidToString(sid.id, sidStr) != RAND_UUID_OK)
5048 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5055 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5057 OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5058 CAResult_t retResult = CA_STATUS_FAILED;
5059 CAResult_t caResult = CA_STATUS_OK;
5061 CATransportAdapter_t connTypes[] = {
5063 CA_ADAPTER_RFCOMM_BTEDR,
5064 CA_ADAPTER_GATT_BTLE,
5067 ,CA_ADAPTER_REMOTE_ACCESS
5074 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5076 for(int i = 0; i < numConnTypes; i++)
5078 // If CA status is not initialized, CASelectNetwork() will not be called.
5079 if (caResult != CA_STATUS_NOT_INITIALIZED)
5081 if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5083 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5084 caResult = CASelectNetwork(connTypes[i]);
5085 if (caResult == CA_STATUS_OK)
5087 retResult = CA_STATUS_OK;
5092 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5097 if (retResult != CA_STATUS_OK)
5099 return caResult; // Returns error of appropriate transport that failed fatally.
5105 OCStackResult CAResultToOCResult(CAResult_t caResult)
5111 case CA_STATUS_INVALID_PARAM:
5112 return OC_STACK_INVALID_PARAM;
5113 case CA_ADAPTER_NOT_ENABLED:
5114 return OC_STACK_ADAPTER_NOT_ENABLED;
5115 case CA_SERVER_STARTED_ALREADY:
5117 case CA_SERVER_NOT_STARTED:
5118 return OC_STACK_ERROR;
5119 case CA_DESTINATION_NOT_REACHABLE:
5120 return OC_STACK_COMM_ERROR;
5121 case CA_SOCKET_OPERATION_FAILED:
5122 return OC_STACK_COMM_ERROR;
5123 case CA_SEND_FAILED:
5124 return OC_STACK_COMM_ERROR;
5125 case CA_RECEIVE_FAILED:
5126 return OC_STACK_COMM_ERROR;
5127 case CA_MEMORY_ALLOC_FAILED:
5128 return OC_STACK_NO_MEMORY;
5129 case CA_REQUEST_TIMEOUT:
5130 return OC_STACK_TIMEOUT;
5131 case CA_DESTINATION_DISCONNECTED:
5132 return OC_STACK_COMM_ERROR;
5133 case CA_STATUS_FAILED:
5134 return OC_STACK_ERROR;
5135 case CA_NOT_SUPPORTED:
5136 return OC_STACK_NOTIMPL;
5138 return OC_STACK_ERROR;
5142 bool OCResultToSuccess(OCStackResult ocResult)
5147 case OC_STACK_RESOURCE_CREATED:
5148 case OC_STACK_RESOURCE_DELETED:
5149 case OC_STACK_CONTINUE:
5150 case OC_STACK_RESOURCE_CHANGED:
5151 case OC_STACK_SLOW_RESOURCE:
5159 OCStackResult OCSetProxyURI(const char *uri)
5161 return CAResultToOCResult(CASetProxyUri(uri));
5165 #if defined(RD_CLIENT) || defined(RD_SERVER)
5166 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5168 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5170 OCResource *resource = NULL;
5172 resource = findResource((OCResource *) handle);
5175 OIC_LOG(ERROR, TAG, "Resource not found");
5176 return OC_STACK_ERROR;
5179 resource->ins = ins;
5185 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5186 const OCClientResponse *response)
5188 // Validate input parameters
5189 VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5190 VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5192 char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5195 return OC_STACK_NO_MEMORY;
5197 strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5199 if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5201 OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5203 char rdPubUri[MAX_URI_LENGTH] = { 0 };
5204 snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5205 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5207 if (strcmp(rdPubUri, targetUri) == 0)
5209 // Update resource unique id in stack.
5212 if (response->payload)
5214 OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5215 OCRepPayload **links = NULL;
5216 size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5217 if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5218 &links, dimensions))
5221 for (; i < dimensions[0]; i++)
5224 if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5226 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5228 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5230 OCBindResourceInsToResource(handle, ins);
5239 size_t count = calcDimTotal(dimensions);
5240 for (size_t k = 0; k < count; k++)
5242 OCRepPayloadDestroy(links[k]);
5250 else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5252 OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5254 uint8_t numResources = 0;
5255 OCGetNumberOfResources(&numResources);
5257 char *ins = strstr(targetUri, OC_RSRVD_INS);
5260 for (uint8_t i = 0; i < numResources; i++)
5262 OCResourceHandle resHandle = OCGetResourceHandle(i);
5265 OCBindResourceInsToResource(resHandle, 0);
5271 const char *token = "&";
5272 char *iterTokenPtr = NULL;
5273 char *start = strtok_r(targetUri, token, &iterTokenPtr);
5275 while (start != NULL)
5277 char *query = start;
5278 query = strstr(query, OC_RSRVD_INS);
5281 int64_t queryIns = atoi(query + 4);
5282 for (uint8_t i = 0; i < numResources; i++)
5284 OCResourceHandle resHandle = OCGetResourceHandle(i);
5288 OCGetResourceIns(resHandle, &resIns);
5289 if (queryIns && queryIns == resIns)
5291 OCBindResourceInsToResource(resHandle, 0);
5297 start = strtok_r(NULL, token, &iterTokenPtr);
5306 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5310 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5314 OCResource *pointer = headResource;
5318 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5320 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5323 pointer = pointer->next;
5328 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t *ins)
5330 OCResource *resource = NULL;
5332 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5333 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5335 resource = findResource((OCResource *) handle);
5338 *ins = resource->ins;
5341 return OC_STACK_ERROR;
5345 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5346 const void* optionData, size_t optionDataLength)
5350 OIC_LOG (INFO, TAG, "Header options are NULL");
5351 return OC_STACK_INVALID_PARAM;
5356 OIC_LOG (INFO, TAG, "optionData are NULL");
5357 return OC_STACK_INVALID_PARAM;
5362 OIC_LOG (INFO, TAG, "numOptions is NULL");
5363 return OC_STACK_INVALID_PARAM;
5366 if (*numOptions >= MAX_HEADER_OPTIONS)
5368 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5369 return OC_STACK_NO_MEMORY;
5372 ocHdrOpt += *numOptions;
5373 ocHdrOpt->protocolID = OC_COAP_ID;
5374 ocHdrOpt->optionID = optionID;
5375 ocHdrOpt->optionLength =
5376 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
5377 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5378 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5384 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5385 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5387 if (!ocHdrOpt || !numOptions)
5389 OIC_LOG (INFO, TAG, "No options present");
5395 OIC_LOG (INFO, TAG, "optionData are NULL");
5396 return OC_STACK_INVALID_PARAM;
5399 if (!receivedDataLength)
5401 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5402 return OC_STACK_INVALID_PARAM;
5405 for (uint8_t i = 0; i < numOptions; i++)
5407 if (ocHdrOpt[i].optionID == optionID)
5409 if (optionDataLength >= ocHdrOpt->optionLength)
5411 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5412 *receivedDataLength = ocHdrOpt->optionLength;
5417 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5418 return OC_STACK_ERROR;
5425 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5427 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5428 if (g_adapterHandler)
5430 g_adapterHandler(adapter, enabled);
5434 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5436 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5437 if (g_connectionHandler)
5439 g_connectionHandler(info, isConnected);
5443 * If the client observes one or more resources over a reliable connection,
5444 * then the CoAP server (or intermediary in the role of the CoAP server)
5445 * MUST remove all entries associated with the client endpoint from the lists
5446 * of observers when the connection is either closed or times out.
5450 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5451 CopyEndpointToDevAddr(info, &devAddr);
5453 // remove observer list with remote device address.
5454 DeleteObserverUsingDevAddr(&devAddr);
5458 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5461 OCStackResult ret = OC_STACK_ERROR;
5463 ret = GetDoxmDeviceID(&oicUuid);
5464 if (OC_STACK_OK == ret)
5466 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5470 OIC_LOG(ERROR, TAG, "Device ID Get error");
5475 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5478 OCStackResult ret = OC_STACK_ERROR;
5480 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5481 for (int i = 0; i < UUID_LENGTH; i++)
5483 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5485 ret = SetDoxmDeviceID(&oicUuid);
5489 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5491 bool isDeviceOwned = true;
5492 OCStackResult ret = OC_STACK_ERROR;
5494 ret = GetDoxmIsOwned(&isDeviceOwned);
5495 if (OC_STACK_OK == ret)
5497 *isOwned = isDeviceOwned;
5501 OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5506 void OCClearCallBackList()
5508 DeleteClientCBList();
5511 void OCClearObserverlist()
5513 DeleteObserverList();
5516 int OCEncrypt(const unsigned char *pt, size_t pt_len,
5517 unsigned char **ct, size_t *ct_len)
5519 #ifndef __SECURE_PSI__
5520 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5523 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5525 return psiEncrypt(pt, pt_len, ct, ct_len);
5526 #endif // __SECURE_PSI__
5529 int OCDecrypt(const unsigned char *ct, size_t ct_len,
5530 unsigned char **pt, size_t *pt_len)
5532 #ifndef __SECURE_PSI__
5533 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5536 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5538 return psiDecrypt(ct, ct_len, pt, pt_len);
5539 #endif // __SECURE_PSI__
5542 OCStackResult OCSetKey(const unsigned char* key)
5544 #ifndef __SECURE_PSI__
5545 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5548 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5550 return psiSetKey(key);
5551 #endif // __SECURE_PSI__
5554 OCStackResult OCGetKey(unsigned char* key)
5556 #ifndef __SECURE_PSI__
5557 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5560 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5562 return psiGetKey(key);
5563 #endif // __SECURE_PSI__
5566 OCStackResult OCSetSecurePSI(const unsigned char *key, const OCPersistentStorage *psPlain,
5567 const OCPersistentStorage *psEnc, const OCPersistentStorage *psRescue)
5569 #ifndef __SECURE_PSI__
5570 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5573 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5575 return setSecurePSI(key, psPlain, psEnc, psRescue);
5576 #endif // __SECURE_PSI__
5579 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5580 static void OtmEventHandler(const char *addr, uint16_t port, const char *uuid, int event)
5582 if (g_otmEventHandler.cb)
5584 g_otmEventHandler.cb(g_otmEventHandler.ctx, addr, port, uuid, event);
5589 * It is already declared in srmutility.h.
5590 * We can't include the header file, because of "redefined VERIFY_NON_NULL"
5592 typedef void (*OicSecOtmEventHandler_t)(const char* addr, uint16_t port,
5593 const char* uuid, int event);
5594 void SetOtmEventHandler(OicSecOtmEventHandler_t otmEventHandler);
5597 OCStackResult OCSetOtmEventHandler(void *ctx, OCOtmEventHandler cb)
5599 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5600 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5602 g_otmEventHandler.cb = cb;
5603 g_otmEventHandler.ctx = ctx;
5605 if (g_otmEventHandler.cb)
5607 OIC_LOG(DEBUG, TAG, "SET OCOtmEventHandler");
5608 SetOtmEventHandler(OtmEventHandler);
5612 OIC_LOG(DEBUG, TAG, "UNSET OCOtmEventHandler");
5613 SetOtmEventHandler(NULL);
5616 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);