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 cbNode->presence = NULL;
1246 result = OC_STACK_NO_MEMORY;
1251 ResetPresenceTTL(cbNode, maxAge);
1253 cbNode->sequenceNumber = response.sequenceNumber;
1258 // This is the multicast case
1259 OIC_LOG(INFO, TAG, "this is the multicast presence");
1262 OIC_LOG(INFO, TAG, "Stopping presence");
1263 response.result = OC_STACK_PRESENCE_STOPPED;
1267 // Ensure that a filter is actually applied.
1268 if (resourceTypeName && cbNode->filterResourceType)
1270 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1271 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1277 OIC_LOG(INFO, TAG, "Before calling into application address space for presence");
1278 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1279 OIC_LOG(INFO, TAG, "After calling into application address space for presence");
1281 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1283 FindAndDeleteClientCB(cbNode);
1287 OCPayloadDestroy(response.payload);
1290 #endif // WITH_PRESENCE
1292 OCStackResult HandleBatchResponse(char *requestUri, OCRepPayload **payload)
1294 if (requestUri && *payload)
1296 char *interfaceName = NULL;
1297 char *rtTypeName = NULL;
1298 char *uriQuery = NULL;
1299 char *uriWithoutQuery = NULL;
1300 if (OC_STACK_OK == getQueryFromUri(requestUri, &uriQuery, &uriWithoutQuery))
1302 if (OC_STACK_OK == ExtractFiltersFromQuery(uriQuery, &interfaceName, &rtTypeName))
1304 if (interfaceName && (0 == strcmp(OC_RSRVD_INTERFACE_BATCH, interfaceName)))
1306 char *uri = (*payload)->uri;
1307 if (uri && 0 != strcmp(uriWithoutQuery, uri))
1309 OCRepPayload *newPayload = OCRepPayloadCreate();
1312 OCRepPayloadSetUri(newPayload, uri);
1313 newPayload->next = *payload;
1314 *payload = newPayload;
1321 OICFree(interfaceName);
1322 OICFree(rtTypeName);
1324 OICFree(uriWithoutQuery);
1327 return OC_STACK_INVALID_PARAM;
1330 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1332 OIC_TRACE_MARK(%s:OCHandleResponse:%s, TAG, responseInfo->info.resourceUri);
1333 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1335 #ifdef WITH_PRESENCE
1336 if(responseInfo->info.resourceUri &&
1337 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1339 HandlePresenceResponse(endPoint, responseInfo);
1344 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1345 responseInfo->info.tokenLength, NULL, NULL);
1349 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1351 // check obs header option
1352 bool obsHeaderOpt = false;
1353 CAHeaderOption_t *options = responseInfo->info.options;
1354 for (uint8_t i = 0; i< responseInfo->info.numOptions; i++)
1356 if (options && options[i].protocolID == CA_COAP_ID &&
1357 options[i].optionID == COAP_OPTION_OBSERVE)
1359 obsHeaderOpt = true;
1364 if(responseInfo->result == CA_EMPTY)
1366 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1367 // We do not have a case for the client to receive a RESET
1368 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1370 //This is the case of receiving an ACK on a request to a slow resource!
1371 OIC_LOG(INFO, TAG, "This is a pure ACK");
1372 //TODO: should we inform the client
1373 // app that at least the request was received at the server?
1376 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1378 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1380 OCClientResponse response =
1381 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1382 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1383 FixUpClientResponse(&response);
1384 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1385 memcpy(response.identity.id, responseInfo->info.identity.id,
1386 sizeof (response.identity.id));
1387 response.identity.id_length = responseInfo->info.identity.id_length;
1389 response.result = CAResponseToOCStackResult(responseInfo->result);
1390 OIC_LOG(INFO, TAG, "Before calling into application address space for reTrans timeout");
1391 cbNode->callBack(cbNode->context,
1392 cbNode->handle, &response);
1393 OIC_LOG(INFO, TAG, "After calling into application address space for reTrans timeout");
1394 FindAndDeleteClientCB(cbNode);
1395 OICFree((void *)response.resourceUri);
1398 else if ((cbNode->method == OC_REST_OBSERVE || cbNode->method == OC_REST_OBSERVE_ALL)
1399 && (responseInfo->result == CA_CONTENT) && !obsHeaderOpt)
1401 OCClientResponse response =
1402 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1403 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1404 FixUpClientResponse(&response);
1405 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1406 memcpy(response.identity.id, responseInfo->info.identity.id,
1407 sizeof (response.identity.id));
1408 response.identity.id_length = responseInfo->info.identity.id_length;
1409 response.result = OC_STACK_UNAUTHORIZED_REQ;
1411 OIC_LOG(INFO, TAG, "Before calling into application address space for observe resp");
1412 cbNode->callBack(cbNode->context,
1415 OIC_LOG(INFO, TAG, "After calling into application address space for observe resp");
1417 FindAndDeleteClientCB(cbNode);
1418 OICFree(response.resourceUri);
1423 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1425 OCClientResponse response;
1426 memset(&response, 0, sizeof(OCClientResponse));
1427 response.devAddr.adapter = OC_DEFAULT_ADAPTER;
1429 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1430 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1431 FixUpClientResponse(&response);
1432 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1433 memcpy(response.identity.id, responseInfo->info.identity.id,
1434 sizeof (response.identity.id));
1435 response.identity.id_length = responseInfo->info.identity.id_length;
1437 response.result = CAResponseToOCStackResult(responseInfo->result);
1439 if(responseInfo->info.payload &&
1440 responseInfo->info.payloadSize)
1442 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1443 // check the security resource
1444 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1446 type = PAYLOAD_TYPE_SECURITY;
1448 else if (cbNode->method == OC_REST_DISCOVER)
1450 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1451 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1453 type = PAYLOAD_TYPE_DISCOVERY;
1456 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1458 type = PAYLOAD_TYPE_DISCOVERY;
1461 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1463 type = PAYLOAD_TYPE_REPRESENTATION;
1465 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1467 type = PAYLOAD_TYPE_REPRESENTATION;
1470 #ifdef ROUTING_GATEWAY
1471 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1473 type = PAYLOAD_TYPE_REPRESENTATION;
1476 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1478 type = PAYLOAD_TYPE_REPRESENTATION;
1481 else if (strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1483 type = PAYLOAD_TYPE_REPRESENTATION;
1488 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1489 cbNode->method, cbNode->requestUri);
1490 OICFree((void *)response.resourceUri);
1494 else if (cbNode->method == OC_REST_GET ||
1495 cbNode->method == OC_REST_PUT ||
1496 cbNode->method == OC_REST_POST ||
1497 cbNode->method == OC_REST_OBSERVE ||
1498 cbNode->method == OC_REST_OBSERVE_ALL ||
1499 cbNode->method == OC_REST_DELETE)
1501 if (cbNode->requestUri)
1503 if (0 == strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri))
1505 type = PAYLOAD_TYPE_REPRESENTATION;
1507 else if (0 == strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri))
1509 type = PAYLOAD_TYPE_REPRESENTATION;
1511 if (type == PAYLOAD_TYPE_INVALID)
1513 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1514 cbNode->method, cbNode->requestUri);
1515 type = PAYLOAD_TYPE_REPRESENTATION;
1520 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1521 type = PAYLOAD_TYPE_REPRESENTATION;
1526 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1527 cbNode->method, cbNode->requestUri);
1528 OICFree((void *)response.resourceUri);
1532 // In case of error, still want application to receive the error message.
1533 if (OCResultToSuccess(response.result) || PAYLOAD_TYPE_REPRESENTATION == type)
1535 if(OC_STACK_OK != OCParsePayload(&response.payload,
1537 responseInfo->info.payload,
1538 responseInfo->info.payloadSize))
1540 OIC_LOG(ERROR, TAG, "Error converting payload");
1541 OCPayloadDestroy(response.payload);
1542 OICFree((void *)response.resourceUri);
1548 OICFree((void *)response.resourceUri);
1549 response.resourceUri = OICStrdup(cbNode->requestUri);
1553 response.numRcvdVendorSpecificHeaderOptions = 0;
1554 if(responseInfo->info.numOptions > 0)
1557 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1558 if(responseInfo->info.options
1559 && responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1562 uint32_t observationOption;
1563 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1564 for (observationOption=0, i=0;
1565 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1569 (observationOption << 8) | optionData[i];
1571 response.sequenceNumber = observationOption;
1572 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1577 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1580 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1582 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1583 OCPayloadDestroy(response.payload);
1584 OICFree((void *)response.resourceUri);
1588 if (response.numRcvdVendorSpecificHeaderOptions > 0)
1590 response.rcvdVendorSpecificHeaderOptions =
1591 (OCHeaderOption *) OICCalloc(response.numRcvdVendorSpecificHeaderOptions, sizeof(OCHeaderOption));
1592 if (NULL == response.rcvdVendorSpecificHeaderOptions)
1594 OIC_LOG(ERROR, TAG, "Failed to allocate memory for vendor header options");
1595 OCPayloadDestroy(response.payload);
1596 OICFree((void *)response.resourceUri);
1600 memcpy(response.rcvdVendorSpecificHeaderOptions, responseInfo->info.options + start,
1601 response.numRcvdVendorSpecificHeaderOptions*sizeof(OCHeaderOption));
1605 if (cbNode->method == OC_REST_OBSERVE &&
1606 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1607 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1608 response.sequenceNumber <= cbNode->sequenceNumber)
1610 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1611 response.sequenceNumber);
1616 if (cbNode->requestUri)
1618 // if request uri is '/oic/rd', update ins value of resource.
1619 char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
1622 OCUpdateResourceInsWithResponse(cbNode->requestUri, &response);
1626 // set remoteID(device ID) into OCClientResponse callback parameter
1627 if (OC_REST_DISCOVER == cbNode->method)
1629 OIC_LOG(INFO, TAG, "cbNode method is OC_REST_DISCOVER");
1630 OCDiscoveryPayload *payload = (OCDiscoveryPayload*) response.payload;
1631 // Payload can be empty in case of error message.
1632 if (payload && payload->sid)
1634 OICStrcpy(response.devAddr.remoteId, sizeof(response.devAddr.remoteId),
1636 OIC_LOG_V(INFO_PRIVATE, TAG, "Device ID of response : %s",
1637 response.devAddr.remoteId);
1640 if(NULL == response.resourceUri)
1642 response.resourceUri = OICStrdup(cbNode->requestUri);
1646 if (cbNode->requestUri)
1648 OIC_LOG_V(INFO, TAG, "cbNode requestUri is %s", cbNode->requestUri);
1649 if (cbNode->method == OC_REST_POST &&
1650 strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1652 OCHandleKeepAliveResponse(endPoint, response.payload);
1656 if (response.payload && response.payload->type == PAYLOAD_TYPE_REPRESENTATION)
1658 OIC_LOG(INFO, TAG, "Handle batch response");
1659 HandleBatchResponse(cbNode->requestUri, (OCRepPayload **)&response.payload);
1662 OIC_LOG(INFO, TAG, "Before calling into application address space for handleResponse");
1663 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1666 OIC_LOG(INFO, TAG, "After calling into application address space for handleResponse");
1668 cbNode->sequenceNumber = response.sequenceNumber;
1670 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1672 FindAndDeleteClientCB(cbNode);
1676 // To keep discovery callbacks active.
1677 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1678 MILLISECONDS_PER_SECOND);
1682 //Need to send ACK when the response is CON
1683 if(responseInfo->info.type == CA_MSG_CONFIRM)
1685 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1687 OIC_LOG(INFO, TAG, "Received a confirmable message. Sending EMPTY");
1688 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1689 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1693 OICFree((void *)response.resourceUri);
1694 OCPayloadDestroy(response.payload);
1695 OICFree(response.rcvdVendorSpecificHeaderOptions);
1700 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1701 responseInfo->info.tokenLength);
1705 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1706 if(responseInfo->result == CA_EMPTY)
1708 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1709 if(responseInfo->info.type == CA_MSG_RESET)
1711 OIC_LOG(INFO, TAG, "This is a RESET");
1712 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1713 OC_OBSERVER_NOT_INTERESTED);
1715 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1717 OIC_LOG(INFO, TAG, "This is a pure ACK");
1718 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1719 OC_OBSERVER_STILL_INTERESTED);
1722 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1724 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1725 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1726 OC_OBSERVER_FAILED_COMM);
1729 FreeObserver(observer);
1733 if(!cbNode && !observer)
1735 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1736 || myStackMode == OC_GATEWAY)
1738 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1739 if(responseInfo->result == CA_EMPTY)
1741 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1745 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1747 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1748 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1749 CA_MSG_RESET, 0, NULL, NULL, 0, NULL,
1750 CA_RESPONSE_FOR_RES);
1755 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1756 || myStackMode == OC_GATEWAY)
1758 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1759 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1761 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1762 responseInfo->info.messageId);
1764 if (responseInfo->info.type == CA_MSG_RESET)
1766 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1767 responseInfo->info.messageId);
1775 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1777 VERIFY_NON_NULL_NR(endPoint, FATAL);
1778 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1780 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1781 OIC_TRACE_BEGIN(%s:HandleCAResponses, TAG);
1783 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1784 #ifdef ROUTING_GATEWAY
1785 bool needRIHandling = false;
1787 * Routing manager is going to update either of endpoint or response or both.
1788 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1789 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1792 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1794 if(ret != OC_STACK_OK || !needRIHandling)
1796 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1803 * Put source in sender endpoint so that the next packet from application can be routed to
1804 * proper destination and remove "RM" coap header option before passing request / response to
1805 * RI as this option will make no sense to either RI or application.
1807 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1808 (uint8_t *) &(responseInfo->info.numOptions),
1809 (CAEndpoint_t *) endPoint);
1812 OCHandleResponse(endPoint, responseInfo);
1814 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1818 * This function handles error response from CA
1819 * code shall be added to handle the errors
1821 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1823 VERIFY_NON_NULL_NR(endPoint, FATAL);
1824 VERIFY_NON_NULL_NR(errorInfo, FATAL);
1826 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1827 OIC_TRACE_BEGIN(%s:HandleCAErrorResponse, TAG);
1829 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1830 errorInfo->info.tokenLength, NULL, NULL);
1833 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1834 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1835 FixUpClientResponse(&response);
1836 response.resourceUri = errorInfo->info.resourceUri;
1837 memcpy(response.identity.id, errorInfo->info.identity.id,
1838 sizeof (response.identity.id));
1839 response.identity.id_length = errorInfo->info.identity.id_length;
1840 response.result = CAResultToOCResult(errorInfo->result);
1842 OIC_LOG(INFO, TAG, "Before calling into application address space for error response");
1843 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1844 OIC_LOG(INFO, TAG, "After calling into application address space for error response");
1847 ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1848 errorInfo->info.tokenLength);
1851 OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1852 OCStackResult result = CAResultToOCResult(errorInfo->result);
1853 if (OC_STACK_COMM_ERROR == result)
1855 OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1856 OC_OBSERVER_FAILED_COMM);
1860 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1865 * This function sends out Direct Stack Responses. These are responses that are not coming
1866 * from the application entity handler. These responses have no payload and are usually ACKs,
1867 * RESETs or some error conditions that were caught by the stack.
1869 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1870 const CAResponseResult_t responseResult, const CAMessageType_t type,
1871 const uint8_t numOptions, const CAHeaderOption_t *options,
1872 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1873 CADataType_t dataType)
1875 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1877 if (endPoint->flags & CA_MULTICAST)
1879 OIC_LOG(ERROR, TAG, "It is unnecessary to respond to a multicast request");
1883 CAResponseInfo_t respInfo = { .result = responseResult };
1884 respInfo.info.messageId = coapID;
1885 respInfo.info.numOptions = numOptions;
1887 if (respInfo.info.numOptions)
1889 respInfo.info.options =
1890 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1891 memcpy (respInfo.info.options, options,
1892 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1896 respInfo.info.payload = NULL;
1897 respInfo.info.token = token;
1898 respInfo.info.tokenLength = tokenLength;
1899 respInfo.info.type = type;
1900 respInfo.info.resourceUri = OICStrdup (resourceUri);
1901 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1902 respInfo.info.dataType = dataType;
1904 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1905 // Add the destination to route option from the endpoint->routeData.
1906 bool doPost = false;
1907 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1908 if(OC_STACK_OK != result)
1910 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1911 OICFree (respInfo.info.resourceUri);
1912 OICFree (respInfo.info.options);
1917 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1918 CARequestInfo_t reqInfo = {.method = CA_POST };
1919 /* The following initialization is not done in a single initializer block as in
1920 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1921 * does not have designated initalizers. This is a work-around for now.
1923 reqInfo.info.type = CA_MSG_NONCONFIRM;
1924 reqInfo.info.messageId = coapID;
1925 reqInfo.info.tokenLength = tokenLength;
1926 reqInfo.info.token = token;
1927 reqInfo.info.numOptions = respInfo.info.numOptions;
1928 reqInfo.info.payload = NULL;
1929 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1930 if (reqInfo.info.numOptions)
1932 reqInfo.info.options =
1933 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1934 if (NULL == reqInfo.info.options)
1936 OIC_LOG(ERROR, TAG, "Calloc failed");
1937 OICFree (reqInfo.info.resourceUri);
1938 OICFree (respInfo.info.resourceUri);
1939 OICFree (respInfo.info.options);
1940 return OC_STACK_NO_MEMORY;
1942 memcpy (reqInfo.info.options, respInfo.info.options,
1943 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1946 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1947 OICFree (reqInfo.info.resourceUri);
1948 OICFree (reqInfo.info.options);
1949 OICFree (respInfo.info.resourceUri);
1950 OICFree (respInfo.info.options);
1951 if (CA_STATUS_OK != caResult)
1953 OIC_LOG(ERROR, TAG, "CASendRequest error");
1954 return CAResultToOCResult(caResult);
1960 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1962 // resourceUri in the info field is cloned in the CA layer and
1963 // thus ownership is still here.
1964 OICFree (respInfo.info.resourceUri);
1965 OICFree (respInfo.info.options);
1966 if(CA_STATUS_OK != caResult)
1968 OIC_LOG(ERROR, TAG, "CASendResponse error");
1969 return CAResultToOCResult(caResult);
1972 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1976 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1978 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1979 OCStackResult result = OC_STACK_ERROR;
1980 if(!protocolRequest)
1982 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1983 return OC_STACK_INVALID_PARAM;
1986 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1987 protocolRequest->tokenLength);
1990 OIC_LOG(INFO, TAG, "This is a new Server Request");
1991 result = AddServerRequest(&request, protocolRequest->coapID,
1992 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1993 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1994 protocolRequest->observationOption, protocolRequest->qos,
1995 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1996 protocolRequest->payload, protocolRequest->requestToken,
1997 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1998 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1999 &protocolRequest->devAddr);
2000 if (OC_STACK_OK != result)
2002 OIC_LOG(ERROR, TAG, "Error adding server request");
2008 OIC_LOG(ERROR, TAG, "Out of Memory");
2009 return OC_STACK_NO_MEMORY;
2012 if(!protocolRequest->reqMorePacket)
2014 request->requestComplete = 1;
2019 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
2022 if(request->requestComplete)
2024 OIC_LOG(INFO, TAG, "This Server Request is complete");
2025 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2026 OCResource *resource = NULL;
2027 result = DetermineResourceHandling (request, &resHandling, &resource);
2028 if (result == OC_STACK_OK)
2030 result = ProcessRequest(resHandling, resource, request);
2035 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2036 result = OC_STACK_CONTINUE;
2041 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2043 OIC_TRACE_MARK(%s:OCHandleRequests:%s, TAG, requestInfo->info.resourceUri);
2044 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2046 OCStackResult requestResult = OC_STACK_ERROR;
2048 if(myStackMode == OC_CLIENT)
2050 //TODO: should the client be responding to requests?
2054 OCServerProtocolRequest serverRequest = {0};
2056 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2058 char * uriWithoutQuery = NULL;
2059 char * query = NULL;
2061 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2063 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2065 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2068 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2069 OIC_LOG_V(INFO, TAG, "Query : %s", query);
2071 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2073 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2074 OICFree(uriWithoutQuery);
2078 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2079 OICFree(uriWithoutQuery);
2086 if(strlen(query) < MAX_QUERY_LENGTH)
2088 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2093 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2099 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2101 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2102 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2103 if (!serverRequest.payload)
2105 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2108 memcpy (serverRequest.payload, requestInfo->info.payload,
2109 requestInfo->info.payloadSize);
2113 serverRequest.reqTotalSize = 0;
2116 switch (requestInfo->method)
2119 serverRequest.method = OC_REST_GET;
2122 serverRequest.method = OC_REST_PUT;
2125 serverRequest.method = OC_REST_POST;
2128 serverRequest.method = OC_REST_DELETE;
2131 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2132 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2133 requestInfo->info.type, requestInfo->info.numOptions,
2134 requestInfo->info.options, requestInfo->info.token,
2135 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2137 OICFree(serverRequest.payload);
2141 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2142 requestInfo->info.tokenLength);
2144 serverRequest.tokenLength = requestInfo->info.tokenLength;
2145 if (serverRequest.tokenLength) {
2147 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2149 if (!serverRequest.requestToken)
2151 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2152 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2153 requestInfo->info.type, requestInfo->info.numOptions,
2154 requestInfo->info.options, requestInfo->info.token,
2155 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2157 OICFree(serverRequest.payload);
2160 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2163 switch (requestInfo->info.acceptFormat)
2165 case CA_FORMAT_APPLICATION_CBOR:
2166 serverRequest.acceptFormat = OC_FORMAT_CBOR;
2168 case CA_FORMAT_UNDEFINED:
2169 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2172 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2175 if (requestInfo->info.type == CA_MSG_CONFIRM)
2177 serverRequest.qos = OC_HIGH_QOS;
2181 serverRequest.qos = OC_LOW_QOS;
2183 // CA does not need the following field
2184 // Are we sure CA does not need them? how is it responding to multicast
2185 serverRequest.delayedResNeeded = 0;
2187 serverRequest.coapID = requestInfo->info.messageId;
2189 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2191 // copy vendor specific header options
2192 uint8_t tempNum = (requestInfo->info.numOptions);
2194 // Assume no observation requested and it is a pure GET.
2195 // If obs registration/de-registration requested it'll be fetched from the
2196 // options in GetObserveHeaderOption()
2197 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2199 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2200 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2203 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2204 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2205 requestInfo->info.type, requestInfo->info.numOptions,
2206 requestInfo->info.options, requestInfo->info.token,
2207 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2209 OICFree(serverRequest.payload);
2210 OICFree(serverRequest.requestToken);
2214 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2215 if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2217 serverRequest.rcvdVendorSpecificHeaderOptions = (OCHeaderOption*) OICCalloc(tempNum, sizeof(OCHeaderOption));
2218 if (NULL == serverRequest.rcvdVendorSpecificHeaderOptions)
2220 OIC_LOG(ERROR, TAG, "Failed to allocated memory to vnd header options!");
2221 OICFree(serverRequest.payload);
2222 OICFree(serverRequest.requestToken);
2226 memcpy (serverRequest.rcvdVendorSpecificHeaderOptions, requestInfo->info.options,
2227 sizeof(CAHeaderOption_t)*tempNum);
2230 requestResult = HandleStackRequests (&serverRequest);
2232 // Send ACK to client as precursor to slow response
2233 if (requestResult == OC_STACK_SLOW_RESOURCE)
2235 if (requestInfo->info.type == CA_MSG_CONFIRM)
2237 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2238 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2243 if (requestResult == OC_STACK_RESOURCE_ERROR
2244 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2246 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2249 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2251 if (requestResult == OC_STACK_RESOURCE_ERROR)
2253 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2255 else if (!OCResultToSuccess(requestResult))
2257 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2261 else if(!OCResultToSuccess(requestResult))
2263 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2265 // Delete observer node if it is OBSERVE failure from app
2266 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2268 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2271 CAResponseResult_t stackResponse =
2272 OCToCAStackResult(requestResult, serverRequest.method);
2274 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2275 requestInfo->info.type, requestInfo->info.numOptions,
2276 requestInfo->info.options, requestInfo->info.token,
2277 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2280 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2281 // The token is copied in there, and is thus still owned by this function.
2282 OICFree(serverRequest.payload);
2283 OICFree(serverRequest.requestToken);
2284 OICFree(serverRequest.rcvdVendorSpecificHeaderOptions);
2285 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2288 //This function will be called back by CA layer when a request is received
2289 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2291 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2292 OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2295 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2302 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2307 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2308 #ifdef ROUTING_GATEWAY
2309 bool needRIHandling = false;
2310 bool isEmptyMsg = false;
2312 * Routing manager is going to update either of endpoint or request or both.
2313 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2314 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2315 * destination. It can also remove "RM" coap header option before passing request / response to
2316 * RI as this option will make no sense to either RI or application.
2318 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2319 &needRIHandling, &isEmptyMsg);
2320 if(OC_STACK_OK != ret || !needRIHandling)
2322 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2329 * Put source in sender endpoint so that the next packet from application can be routed to
2330 * proper destination and remove RM header option.
2332 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2333 (uint8_t *) &(requestInfo->info.numOptions),
2334 (CAEndpoint_t *) endPoint);
2336 #ifdef ROUTING_GATEWAY
2340 * In Gateways, the MSGType in route option is used to check if the actual
2341 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2342 * EMPTY response is sent in the form of POST request which need to be changed
2343 * to a EMPTY response by RM. This translation is done in this part of the code.
2345 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2346 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2347 .info.messageId = requestInfo->info.messageId,
2348 .info.type = CA_MSG_ACKNOWLEDGE};
2349 OCHandleResponse(endPoint, &respInfo);
2355 // Normal handling of the packet
2356 OCHandleRequests(endPoint, requestInfo);
2358 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2362 //-----------------------------------------------------------------------------
2364 //-----------------------------------------------------------------------------
2366 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2369 !raInfo->username ||
2370 !raInfo->hostname ||
2371 !raInfo->xmpp_domain)
2374 return OC_STACK_INVALID_PARAM;
2376 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2377 gRASetInfo = (result == OC_STACK_OK)? true : false;
2383 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2387 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2390 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2392 OC_UNUSED(serverFlags);
2393 OC_UNUSED(clientFlags);
2395 OIC_LOG(DEBUG, TAG, "call OCInit1");
2396 return OCInit2(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS, OC_DEFAULT_ADAPTER);
2399 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2400 OCTransportAdapter transportType)
2402 if(stackState == OC_STACK_INITIALIZED)
2404 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2405 OCStop() between them are ignored.");
2409 #ifndef ROUTING_GATEWAY
2410 if (OC_GATEWAY == mode)
2412 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2413 return OC_STACK_INVALID_PARAM;
2420 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2421 return OC_STACK_ERROR;
2425 OCStackResult result = OC_STACK_ERROR;
2426 OIC_LOG(INFO, TAG, "Entering OCInit");
2429 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2430 || (mode == OC_GATEWAY)))
2432 OIC_LOG(ERROR, TAG, "Invalid mode");
2433 return OC_STACK_ERROR;
2437 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2439 caglobals.client = true;
2441 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2443 caglobals.server = true;
2446 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2447 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2449 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2451 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2452 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2454 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2457 defaultDeviceHandler = NULL;
2458 defaultDeviceHandlerCallbackParameter = NULL;
2460 result = InitializeScheduleResourceList();
2461 VERIFY_SUCCESS(result, OC_STACK_OK);
2463 result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2464 VERIFY_SUCCESS(result, OC_STACK_OK);
2466 result = CAResultToOCResult(OCSelectNetwork(transportType));
2467 VERIFY_SUCCESS(result, OC_STACK_OK);
2469 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2470 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2471 VERIFY_SUCCESS(result, OC_STACK_OK);
2473 switch (myStackMode)
2476 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2477 result = CAResultToOCResult(CAStartDiscoveryServer());
2478 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2481 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2482 result = CAResultToOCResult(CAStartListeningServer());
2483 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2485 case OC_CLIENT_SERVER:
2487 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2488 result = CAResultToOCResult(CAStartListeningServer());
2489 if(result == OC_STACK_OK)
2491 result = CAResultToOCResult(CAStartDiscoveryServer());
2495 VERIFY_SUCCESS(result, OC_STACK_OK);
2498 CARegisterKeepAliveHandler(OCHandleKeepAliveConnCB);
2501 #ifdef WITH_PRESENCE
2502 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2503 #endif // WITH_PRESENCE
2505 //Update Stack state to initialized
2506 stackState = OC_STACK_INITIALIZED;
2508 // Initialize resource
2509 if(myStackMode != OC_CLIENT)
2511 result = initResources();
2514 // Initialize the SRM Policy Engine
2515 if(result == OC_STACK_OK)
2517 result = SRMInitPolicyEngine();
2518 // TODO after BeachHead delivery: consolidate into single SRMInit()
2520 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2521 RMSetStackMode(mode);
2522 #ifdef ROUTING_GATEWAY
2523 if (OC_GATEWAY == myStackMode)
2525 result = RMInitialize();
2531 if (result == OC_STACK_OK)
2533 result = OCInitializeKeepAlive(myStackMode);
2537 InitializeObserverList();
2540 if(result != OC_STACK_OK)
2542 OIC_LOG(ERROR, TAG, "Stack initialization error");
2543 TerminateScheduleResourceList();
2544 deleteAllResources();
2546 stackState = OC_STACK_UNINITIALIZED;
2551 OCStackResult OCStop()
2553 OIC_LOG(INFO, TAG, "Entering OCStop");
2555 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2557 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2560 else if (stackState != OC_STACK_INITIALIZED)
2562 OIC_LOG(INFO, TAG, "Stack not initialized");
2563 return OC_STACK_ERROR;
2566 // unset cautil config
2567 CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2568 CAUtilSetBTConfigure(configs);
2570 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2572 CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2573 OCDefaultConnectionStateChangedHandler);
2575 #ifdef WITH_PRESENCE
2576 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2577 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2578 presenceResource.presenceTTL = 0;
2579 presenceState = OC_PRESENCE_UNINITIALIZED;
2580 #endif // WITH_PRESENCE
2582 #ifdef ROUTING_GATEWAY
2583 if (OC_GATEWAY == myStackMode)
2590 OCTerminateKeepAlive(myStackMode);
2593 TerminateScheduleResourceList();
2594 // Remove all observers
2595 DeleteObserverList();
2596 // Free memory dynamically allocated for resources
2597 deleteAllResources();
2598 // Remove all the client callbacks
2599 DeleteClientCBList();
2600 // Terminate connectivity-abstraction layer.
2603 // De-init the SRM Policy Engine
2604 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2605 SRMDeInitPolicyEngine();
2607 // Destroy Observer List Mutex
2608 TerminateObserverList();
2610 stackState = OC_STACK_UNINITIALIZED;
2614 OCStackResult OCStartMulticastServer()
2616 if(stackState != OC_STACK_INITIALIZED)
2618 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2619 return OC_STACK_ERROR;
2621 CAResult_t ret = CAStartListeningServer();
2622 if (CA_STATUS_OK != ret)
2624 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2625 return OC_STACK_ERROR;
2630 OCStackResult OCStopMulticastServer()
2632 CAResult_t ret = CAStopListeningServer();
2633 if (CA_STATUS_OK != ret)
2635 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2636 return OC_STACK_ERROR;
2641 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2646 return CA_MSG_CONFIRM;
2651 return CA_MSG_NONCONFIRM;
2655 OCStackResult ParseRequestUri(const char *fullUri,
2656 OCTransportAdapter adapter,
2657 OCTransportFlags flags,
2658 OCDevAddr **devAddr,
2660 char **resourceType)
2662 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2664 OCStackResult result = OC_STACK_OK;
2665 OCDevAddr *da = NULL;
2669 // provide defaults for all returned values
2676 *resourceUri = NULL;
2680 *resourceType = NULL;
2683 // delimit url prefix, if any
2684 const char *start = fullUri;
2685 char *slash2 = strstr(start, "//");
2690 char *slash = strchr(start, '/');
2693 return OC_STACK_INVALID_URI;
2696 // process url scheme
2697 size_t prefixLen = slash2 - fullUri;
2701 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2702 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2708 // TODO: this logic should come in with unit tests exercising the various strings
2709 // processs url prefix, if any
2710 size_t urlLen = slash - start;
2714 if (urlLen && devAddr)
2715 { // construct OCDevAddr
2716 if (start[0] == '[')
2718 char *close = strchr(++start, ']');
2719 if (!close || close > slash)
2721 return OC_STACK_INVALID_URI;
2724 if (close[1] == ':')
2731 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2735 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2737 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2741 char *dot = strchr(start, '.');
2742 if (dot && dot < slash)
2744 colon = strchr(start, ':');
2745 end = (colon && colon < slash) ? colon : slash;
2750 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2754 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2756 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2764 if (len >= sizeof(da->addr))
2766 return OC_STACK_INVALID_URI;
2768 // collect port, if any
2769 if (colon && colon < slash)
2771 for (colon++; colon < slash; colon++)
2774 if (c < '0' || c > '9')
2776 return OC_STACK_INVALID_URI;
2778 port = 10 * port + c - '0';
2783 if (len >= sizeof(da->addr))
2785 return OC_STACK_INVALID_URI;
2788 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2791 return OC_STACK_NO_MEMORY;
2794 // Decode address per RFC 6874.
2795 result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2796 if (result != OC_STACK_OK)
2803 da->adapter = adapter;
2805 if (!strncmp(fullUri, "coaps", 5))
2807 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2812 // process resource uri, if any
2814 { // request uri and query
2815 size_t ulen = strlen(slash); // resource uri length
2816 size_t tlen = 0; // resource type length
2819 static const char strPresence[] = "/oic/ad?rt=";
2820 static const size_t lenPresence = sizeof(strPresence) - 1;
2821 if (!strncmp(slash, strPresence, lenPresence))
2823 type = slash + lenPresence;
2824 tlen = ulen - lenPresence;
2829 *resourceUri = (char *)OICMalloc(ulen + 1);
2832 result = OC_STACK_NO_MEMORY;
2835 OICStrcpy(*resourceUri, (ulen + 1), slash);
2838 if (type && resourceType)
2840 *resourceType = (char *)OICMalloc(tlen + 1);
2843 result = OC_STACK_NO_MEMORY;
2847 OICStrcpy(*resourceType, (tlen+1), type);
2854 // free all returned values
2861 OICFree(*resourceUri);
2865 OICFree(*resourceType);
2870 #ifdef WITH_PRESENCE
2871 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2875 char uri[CA_MAX_URI_LENGTH];
2877 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2879 *requestUri = OICStrdup(uri);
2882 return OC_STACK_NO_MEMORY;
2887 #endif // WITH_PRESENCE
2890 * Discover or Perform requests on a specified resource
2892 OCStackResult OCDoResource(OCDoHandle *handle,
2894 const char *requestUri,
2895 const OCDevAddr *destination,
2897 OCConnectivityType connectivityType,
2898 OCQualityOfService qos,
2899 OCCallbackData *cbData,
2900 OCHeaderOption *options,
2903 OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
2904 connectivityType, qos, cbData, options, numOptions);
2906 // This is the owner of the payload object, so we free it
2907 OCPayloadDestroy(payload);
2912 * Discover or Perform requests on a specified resource
2914 OCStackResult OCDoRequest(OCDoHandle *handle,
2916 const char *requestUri,
2917 const OCDevAddr *destination,
2919 OCConnectivityType connectivityType,
2920 OCQualityOfService qos,
2921 OCCallbackData *cbData,
2922 OCHeaderOption *options,
2925 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2926 OIC_TRACE_BEGIN(%s:OCDoRequest, TAG);
2928 // Validate input parameters
2929 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2930 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2932 OCStackResult result = OC_STACK_ERROR;
2933 CAResult_t caResult;
2934 CAToken_t token = NULL;
2935 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2936 ClientCB *clientCB = NULL;
2937 OCDoHandle resHandle = NULL;
2938 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2939 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2941 OCTransportAdapter adapter;
2942 OCTransportFlags flags;
2943 // the request contents are put here
2944 CARequestInfo_t requestInfo = {.method = CA_GET};
2945 // requestUri will be parsed into the following three variables
2946 OCDevAddr *devAddr = NULL;
2947 char *resourceUri = NULL;
2948 char *resourceType = NULL;
2951 * Support original behavior with address on resourceUri argument.
2953 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2954 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2958 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2959 if (result != OC_STACK_OK)
2961 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2965 else if (!checkProxyUri(options, numOptions))
2967 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2974 case OC_REST_OBSERVE:
2975 case OC_REST_OBSERVE_ALL:
2976 requestInfo.method = CA_GET;
2979 requestInfo.method = CA_PUT;
2982 requestInfo.method = CA_POST;
2984 case OC_REST_DELETE:
2985 requestInfo.method = CA_DELETE;
2987 case OC_REST_DISCOVER:
2988 #ifdef WITH_PRESENCE
2989 case OC_REST_PRESENCE:
2991 if (destination || devAddr)
2993 requestInfo.isMulticast = false;
2997 tmpDevAddr.adapter = adapter;
2998 tmpDevAddr.flags = flags;
2999 destination = &tmpDevAddr;
3000 requestInfo.isMulticast = true;
3003 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
3004 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
3005 // replacing method type with GET.
3006 requestInfo.method = CA_GET;
3009 result = OC_STACK_INVALID_METHOD;
3013 if (!devAddr && !destination)
3015 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
3016 result = OC_STACK_INVALID_PARAM;
3020 /* If not original behavior, use destination argument */
3021 if (destination && !devAddr)
3023 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
3026 result = OC_STACK_NO_MEMORY;
3029 OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
3030 *devAddr = *destination;
3035 OIC_LOG_V(INFO_PRIVATE, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
3036 if (!requestInfo.isMulticast)
3038 OIC_LOG_V(DEBUG, TAG, "remoteAddr of devAddr : [%s]:[%d]",
3039 devAddr->addr, devAddr->port);
3043 resHandle = GenerateInvocationHandle();
3046 result = OC_STACK_NO_MEMORY;
3050 caResult = CAGenerateToken(&token, tokenLength);
3051 if (caResult != CA_STATUS_OK)
3053 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3054 result= OC_STACK_ERROR;
3058 // fill in request data
3059 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3060 requestInfo.info.token = token;
3061 requestInfo.info.tokenLength = tokenLength;
3063 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3065 result = CreateObserveHeaderOption (&(requestInfo.info.options),
3066 options, numOptions, OC_OBSERVE_REGISTER);
3067 if (result != OC_STACK_OK)
3071 requestInfo.info.numOptions = numOptions + 1;
3075 requestInfo.info.numOptions = numOptions;
3076 requestInfo.info.options =
3077 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3078 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3079 numOptions * sizeof(CAHeaderOption_t));
3082 CopyDevAddrToEndpoint(devAddr, &endpoint);
3087 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3090 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3093 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3097 requestInfo.info.payload = NULL;
3098 requestInfo.info.payloadSize = 0;
3099 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3102 // prepare for response
3103 #ifdef WITH_PRESENCE
3104 if (method == OC_REST_PRESENCE)
3106 char *presenceUri = NULL;
3107 result = OCPreparePresence(&endpoint, &presenceUri,
3108 requestInfo.isMulticast);
3109 if (OC_STACK_OK != result)
3114 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3115 // Presence notification will form a canonical uri to
3116 // look for callbacks into the application.
3119 OICFree(resourceUri);
3121 resourceUri = presenceUri;
3125 // update resourceUri onto requestInfo after check presence uri
3126 requestInfo.info.resourceUri = resourceUri;
3128 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3129 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3130 method, devAddr, resourceUri, resourceType, ttl);
3131 if (OC_STACK_OK != result)
3136 cbData = NULL; // Client CB list entry now owns it
3137 token = NULL; // Client CB list entry now owns it
3138 devAddr = NULL; // Client CB list entry now owns it
3139 resourceUri = NULL; // Client CB list entry now owns it
3140 resourceType = NULL; // Client CB list entry now owns it
3142 #ifdef WITH_PRESENCE
3143 if (method == OC_REST_PRESENCE)
3145 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3149 *handle = resHandle;
3157 result = OCSendRequest(&endpoint, &requestInfo);
3158 if (OC_STACK_OK != result)
3165 *handle = resHandle;
3169 if (result != OC_STACK_OK)
3171 OIC_LOG(ERROR, TAG, "OCDoResource error");
3172 if (NULL != cbData && NULL != cbData->cd)
3174 cbData->cd(cbData->context);
3176 FindAndDeleteClientCB(clientCB);
3177 CADestroyToken(token);
3185 OICFree(requestInfo.info.payload);
3187 OICFree(resourceUri);
3188 OICFree(resourceType);
3189 OICFree(requestInfo.info.options);
3194 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3198 * This ftn is implemented one of two ways in the case of observation:
3200 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3201 * Remove the callback associated on client side.
3202 * When the next notification comes in from server,
3203 * reply with RESET message to server.
3204 * Keep in mind that the server will react to RESET only
3205 * if the last notification was sent as CON
3207 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3208 * and it is associated with an observe request
3209 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3210 * Send CON Observe request to server with
3211 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3212 * Remove the callback associated on client side.
3214 OCStackResult ret = OC_STACK_OK;
3215 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3216 CARequestInfo_t requestInfo = {.method = CA_GET};
3220 return OC_STACK_INVALID_PARAM;
3223 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3226 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3227 return OC_STACK_ERROR;
3230 switch (clientCB->method)
3232 case OC_REST_OBSERVE:
3233 case OC_REST_OBSERVE_ALL:
3235 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3237 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3239 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
3241 FindAndDeleteClientCB(clientCB);
3245 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3247 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3248 requestInfo.info.token = clientCB->token;
3249 requestInfo.info.tokenLength = clientCB->tokenLength;
3251 if (CreateObserveHeaderOption (&(requestInfo.info.options),
3252 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3254 return OC_STACK_ERROR;
3256 requestInfo.info.numOptions = numOptions + 1;
3257 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3260 ret = OCSendRequest(&endpoint, &requestInfo);
3262 if (requestInfo.info.options)
3264 OICFree (requestInfo.info.options);
3266 if (requestInfo.info.resourceUri)
3268 OICFree (requestInfo.info.resourceUri);
3273 case OC_REST_DISCOVER:
3274 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3275 clientCB->requestUri);
3276 FindAndDeleteClientCB(clientCB);
3279 #ifdef WITH_PRESENCE
3280 case OC_REST_PRESENCE:
3281 FindAndDeleteClientCB(clientCB);
3287 case OC_REST_DELETE:
3288 OIC_LOG_V(INFO, TAG, "Cancelling request callback for resource %s",
3289 clientCB->requestUri);
3290 FindAndDeleteClientCB(clientCB);
3294 ret = OC_STACK_INVALID_METHOD;
3302 * @brief Register Persistent storage callback.
3303 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3305 * OC_STACK_OK - No errors; Success
3306 * OC_STACK_INVALID_PARAM - Invalid parameter
3308 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3310 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3311 if(!persistentStorageHandler)
3313 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3314 return OC_STACK_INVALID_PARAM;
3318 if( !persistentStorageHandler->open ||
3319 !persistentStorageHandler->close ||
3320 !persistentStorageHandler->read ||
3321 !persistentStorageHandler->unlink ||
3322 !persistentStorageHandler->write)
3324 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3325 return OC_STACK_INVALID_PARAM;
3328 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3331 #ifdef WITH_PRESENCE
3333 OCStackResult OCProcessPresence()
3335 OCStackResult result = OC_STACK_OK;
3337 // the following line floods the log with messages that are irrelevant
3338 // to most purposes. Uncomment as needed.
3339 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3340 ClientCB* cbNode = NULL;
3341 ClientCB* tempcbNode = NULL;
3342 OCClientResponse clientResponse;
3343 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3345 LL_FOREACH_SAFE(cbList, cbNode, tempcbNode)
3347 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3352 uint32_t now = GetTicks(0);
3353 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3354 cbNode->presence->TTLlevel);
3355 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3357 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3362 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3364 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3365 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3367 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3369 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3371 clientResponse.sequenceNumber = 0;
3372 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3373 clientResponse.devAddr = *cbNode->devAddr;
3374 FixUpClientResponse(&clientResponse);
3375 clientResponse.payload = NULL;
3377 // Increment the TTLLevel (going to a next state), so we don't keep
3378 // sending presence notification to client.
3379 cbNode->presence->TTLlevel++;
3380 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3381 cbNode->presence->TTLlevel);
3383 OIC_LOG(INFO, TAG, "Before calling into application address space for presence timeout");
3384 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3385 OIC_LOG(INFO, TAG, "After calling into application address space for presence timeout");
3387 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3389 FindAndDeleteClientCB(cbNode);
3394 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3399 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3400 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3401 CARequestInfo_t requestInfo = {.method = CA_GET};
3403 OIC_LOG(DEBUG, TAG, "time to test server presence");
3405 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3407 requestData.type = CA_MSG_NONCONFIRM;
3408 requestData.token = cbNode->token;
3409 requestData.tokenLength = cbNode->tokenLength;
3410 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3411 requestInfo.method = CA_GET;
3412 requestInfo.info = requestData;
3414 result = OCSendRequest(&endpoint, &requestInfo);
3415 if (OC_STACK_OK != result)
3420 cbNode->presence->TTLlevel++;
3421 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3424 if (result != OC_STACK_OK)
3426 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3431 #endif // WITH_PRESENCE
3433 OCStackResult OCProcess()
3435 if (stackState == OC_STACK_UNINITIALIZED)
3437 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3438 return OC_STACK_ERROR;
3440 #ifdef WITH_PRESENCE
3441 OCProcessPresence();
3443 CAHandleRequestResponse();
3445 #ifdef ROUTING_GATEWAY
3450 OCProcessKeepAlive();
3455 #ifdef WITH_PRESENCE
3456 OCStackResult OCStartPresence(const uint32_t ttl)
3458 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3459 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3460 OCChangeResourceProperty(
3461 &(((OCResource *)presenceResource.handle)->resourceProperties),
3464 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3466 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3467 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3471 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3472 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3476 presenceResource.presenceTTL = ttl;
3479 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3482 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3484 presenceState = OC_PRESENCE_INITIALIZED;
3486 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3488 CAToken_t caToken = NULL;
3489 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3490 if (caResult != CA_STATUS_OK)
3492 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3493 CADestroyToken(caToken);
3494 return OC_STACK_ERROR;
3497 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3498 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3499 CADestroyToken(caToken);
3502 // Each time OCStartPresence is called
3503 // a different random 32-bit integer number is used
3504 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3506 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3507 OC_PRESENCE_TRIGGER_CREATE);
3510 OCStackResult OCStopPresence()
3512 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3513 OCStackResult result = OC_STACK_ERROR;
3515 if(presenceResource.handle)
3517 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3519 // make resource inactive
3520 result = OCChangeResourceProperty(
3521 &(((OCResource *) presenceResource.handle)->resourceProperties),
3525 if(result != OC_STACK_OK)
3528 "Changing the presence resource properties to ACTIVE not successful");
3532 return SendStopNotification();
3536 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3537 void* callbackParameter)
3539 defaultDeviceHandler = entityHandler;
3540 defaultDeviceHandlerCallbackParameter = callbackParameter;
3545 OCStackResult OCCreateResource(OCResourceHandle *handle,
3546 const char *resourceTypeName,
3547 const char *resourceInterfaceName,
3548 const char *uri, OCEntityHandler entityHandler,
3549 void* callbackParam,
3550 uint8_t resourceProperties)
3553 OCResource *pointer = NULL;
3554 OCStackResult result = OC_STACK_ERROR;
3556 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3558 if(myStackMode == OC_CLIENT)
3560 return OC_STACK_INVALID_PARAM;
3562 // Validate parameters
3563 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3565 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3566 return OC_STACK_INVALID_URI;
3568 // Is it presented during resource discovery?
3569 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3571 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3572 return OC_STACK_INVALID_PARAM;
3575 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3577 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3581 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3583 // Make sure resourceProperties bitmask has allowed properties specified
3584 if (resourceProperties
3585 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3586 OC_EXPLICIT_DISCOVERABLE
3595 OIC_LOG(ERROR, TAG, "Invalid property");
3596 return OC_STACK_INVALID_PARAM;
3599 // If the headResource is NULL, then no resources have been created...
3600 pointer = headResource;
3603 // At least one resources is in the resource list, so we need to search for
3604 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3607 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3609 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3610 return OC_STACK_INVALID_PARAM;
3612 pointer = pointer->next;
3615 // Create the pointer and insert it into the resource list
3616 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3619 result = OC_STACK_NO_MEMORY;
3622 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3624 insertResource(pointer);
3627 pointer->uri = OICStrdup(uri);
3630 result = OC_STACK_NO_MEMORY;
3634 // Set properties. Set OC_ACTIVE
3635 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3638 // Add the resourcetype to the resource
3639 result = BindResourceTypeToResource(pointer, resourceTypeName);
3640 if (result != OC_STACK_OK)
3642 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3646 // Add the resourceinterface to the resource
3647 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3648 if (result != OC_STACK_OK)
3650 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3654 // If an entity handler has been passed, attach it to the newly created
3655 // resource. Otherwise, set the default entity handler.
3658 pointer->entityHandler = entityHandler;
3659 pointer->entityHandlerCallbackParam = callbackParam;
3663 pointer->entityHandler = defaultResourceEHandler;
3664 pointer->entityHandlerCallbackParam = NULL;
3667 // Initialize a pointer indicating child resources in case of collection
3668 pointer->rsrcChildResourcesHead = NULL;
3671 result = OC_STACK_OK;
3673 #ifdef WITH_PRESENCE
3674 if (presenceResource.handle)
3676 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3677 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3681 if (result != OC_STACK_OK)
3683 // Deep delete of resource and other dynamic elements that it contains
3684 deleteResource(pointer);
3689 OCStackResult OCBindResource(
3690 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3692 OCResource *resource = NULL;
3693 OCChildResource *tempChildResource = NULL;
3694 OCChildResource *newChildResource = NULL;
3696 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3698 // Validate parameters
3699 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3700 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3701 // Container cannot contain itself
3702 if (collectionHandle == resourceHandle)
3704 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3705 return OC_STACK_INVALID_PARAM;
3708 // Use the handle to find the resource in the resource linked list
3709 resource = findResource((OCResource *) collectionHandle);
3712 OIC_LOG(ERROR, TAG, "Collection handle not found");
3713 return OC_STACK_INVALID_PARAM;
3716 // Look for an open slot to add add the child resource.
3717 // If found, add it and return success
3719 tempChildResource = resource->rsrcChildResourcesHead;
3721 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3723 // TODO: what if one of child resource was deregistered without unbinding?
3724 tempChildResource = tempChildResource->next;
3727 // Do memory allocation for child resource
3728 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3729 if(!newChildResource)
3731 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3732 return OC_STACK_ERROR;
3735 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3736 newChildResource->next = NULL;
3738 if(!resource->rsrcChildResourcesHead)
3740 resource->rsrcChildResourcesHead = newChildResource;
3743 tempChildResource->next = newChildResource;
3746 OIC_LOG(INFO, TAG, "resource bound");
3748 #ifdef WITH_PRESENCE
3749 if (presenceResource.handle)
3751 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3752 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3753 OC_PRESENCE_TRIGGER_CHANGE);
3760 OCStackResult OCUnBindResource(
3761 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3763 OCResource *resource = NULL;
3764 OCChildResource *tempChildResource = NULL;
3765 OCChildResource *tempLastChildResource = NULL;
3767 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3769 // Validate parameters
3770 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3771 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3772 // Container cannot contain itself
3773 if (collectionHandle == resourceHandle)
3775 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3776 return OC_STACK_INVALID_PARAM;
3779 // Use the handle to find the resource in the resource linked list
3780 resource = findResource((OCResource *) collectionHandle);
3783 OIC_LOG(ERROR, TAG, "Collection handle not found");
3784 return OC_STACK_INVALID_PARAM;
3787 // Look for an open slot to add add the child resource.
3788 // If found, add it and return success
3789 if(!resource->rsrcChildResourcesHead)
3791 OIC_LOG(INFO, TAG, "resource not found in collection");
3793 // Unable to add resourceHandle, so return error
3794 return OC_STACK_ERROR;
3798 tempChildResource = resource->rsrcChildResourcesHead;
3800 while (tempChildResource)
3802 if(tempChildResource->rsrcResource == resourceHandle)
3804 // if resource going to be unbinded is the head one.
3805 if( tempChildResource == resource->rsrcChildResourcesHead )
3807 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3808 OICFree(resource->rsrcChildResourcesHead);
3809 resource->rsrcChildResourcesHead = temp;
3814 OCChildResource *temp = tempChildResource->next;
3815 OICFree(tempChildResource);
3816 if (tempLastChildResource)
3818 tempLastChildResource->next = temp;
3823 OIC_LOG(INFO, TAG, "resource unbound");
3825 // Send notification when resource is unbounded successfully.
3826 #ifdef WITH_PRESENCE
3827 if (presenceResource.handle)
3829 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3830 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3831 OC_PRESENCE_TRIGGER_CHANGE);
3834 tempChildResource = NULL;
3835 tempLastChildResource = NULL;
3841 tempLastChildResource = tempChildResource;
3842 tempChildResource = tempChildResource->next;
3845 OIC_LOG(INFO, TAG, "resource not found in collection");
3847 tempChildResource = NULL;
3848 tempLastChildResource = NULL;
3850 // Unable to add resourceHandle, so return error
3851 return OC_STACK_ERROR;
3854 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3856 if (!resourceItemName)
3860 // Per RFC 6690 only registered values must follow the first rule below.
3861 // At this point in time the only values registered begin with "core", and
3862 // all other values are specified as opaque strings where multiple values
3863 // are separated by a space.
3864 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3866 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3868 if (resourceItemName[index] != '.'
3869 && resourceItemName[index] != '-'
3870 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3871 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3879 for (size_t index = 0; resourceItemName[index]; ++index)
3881 if (resourceItemName[index] == ' '
3882 || resourceItemName[index] == '\t'
3883 || resourceItemName[index] == '\r'
3884 || resourceItemName[index] == '\n')
3894 OCStackResult BindResourceTypeToResource(OCResource* resource,
3895 const char *resourceTypeName)
3897 OCResourceType *pointer = NULL;
3899 OCStackResult result = OC_STACK_ERROR;
3901 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3903 if (!ValidateResourceTypeInterface(resourceTypeName))
3905 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3906 return OC_STACK_INVALID_PARAM;
3909 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3912 result = OC_STACK_NO_MEMORY;
3916 str = OICStrdup(resourceTypeName);
3919 result = OC_STACK_NO_MEMORY;
3922 pointer->resourcetypename = str;
3923 pointer->next = NULL;
3925 insertResourceType(resource, pointer);
3926 result = OC_STACK_OK;
3929 if (result != OC_STACK_OK)
3938 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3939 const char *resourceInterfaceName)
3941 OCResourceInterface *pointer = NULL;
3943 OCStackResult result = OC_STACK_ERROR;
3945 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3947 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3949 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3950 return OC_STACK_INVALID_PARAM;
3953 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3955 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3958 result = OC_STACK_NO_MEMORY;
3962 str = OICStrdup(resourceInterfaceName);
3965 result = OC_STACK_NO_MEMORY;
3968 pointer->name = str;
3970 // Bind the resourceinterface to the resource
3971 insertResourceInterface(resource, pointer);
3973 result = OC_STACK_OK;
3976 if (result != OC_STACK_OK)
3985 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3986 const char *resourceTypeName)
3989 OCStackResult result = OC_STACK_ERROR;
3990 OCResource *resource = NULL;
3992 resource = findResource((OCResource *) handle);
3995 OIC_LOG(ERROR, TAG, "Resource not found");
3996 return OC_STACK_ERROR;
3999 result = BindResourceTypeToResource(resource, resourceTypeName);
4001 #ifdef WITH_PRESENCE
4002 if(presenceResource.handle)
4004 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4005 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4012 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
4013 const char *resourceInterfaceName)
4016 OCStackResult result = OC_STACK_ERROR;
4017 OCResource *resource = NULL;
4019 resource = findResource((OCResource *) handle);
4022 OIC_LOG(ERROR, TAG, "Resource not found");
4023 return OC_STACK_ERROR;
4026 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
4028 #ifdef WITH_PRESENCE
4029 if (presenceResource.handle)
4031 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4032 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4039 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
4041 OCResource *pointer = headResource;
4043 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
4047 *numResources = *numResources + 1;
4048 pointer = pointer->next;
4053 OCResourceHandle OCGetResourceHandle(uint8_t index)
4055 OCResource *pointer = headResource;
4057 for( uint8_t i = 0; i < index && pointer; ++i)
4059 pointer = pointer->next;
4061 return (OCResourceHandle) pointer;
4064 OCStackResult OCDeleteResource(OCResourceHandle handle)
4068 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4069 return OC_STACK_INVALID_PARAM;
4072 OCResource *resource = findResource((OCResource *) handle);
4073 if (resource == NULL)
4075 OIC_LOG(ERROR, TAG, "Resource not found");
4076 return OC_STACK_NO_RESOURCE;
4079 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4081 OIC_LOG(ERROR, TAG, "Error deleting resource");
4082 return OC_STACK_ERROR;
4088 const char *OCGetResourceUri(OCResourceHandle handle)
4090 OCResource *resource = NULL;
4092 resource = findResource((OCResource *) handle);
4095 return resource->uri;
4097 return (const char *) NULL;
4100 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4102 OCResource *resource = NULL;
4104 resource = findResource((OCResource *) handle);
4107 return resource->resourceProperties;
4109 return (OCResourceProperty)-1;
4112 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4113 uint8_t *numResourceTypes)
4115 OCResource *resource = NULL;
4116 OCResourceType *pointer = NULL;
4118 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4119 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4121 *numResourceTypes = 0;
4123 resource = findResource((OCResource *) handle);
4126 pointer = resource->rsrcType;
4129 *numResourceTypes = *numResourceTypes + 1;
4130 pointer = pointer->next;
4136 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4138 OCResourceType *resourceType = NULL;
4140 resourceType = findResourceTypeAtIndex(handle, index);
4143 return resourceType->resourcetypename;
4145 return (const char *) NULL;
4148 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4149 uint8_t *numResourceInterfaces)
4151 OCResourceInterface *pointer = NULL;
4152 OCResource *resource = NULL;
4154 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4155 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4157 *numResourceInterfaces = 0;
4158 resource = findResource((OCResource *) handle);
4161 pointer = resource->rsrcInterface;
4164 *numResourceInterfaces = *numResourceInterfaces + 1;
4165 pointer = pointer->next;
4171 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4173 OCResourceInterface *resourceInterface = NULL;
4175 resourceInterface = findResourceInterfaceAtIndex(handle, index);
4176 if (resourceInterface)
4178 return resourceInterface->name;
4180 return (const char *) NULL;
4183 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4186 OCResource *resource = NULL;
4187 OCChildResource *tempChildResource = NULL;
4190 resource = findResource((OCResource *) collectionHandle);
4196 tempChildResource = resource->rsrcChildResourcesHead;
4198 while(tempChildResource)
4202 return tempChildResource->rsrcResource;
4205 tempChildResource = tempChildResource->next;
4208 // In this case, the number of resource handles in the collection exceeds the index
4209 tempChildResource = NULL;
4213 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4214 OCEntityHandler entityHandler,
4215 void* callbackParam)
4217 OCResource *resource = NULL;
4219 // Validate parameters
4220 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4222 // Use the handle to find the resource in the resource linked list
4223 resource = findResource((OCResource *)handle);
4226 OIC_LOG(ERROR, TAG, "Resource not found");
4227 return OC_STACK_ERROR;
4231 resource->entityHandler = entityHandler;
4232 resource->entityHandlerCallbackParam = callbackParam;
4234 #ifdef WITH_PRESENCE
4235 if (presenceResource.handle)
4237 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4238 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4245 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4247 OCResource *resource = NULL;
4249 resource = findResource((OCResource *)handle);
4252 OIC_LOG(ERROR, TAG, "Resource not found");
4257 return resource->entityHandler;
4260 void incrementSequenceNumber(OCResource * resPtr)
4262 // Increment the sequence number
4263 resPtr->sequenceNum += 1;
4264 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4266 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4271 #ifdef WITH_PRESENCE
4272 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4273 OCPresenceTrigger trigger)
4275 OIC_LOG(INFO, TAG, "SendPresenceNotification");
4276 OCResource *resPtr = NULL;
4277 OCStackResult result = OC_STACK_ERROR;
4278 OCMethod method = OC_REST_PRESENCE;
4279 uint32_t maxAge = 0;
4280 resPtr = findResource((OCResource *) presenceResource.handle);
4283 return OC_STACK_NO_RESOURCE;
4286 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4288 maxAge = presenceResource.presenceTTL;
4290 result = SendAllObserverNotification(method, resPtr, maxAge,
4291 trigger, resourceType, OC_LOW_QOS);
4297 OCStackResult SendStopNotification()
4299 OIC_LOG(INFO, TAG, "SendStopNotification");
4300 OCResource *resPtr = NULL;
4301 OCStackResult result = OC_STACK_ERROR;
4302 OCMethod method = OC_REST_PRESENCE;
4303 resPtr = findResource((OCResource *) presenceResource.handle);
4306 return OC_STACK_NO_RESOURCE;
4309 // maxAge is 0. ResourceType is NULL.
4310 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4316 #endif // WITH_PRESENCE
4317 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4319 OCResource *resPtr = NULL;
4320 OCStackResult result = OC_STACK_ERROR;
4321 OCMethod method = OC_REST_NOMETHOD;
4322 uint32_t maxAge = 0;
4324 OIC_LOG(INFO, TAG, "Notifying all observers");
4325 #ifdef WITH_PRESENCE
4326 if(handle == presenceResource.handle)
4330 #endif // WITH_PRESENCE
4331 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4333 // Verify that the resource exists
4334 resPtr = findResource ((OCResource *) handle);
4337 return OC_STACK_NO_RESOURCE;
4341 //only increment in the case of regular observing (not presence)
4342 incrementSequenceNumber(resPtr);
4343 method = OC_REST_OBSERVE;
4344 maxAge = MAX_OBSERVE_AGE;
4345 #ifdef WITH_PRESENCE
4346 result = SendAllObserverNotification (method, resPtr, maxAge,
4347 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4349 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4356 OCNotifyListOfObservers (OCResourceHandle handle,
4357 OCObservationId *obsIdList,
4358 uint8_t numberOfIds,
4359 const OCRepPayload *payload,
4360 OCQualityOfService qos)
4362 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4364 OCResource *resPtr = NULL;
4365 //TODO: we should allow the server to define this
4366 uint32_t maxAge = MAX_OBSERVE_AGE;
4368 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4369 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4370 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4372 resPtr = findResource ((OCResource *) handle);
4373 if (NULL == resPtr || myStackMode == OC_CLIENT)
4375 return OC_STACK_NO_RESOURCE;
4379 incrementSequenceNumber(resPtr);
4381 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4382 payload, maxAge, qos));
4385 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4387 OIC_TRACE_BEGIN(%s:OCDoResponse, TAG);
4388 OCStackResult result = OC_STACK_ERROR;
4389 OCServerRequest *serverRequest = NULL;
4391 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4393 // Validate input parameters
4394 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4395 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4398 // Get pointer to request info
4399 serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
4402 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4403 result = serverRequest->ehResponseHandler(ehResponse);
4410 //#ifdef DIRECT_PAIRING
4411 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4413 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4414 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4416 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4420 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4423 const OCDPDev_t* OCGetDirectPairedDevices()
4425 return (const OCDPDev_t*)DPGetPairedDevices();
4428 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4429 OCDirectPairingCB resultCallback)
4431 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4432 if(NULL == peer || NULL == pinNumber)
4434 OIC_LOG(ERROR, TAG, "Invalid parameters");
4435 return OC_STACK_INVALID_PARAM;
4437 if (NULL == resultCallback)
4439 OIC_LOG(ERROR, TAG, "Invalid callback");
4440 return OC_STACK_INVALID_CALLBACK;
4443 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4444 pinNumber, (OCDirectPairingResultCB)resultCallback);
4446 //#endif // DIRECT_PAIRING
4448 //-----------------------------------------------------------------------------
4449 // Private internal function definitions
4450 //-----------------------------------------------------------------------------
4451 static OCDoHandle GenerateInvocationHandle()
4453 OCDoHandle handle = NULL;
4454 // Generate token here, it will be deleted when the transaction is deleted
4455 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4458 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4464 #ifdef WITH_PRESENCE
4465 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4466 OCResourceProperty resourceProperties, uint8_t enable)
4470 return OC_STACK_INVALID_PARAM;
4472 if (resourceProperties
4473 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4475 OIC_LOG(ERROR, TAG, "Invalid property");
4476 return OC_STACK_INVALID_PARAM;
4480 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4484 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4490 OCStackResult initResources()
4492 OCStackResult result = OC_STACK_OK;
4494 headResource = NULL;
4495 tailResource = NULL;
4496 // Init Virtual Resources
4497 #ifdef WITH_PRESENCE
4498 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4500 result = OCCreateResource(&presenceResource.handle,
4501 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4503 OC_RSRVD_PRESENCE_URI,
4507 //make resource inactive
4508 result = OCChangeResourceProperty(
4509 &(((OCResource *) presenceResource.handle)->resourceProperties),
4512 #ifndef WITH_ARDUINO
4513 if (result == OC_STACK_OK)
4515 result = SRMInitSecureResources();
4519 if(result == OC_STACK_OK)
4521 CreateResetProfile();
4522 result = OCCreateResource(&deviceResource,
4523 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4524 OC_RSRVD_INTERFACE_DEFAULT,
4525 OC_RSRVD_DEVICE_URI,
4529 if(result == OC_STACK_OK)
4531 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4532 OC_RSRVD_INTERFACE_READ);
4536 if(result == OC_STACK_OK)
4538 result = OCCreateResource(&platformResource,
4539 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4540 OC_RSRVD_INTERFACE_DEFAULT,
4541 OC_RSRVD_PLATFORM_URI,
4545 if(result == OC_STACK_OK)
4547 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4548 OC_RSRVD_INTERFACE_READ);
4555 void insertResource(OCResource *resource)
4559 headResource = resource;
4560 tailResource = resource;
4564 tailResource->next = resource;
4565 tailResource = resource;
4567 resource->next = NULL;
4570 OCResource *findResource(OCResource *resource)
4572 OCResource *pointer = headResource;
4576 if (pointer == resource)
4580 pointer = pointer->next;
4585 void deleteAllResources()
4587 OCResource *pointer = headResource;
4588 OCResource *temp = NULL;
4592 temp = pointer->next;
4593 #ifdef WITH_PRESENCE
4594 if (pointer != (OCResource *) presenceResource.handle)
4596 #endif // WITH_PRESENCE
4597 deleteResource(pointer);
4598 #ifdef WITH_PRESENCE
4600 #endif // WITH_PRESENCE
4603 memset(&platformResource, 0, sizeof(platformResource));
4604 memset(&deviceResource, 0, sizeof(deviceResource));
4606 memset(&brokerResource, 0, sizeof(brokerResource));
4609 SRMDeInitSecureResources();
4611 #ifdef WITH_PRESENCE
4612 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4613 // presence notification attributed to their deletion to be processed.
4614 deleteResource((OCResource *) presenceResource.handle);
4615 memset(&presenceResource, 0, sizeof(presenceResource));
4616 #endif // WITH_PRESENCE
4619 OCStackResult deleteResource(OCResource *resource)
4621 OCResource *prev = NULL;
4622 OCResource *temp = NULL;
4625 OIC_LOG(DEBUG,TAG,"resource is NULL");
4626 return OC_STACK_INVALID_PARAM;
4629 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4631 temp = headResource;
4634 if (temp == resource)
4636 // Invalidate all Resource Properties.
4637 resource->resourceProperties = (OCResourceProperty) 0;
4638 #ifdef WITH_PRESENCE
4639 if(resource != (OCResource *) presenceResource.handle)
4641 #endif // WITH_PRESENCE
4642 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4643 #ifdef WITH_PRESENCE
4646 if(presenceResource.handle)
4648 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4649 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4652 // Delete resource's all observers
4653 DeleteObserverUsingResource(resource);
4655 // Only resource in list.
4656 if (temp == headResource && temp == tailResource)
4658 headResource = NULL;
4659 tailResource = NULL;
4662 else if (temp == headResource)
4664 headResource = temp->next;
4667 else if (temp == tailResource && prev)
4669 tailResource = prev;
4670 tailResource->next = NULL;
4674 prev->next = temp->next;
4677 deleteResourceElements(temp);
4688 return OC_STACK_ERROR;
4691 void deleteResourceElements(OCResource *resource)
4700 OICFree(resource->uri);
4701 resource->uri = NULL;
4703 if (resource->rsrcType)
4705 deleteResourceType(resource->rsrcType);
4706 resource->rsrcType = NULL;
4708 if (resource->rsrcInterface)
4710 deleteResourceInterface(resource->rsrcInterface);
4711 resource->rsrcInterface = NULL;
4713 if (resource->rsrcChildResourcesHead)
4715 unbindChildResources(resource->rsrcChildResourcesHead);
4716 resource->rsrcChildResourcesHead = NULL;
4718 if (resource->rsrcAttributes)
4720 OCDeleteResourceAttributes(resource->rsrcAttributes);
4721 resource->rsrcAttributes = NULL;
4724 resource->entityHandler = NULL;
4728 void deleteResourceType(OCResourceType *resourceType)
4730 OCResourceType *next = NULL;
4732 for (OCResourceType *pointer = resourceType; pointer; pointer = next)
4734 next = pointer->next ? pointer->next : NULL;
4735 if (pointer->resourcetypename)
4737 OICFree(pointer->resourcetypename);
4738 pointer->resourcetypename = NULL;
4744 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4746 OCResourceInterface *next = NULL;
4747 for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
4749 next = pointer->next ? pointer->next : NULL;
4752 OICFree(pointer->name);
4753 pointer->name = NULL;
4759 void unbindChildResources(OCChildResource *head)
4761 OCChildResource *next = NULL;
4762 for (OCChildResource *current = head; current; current = next)
4764 next = current->next;
4769 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
4771 OCAttribute *next = NULL;
4772 for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
4774 next = pointer->next ? pointer->next : NULL;
4775 if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
4777 OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
4778 pointer->attrValue = NULL;
4780 else if (pointer->attrValue)
4782 OICFree(pointer->attrValue);
4783 pointer->attrValue = NULL;
4785 if (pointer->attrName)
4787 OICFree(pointer->attrName);
4788 pointer->attrName = NULL;
4794 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4796 OCResourceType *pointer = NULL;
4797 OCResourceType *previous = NULL;
4798 if (!resource || !resourceType)
4802 // resource type list is empty.
4803 else if (!resource->rsrcType)
4805 resource->rsrcType = resourceType;
4809 pointer = resource->rsrcType;
4813 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4815 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4816 OICFree(resourceType->resourcetypename);
4817 OICFree(resourceType);
4821 pointer = pointer->next;
4826 previous->next = resourceType;
4829 resourceType->next = NULL;
4831 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4834 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4836 OCResource *resource = NULL;
4837 OCResourceType *pointer = NULL;
4839 // Find the specified resource
4840 resource = findResource((OCResource *) handle);
4846 // Make sure a resource has a resourcetype
4847 if (!resource->rsrcType)
4852 // Iterate through the list
4853 pointer = resource->rsrcType;
4854 for(uint8_t i = 0; i< index && pointer; ++i)
4856 pointer = pointer->next;
4861 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4863 if(resourceTypeList && resourceTypeName)
4865 OCResourceType * rtPointer = resourceTypeList;
4866 while(resourceTypeName && rtPointer)
4868 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4869 if(rtPointer->resourcetypename &&
4870 strcmp(resourceTypeName, (const char *)
4871 (rtPointer->resourcetypename)) == 0)
4875 rtPointer = rtPointer->next;
4883 * Insert a new interface into interface linked list only if not already present.
4884 * If alredy present, 2nd arg is free'd.
4885 * Default interface will always be first if present.
4887 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4889 OCResourceInterface *pointer = NULL;
4890 OCResourceInterface *previous = NULL;
4892 newInterface->next = NULL;
4894 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4896 if (!*firstInterface)
4898 // If first interface is not oic.if.baseline, by default add it as first interface type.
4899 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4901 *firstInterface = newInterface;
4905 OCStackResult result = BindResourceInterfaceToResource(resource,
4906 OC_RSRVD_INTERFACE_DEFAULT);
4907 if (result != OC_STACK_OK)
4909 OICFree(newInterface->name);
4910 OICFree(newInterface);
4913 if (*firstInterface)
4915 (*firstInterface)->next = newInterface;
4919 // If once add oic.if.baseline, later too below code take care of freeing memory.
4920 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4922 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4924 OICFree(newInterface->name);
4925 OICFree(newInterface);
4928 // This code will not hit anymore, keeping
4931 newInterface->next = *firstInterface;
4932 *firstInterface = newInterface;
4937 pointer = *firstInterface;
4940 if (strcmp(newInterface->name, pointer->name) == 0)
4942 OICFree(newInterface->name);
4943 OICFree(newInterface);
4947 pointer = pointer->next;
4952 previous->next = newInterface;
4957 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4960 OCResource *resource = NULL;
4961 OCResourceInterface *pointer = NULL;
4963 // Find the specified resource
4964 resource = findResource((OCResource *) handle);
4970 // Make sure a resource has a resourceinterface
4971 if (!resource->rsrcInterface)
4976 // Iterate through the list
4977 pointer = resource->rsrcInterface;
4979 for (uint8_t i = 0; i < index && pointer; ++i)
4981 pointer = pointer->next;
4987 * This function splits the uri using the '?' delimiter.
4988 * "uriWithoutQuery" is the block of characters between the beginning
4989 * till the delimiter or '\0' which ever comes first.
4990 * "query" is whatever is to the right of the delimiter if present.
4991 * No delimiter sets the query to NULL.
4992 * If either are present, they will be malloc'ed into the params 2, 3.
4993 * The first param, *uri is left untouched.
4995 * NOTE: This function does not account for whitespace at the end of the uri NOR
4996 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4997 * part of the query.
4999 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
5003 return OC_STACK_INVALID_URI;
5005 if(!query || !uriWithoutQuery)
5007 return OC_STACK_INVALID_PARAM;
5011 *uriWithoutQuery = NULL;
5013 size_t uriWithoutQueryLen = 0;
5014 size_t queryLen = 0;
5015 size_t uriLen = strlen(uri);
5017 char *pointerToDelimiter = strstr(uri, "?");
5019 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
5020 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
5022 if (uriWithoutQueryLen)
5024 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
5025 if (!*uriWithoutQuery)
5029 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
5033 *query = (char *) OICCalloc(queryLen + 1, 1);
5036 OICFree(*uriWithoutQuery);
5037 *uriWithoutQuery = NULL;
5040 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5046 return OC_STACK_NO_MEMORY;
5049 const char* OCGetServerInstanceIDString(void)
5051 static char sidStr[UUID_STRING_SIZE];
5053 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5055 OIC_LOG(FATAL, TAG, "GetDoxmDeviceID failed!");
5059 if (OCConvertUuidToString(sid.id, sidStr) != RAND_UUID_OK)
5061 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5068 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5070 OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5071 CAResult_t retResult = CA_STATUS_FAILED;
5072 CAResult_t caResult = CA_STATUS_OK;
5074 CATransportAdapter_t connTypes[] = {
5076 CA_ADAPTER_RFCOMM_BTEDR,
5077 CA_ADAPTER_GATT_BTLE,
5080 ,CA_ADAPTER_REMOTE_ACCESS
5087 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5089 for(int i = 0; i < numConnTypes; i++)
5091 // If CA status is not initialized, CASelectNetwork() will not be called.
5092 if (caResult != CA_STATUS_NOT_INITIALIZED)
5094 if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5096 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5097 caResult = CASelectNetwork(connTypes[i]);
5098 if (caResult == CA_STATUS_OK)
5100 retResult = CA_STATUS_OK;
5105 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5110 if (retResult != CA_STATUS_OK)
5112 return caResult; // Returns error of appropriate transport that failed fatally.
5118 OCStackResult CAResultToOCResult(CAResult_t caResult)
5124 case CA_STATUS_INVALID_PARAM:
5125 return OC_STACK_INVALID_PARAM;
5126 case CA_ADAPTER_NOT_ENABLED:
5127 return OC_STACK_ADAPTER_NOT_ENABLED;
5128 case CA_SERVER_STARTED_ALREADY:
5130 case CA_SERVER_NOT_STARTED:
5131 return OC_STACK_ERROR;
5132 case CA_DESTINATION_NOT_REACHABLE:
5133 return OC_STACK_COMM_ERROR;
5134 case CA_SOCKET_OPERATION_FAILED:
5135 return OC_STACK_COMM_ERROR;
5136 case CA_SEND_FAILED:
5137 return OC_STACK_COMM_ERROR;
5138 case CA_RECEIVE_FAILED:
5139 return OC_STACK_COMM_ERROR;
5140 case CA_MEMORY_ALLOC_FAILED:
5141 return OC_STACK_NO_MEMORY;
5142 case CA_REQUEST_TIMEOUT:
5143 return OC_STACK_TIMEOUT;
5144 case CA_DESTINATION_DISCONNECTED:
5145 return OC_STACK_COMM_ERROR;
5146 case CA_STATUS_FAILED:
5147 return OC_STACK_ERROR;
5148 case CA_NOT_SUPPORTED:
5149 return OC_STACK_NOTIMPL;
5151 return OC_STACK_ERROR;
5155 bool OCResultToSuccess(OCStackResult ocResult)
5160 case OC_STACK_RESOURCE_CREATED:
5161 case OC_STACK_RESOURCE_DELETED:
5162 case OC_STACK_CONTINUE:
5163 case OC_STACK_RESOURCE_CHANGED:
5164 case OC_STACK_SLOW_RESOURCE:
5172 OCStackResult OCSetProxyURI(const char *uri)
5174 return CAResultToOCResult(CASetProxyUri(uri));
5178 #if defined(RD_CLIENT) || defined(RD_SERVER)
5179 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5181 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5183 OCResource *resource = NULL;
5185 resource = findResource((OCResource *) handle);
5188 OIC_LOG(ERROR, TAG, "Resource not found");
5189 return OC_STACK_ERROR;
5192 resource->ins = ins;
5198 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5199 const OCClientResponse *response)
5201 // Validate input parameters
5202 VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5203 VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5205 char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5208 return OC_STACK_NO_MEMORY;
5210 strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5212 if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5214 OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5216 char rdPubUri[MAX_URI_LENGTH] = { 0 };
5217 snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5218 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5220 if (strcmp(rdPubUri, targetUri) == 0)
5222 // Update resource unique id in stack.
5225 if (response->payload)
5227 OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5228 OCRepPayload **links = NULL;
5229 size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5230 if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5231 &links, dimensions))
5234 for (; i < dimensions[0]; i++)
5237 if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5239 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5241 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5243 OCBindResourceInsToResource(handle, ins);
5252 size_t count = calcDimTotal(dimensions);
5253 for (size_t k = 0; k < count; k++)
5255 OCRepPayloadDestroy(links[k]);
5263 else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5265 OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5267 uint8_t numResources = 0;
5268 OCGetNumberOfResources(&numResources);
5270 char *ins = strstr(targetUri, OC_RSRVD_INS);
5273 for (uint8_t i = 0; i < numResources; i++)
5275 OCResourceHandle resHandle = OCGetResourceHandle(i);
5278 OCBindResourceInsToResource(resHandle, 0);
5284 const char *token = "&";
5285 char *iterTokenPtr = NULL;
5286 char *start = strtok_r(targetUri, token, &iterTokenPtr);
5288 while (start != NULL)
5290 char *query = start;
5291 query = strstr(query, OC_RSRVD_INS);
5294 int64_t queryIns = atoi(query + 4);
5295 for (uint8_t i = 0; i < numResources; i++)
5297 OCResourceHandle resHandle = OCGetResourceHandle(i);
5301 OCGetResourceIns(resHandle, &resIns);
5302 if (queryIns && queryIns == resIns)
5304 OCBindResourceInsToResource(resHandle, 0);
5310 start = strtok_r(NULL, token, &iterTokenPtr);
5319 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5323 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5327 OCResource *pointer = headResource;
5331 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5333 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5336 pointer = pointer->next;
5341 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t *ins)
5343 OCResource *resource = NULL;
5345 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5346 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5348 resource = findResource((OCResource *) handle);
5351 *ins = resource->ins;
5354 return OC_STACK_ERROR;
5358 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5359 const void* optionData, size_t optionDataLength)
5363 OIC_LOG (INFO, TAG, "Header options are NULL");
5364 return OC_STACK_INVALID_PARAM;
5369 OIC_LOG (INFO, TAG, "optionData are NULL");
5370 return OC_STACK_INVALID_PARAM;
5375 OIC_LOG (INFO, TAG, "numOptions is NULL");
5376 return OC_STACK_INVALID_PARAM;
5379 if (*numOptions >= MAX_HEADER_OPTIONS)
5381 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5382 return OC_STACK_NO_MEMORY;
5385 ocHdrOpt += *numOptions;
5386 ocHdrOpt->protocolID = OC_COAP_ID;
5387 ocHdrOpt->optionID = optionID;
5388 ocHdrOpt->optionLength =
5389 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
5390 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5391 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5397 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5398 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5400 if (!ocHdrOpt || !numOptions)
5402 OIC_LOG (INFO, TAG, "No options present");
5408 OIC_LOG (INFO, TAG, "optionData are NULL");
5409 return OC_STACK_INVALID_PARAM;
5412 if (!receivedDataLength)
5414 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5415 return OC_STACK_INVALID_PARAM;
5418 for (uint8_t i = 0; i < numOptions; i++)
5420 if (ocHdrOpt[i].optionID == optionID)
5422 if (optionDataLength >= ocHdrOpt->optionLength)
5424 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5425 *receivedDataLength = ocHdrOpt->optionLength;
5430 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5431 return OC_STACK_ERROR;
5438 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5440 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5441 if (g_adapterHandler)
5443 g_adapterHandler(adapter, enabled);
5447 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5449 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5450 if (g_connectionHandler)
5452 g_connectionHandler(info, isConnected);
5456 * If the client observes one or more resources over a reliable connection,
5457 * then the CoAP server (or intermediary in the role of the CoAP server)
5458 * MUST remove all entries associated with the client endpoint from the lists
5459 * of observers when the connection is either closed or times out.
5463 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5464 CopyEndpointToDevAddr(info, &devAddr);
5466 // remove observer list with remote device address.
5467 DeleteObserverUsingDevAddr(&devAddr);
5471 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5474 OCStackResult ret = OC_STACK_ERROR;
5476 ret = GetDoxmDeviceID(&oicUuid);
5477 if (OC_STACK_OK == ret)
5479 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5483 OIC_LOG(ERROR, TAG, "Device ID Get error");
5488 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5491 OCStackResult ret = OC_STACK_ERROR;
5493 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5494 for (int i = 0; i < UUID_LENGTH; i++)
5496 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5498 ret = SetDoxmDeviceID(&oicUuid);
5502 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5504 bool isDeviceOwned = true;
5505 OCStackResult ret = OC_STACK_ERROR;
5507 ret = GetDoxmIsOwned(&isDeviceOwned);
5508 if (OC_STACK_OK == ret)
5510 *isOwned = isDeviceOwned;
5514 OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5519 void OCClearCallBackList()
5521 DeleteClientCBList();
5524 void OCClearObserverlist()
5526 DeleteObserverList();
5529 int OCEncrypt(const unsigned char *pt, size_t pt_len,
5530 unsigned char **ct, size_t *ct_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 psiEncrypt(pt, pt_len, ct, ct_len);
5539 #endif // __SECURE_PSI__
5542 int OCDecrypt(const unsigned char *ct, size_t ct_len,
5543 unsigned char **pt, size_t *pt_len)
5545 #ifndef __SECURE_PSI__
5546 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5549 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5551 return psiDecrypt(ct, ct_len, pt, pt_len);
5552 #endif // __SECURE_PSI__
5555 OCStackResult OCSetKey(const unsigned char* key)
5557 #ifndef __SECURE_PSI__
5558 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5561 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5563 return psiSetKey(key);
5564 #endif // __SECURE_PSI__
5567 OCStackResult OCGetKey(unsigned char* key)
5569 #ifndef __SECURE_PSI__
5570 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5573 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5575 return psiGetKey(key);
5576 #endif // __SECURE_PSI__
5579 OCStackResult OCSetSecurePSI(const unsigned char *key, const OCPersistentStorage *psPlain,
5580 const OCPersistentStorage *psEnc, const OCPersistentStorage *psRescue)
5582 #ifndef __SECURE_PSI__
5583 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5586 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5588 return setSecurePSI(key, psPlain, psEnc, psRescue);
5589 #endif // __SECURE_PSI__
5592 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5593 static void OtmEventHandler(const char *addr, uint16_t port, const char *uuid, int event)
5595 if (g_otmEventHandler.cb)
5597 g_otmEventHandler.cb(g_otmEventHandler.ctx, addr, port, uuid, event);
5602 * It is already declared in srmutility.h.
5603 * We can't include the header file, because of "redefined VERIFY_NON_NULL"
5605 typedef void (*OicSecOtmEventHandler_t)(const char* addr, uint16_t port,
5606 const char* uuid, int event);
5607 void SetOtmEventHandler(OicSecOtmEventHandler_t otmEventHandler);
5610 OCStackResult OCSetOtmEventHandler(void *ctx, OCOtmEventHandler cb)
5612 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5613 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5615 g_otmEventHandler.cb = cb;
5616 g_otmEventHandler.ctx = ctx;
5618 if (g_otmEventHandler.cb)
5620 OIC_LOG(DEBUG, TAG, "SET OCOtmEventHandler");
5621 SetOtmEventHandler(OtmEventHandler);
5625 OIC_LOG(DEBUG, TAG, "UNSET OCOtmEventHandler");
5626 SetOtmEventHandler(NULL);
5629 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);