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_INTERNAL_SERVER_ERROR:
726 ret = OC_STACK_INTERNAL_SERVER_ERROR;
728 case CA_NOT_IMPLEMENTED:
729 ret = OC_STACK_NOT_IMPLEMENTED;
732 ret = OC_STACK_BAD_GATEWAY;
734 case CA_SERVICE_UNAVAILABLE:
735 ret = OC_STACK_SERVICE_UNAVAILABLE;
737 case CA_RETRANSMIT_TIMEOUT:
738 ret = OC_STACK_GATEWAY_TIMEOUT;
740 case CA_PROXY_NOT_SUPPORTED:
741 ret = OC_STACK_PROXY_NOT_SUPPORTED;
749 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
751 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
760 // This Response Code is like HTTP 204 "No Content" but only used in
761 // response to POST and PUT requests.
765 // This Response Code is like HTTP 200 "OK" but only used in response to
770 // This should not happen but,
771 // give it a value just in case but output an error
773 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
777 case OC_STACK_RESOURCE_CREATED:
780 case OC_STACK_RESOURCE_DELETED:
783 case OC_STACK_RESOURCE_CHANGED:
786 case OC_STACK_INVALID_QUERY:
789 case OC_STACK_INVALID_OPTION:
792 case OC_STACK_NO_RESOURCE:
795 case OC_STACK_COMM_ERROR:
796 ret = CA_RETRANSMIT_TIMEOUT;
798 case OC_STACK_METHOD_NOT_ALLOWED:
799 ret = CA_METHOD_NOT_ALLOWED;
801 case OC_STACK_NOT_ACCEPTABLE:
802 ret = CA_NOT_ACCEPTABLE;
804 case OC_STACK_UNAUTHORIZED_REQ:
805 ret = CA_UNAUTHORIZED_REQ;
807 case OC_STACK_FORBIDDEN_REQ:
808 ret = CA_FORBIDDEN_REQ;
810 case OC_STACK_INTERNAL_SERVER_ERROR:
811 ret = CA_INTERNAL_SERVER_ERROR;
813 case OC_STACK_NOT_IMPLEMENTED:
814 ret = CA_NOT_IMPLEMENTED;
816 case OC_STACK_BAD_GATEWAY:
817 ret = CA_BAD_GATEWAY;
819 case OC_STACK_SERVICE_UNAVAILABLE:
820 ret = CA_SERVICE_UNAVAILABLE;
822 case OC_STACK_GATEWAY_TIMEOUT:
823 ret = CA_RETRANSMIT_TIMEOUT;
825 case OC_STACK_PROXY_NOT_SUPPORTED:
826 ret = CA_PROXY_NOT_SUPPORTED;
834 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
836 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
838 // supply default behavior.
839 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
841 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
843 if ((caFlags & OC_MASK_SCOPE) == 0)
845 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
850 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
852 return (OCTransportFlags)caFlags;
856 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
858 uint32_t lowerBound = 0;
859 uint32_t higherBound = 0;
861 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
863 return OC_STACK_INVALID_PARAM;
866 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
868 cbNode->presence->TTL = maxAgeSeconds;
870 for (int index = 0; index < PresenceTimeOutSize; index++)
872 // Guard against overflow
873 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
876 lowerBound = GetTicks((PresenceTimeOut[index] *
877 cbNode->presence->TTL *
878 MILLISECONDS_PER_SECOND)/100);
882 lowerBound = GetTicks(UINT32_MAX);
885 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
888 higherBound = GetTicks((PresenceTimeOut[index + 1] *
889 cbNode->presence->TTL *
890 MILLISECONDS_PER_SECOND)/100);
894 higherBound = GetTicks(UINT32_MAX);
897 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
899 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
900 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
901 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
904 cbNode->presence->TTLlevel = 0;
906 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
910 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
912 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
914 return OC_RSRVD_TRIGGER_CREATE;
916 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
918 return OC_RSRVD_TRIGGER_CHANGE;
922 return OC_RSRVD_TRIGGER_DELETE;
926 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
930 return OC_PRESENCE_TRIGGER_CREATE;
932 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
934 return OC_PRESENCE_TRIGGER_CREATE;
936 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
938 return OC_PRESENCE_TRIGGER_CHANGE;
942 return OC_PRESENCE_TRIGGER_DELETE;
945 #endif // WITH_PRESENCE
947 OCStackResult OCEncodeAddressForRFC6874(char *outputAddress,
949 const char *inputAddress)
951 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
952 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
954 size_t inputLength = strnlen(inputAddress, outputSize);
956 // inputSize includes the null terminator
957 size_t inputSize = inputLength + 1;
959 if (inputSize > outputSize)
961 OIC_LOG_V(ERROR, TAG,
962 "OCEncodeAddressForRFC6874 failed: "
963 "outputSize (%zu) < inputSize (%zu)",
964 outputSize, inputSize);
966 return OC_STACK_ERROR;
969 char* percentChar = strchr(inputAddress, '%');
971 // If there is no '%' character, then no change is required to the string.
972 if (NULL == percentChar)
974 OICStrcpy(outputAddress, outputSize, inputAddress);
978 const char* addressPart = &inputAddress[0];
979 const char* scopeIdPart = percentChar + 1;
981 // Sanity check to make sure this string doesn't have more '%' characters
982 if (NULL != strchr(scopeIdPart, '%'))
984 return OC_STACK_ERROR;
987 // If no string follows the first '%', then the input was invalid.
988 if (scopeIdPart[0] == '\0')
990 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
991 return OC_STACK_ERROR;
994 // Check to see if the string is already encoded
995 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
997 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Input string is already encoded");
998 return OC_STACK_ERROR;
1001 // Fail if we don't have room for encoded string's two additional chars
1002 if (outputSize < (inputSize + 2))
1004 OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: encoded output will not fit!");
1005 return OC_STACK_ERROR;
1008 // Restore the null terminator with an escaped '%' character, per RFC 6874
1009 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
1010 OICStrcat(outputAddress, outputSize, "%25");
1011 OICStrcat(outputAddress, outputSize, scopeIdPart);
1016 OCStackResult OCDecodeAddressForRFC6874(char *outputAddress,
1018 const char *inputAddress,
1021 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
1022 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
1026 end = inputAddress + strlen(inputAddress);
1028 size_t inputLength = end - inputAddress;
1030 const char *percent = strchr(inputAddress, '%');
1031 if (!percent || (percent > end))
1033 OICStrcpyPartial(outputAddress, outputSize, inputAddress, inputLength);
1037 if (percent[1] != '2' || percent[2] != '5')
1039 return OC_STACK_INVALID_URI;
1042 int addrlen = percent - inputAddress + 1;
1043 OICStrcpyPartial(outputAddress, outputSize, inputAddress, addrlen);
1044 OICStrcpyPartial(outputAddress + addrlen, outputSize - addrlen,
1045 percent + 3, end - percent - 3);
1051 #ifdef WITH_PRESENCE
1053 * The cononical presence allows constructed URIs to be string compared.
1055 * requestUri must be a char array of size CA_MAX_URI_LENGTH
1057 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
1058 char *presenceUri, bool isMulticast)
1060 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
1061 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1065 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1066 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1069 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1070 if (ep->adapter == CA_ADAPTER_IP)
1072 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1074 if ('\0' == ep->addr[0]) // multicast
1076 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1080 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1082 OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1083 sizeof(addressEncoded),
1086 if (OC_STACK_OK != result)
1091 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1092 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1097 if ('\0' == ep->addr[0]) // multicast
1099 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1100 ep->port = OC_MULTICAST_PORT;
1102 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1103 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1107 // might work for other adapters (untested, but better than nothing)
1108 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1109 OC_RSRVD_PRESENCE_URI);
1113 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1114 const CAResponseInfo_t *responseInfo)
1116 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1117 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1119 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1120 ClientCB * cbNode = NULL;
1121 char *resourceTypeName = NULL;
1122 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1123 OCStackResult result = OC_STACK_ERROR;
1124 uint32_t maxAge = 0;
1126 char presenceUri[CA_MAX_URI_LENGTH];
1128 int presenceSubscribe = 0;
1129 int multicastPresenceSubscribe = 0;
1131 if (responseInfo->result != CA_CONTENT)
1133 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1134 return OC_STACK_ERROR;
1137 response.payload = NULL;
1138 response.result = OC_STACK_OK;
1140 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1141 FixUpClientResponse(&response);
1143 if (responseInfo->info.payload)
1145 result = OCParsePayload(&response.payload,
1146 PAYLOAD_TYPE_PRESENCE,
1147 responseInfo->info.payload,
1148 responseInfo->info.payloadSize);
1150 if(result != OC_STACK_OK)
1152 OIC_LOG(ERROR, TAG, "Presence parse failed");
1155 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1157 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1158 result = OC_STACK_ERROR;
1161 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1162 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1163 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1166 // check for unicast presence
1167 uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1168 responseInfo->isMulticast);
1169 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1171 return OC_STACK_INVALID_URI;
1173 OIC_LOG(INFO, TAG, "check for unicast presence");
1174 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1177 presenceSubscribe = 1;
1181 // check for multicast presence
1182 OIC_LOG(INFO, TAG, "check for multicast presence");
1183 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1186 multicastPresenceSubscribe = 1;
1190 if (!presenceSubscribe && !multicastPresenceSubscribe)
1192 OIC_LOG(INFO, TAG, "Received a presence notification, "
1193 "but need to register presence callback, ignoring");
1197 if (presenceSubscribe)
1199 if(cbNode->sequenceNumber == response.sequenceNumber)
1201 OIC_LOG(INFO, TAG, "No presence change");
1202 ResetPresenceTTL(cbNode, maxAge);
1203 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1209 OIC_LOG(INFO, TAG, "Stopping presence");
1210 response.result = OC_STACK_PRESENCE_STOPPED;
1211 if(cbNode->presence)
1213 OICFree(cbNode->presence->timeOut);
1214 OICFree(cbNode->presence);
1215 cbNode->presence = NULL;
1220 if(!cbNode->presence)
1222 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1224 if(!(cbNode->presence))
1226 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1227 result = OC_STACK_NO_MEMORY;
1231 VERIFY_NON_NULL_V(cbNode->presence);
1232 cbNode->presence->timeOut = NULL;
1233 cbNode->presence->timeOut = (uint32_t *)
1234 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1235 if(!(cbNode->presence->timeOut)){
1237 "Could not allocate memory for cbNode->presence->timeOut");
1238 OICFree(cbNode->presence);
1239 result = OC_STACK_NO_MEMORY;
1244 ResetPresenceTTL(cbNode, maxAge);
1246 cbNode->sequenceNumber = response.sequenceNumber;
1251 // This is the multicast case
1252 OIC_LOG(INFO, TAG, "this is the multicast presence");
1255 OIC_LOG(INFO, TAG, "Stopping presence");
1256 response.result = OC_STACK_PRESENCE_STOPPED;
1260 // Ensure that a filter is actually applied.
1261 if (resourceTypeName && cbNode->filterResourceType)
1263 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1264 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1270 OIC_LOG(INFO, TAG, "Before calling into application address space for presence");
1271 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1272 OIC_LOG(INFO, TAG, "After calling into application address space for presence");
1274 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1276 FindAndDeleteClientCB(cbNode);
1280 OCPayloadDestroy(response.payload);
1283 #endif // WITH_PRESENCE
1285 OCStackResult HandleBatchResponse(char *requestUri, OCRepPayload **payload)
1287 if (requestUri && *payload)
1289 char *interfaceName = NULL;
1290 char *rtTypeName = NULL;
1291 char *uriQuery = NULL;
1292 char *uriWithoutQuery = NULL;
1293 if (OC_STACK_OK == getQueryFromUri(requestUri, &uriQuery, &uriWithoutQuery))
1295 if (OC_STACK_OK == ExtractFiltersFromQuery(uriQuery, &interfaceName, &rtTypeName))
1297 if (interfaceName && (0 == strcmp(OC_RSRVD_INTERFACE_BATCH, interfaceName)))
1299 char *uri = (*payload)->uri;
1300 if (uri && 0 != strcmp(uriWithoutQuery, uri))
1302 OCRepPayload *newPayload = OCRepPayloadCreate();
1305 OCRepPayloadSetUri(newPayload, uri);
1306 newPayload->next = *payload;
1307 *payload = newPayload;
1314 OICFree(interfaceName);
1315 OICFree(rtTypeName);
1317 OICFree(uriWithoutQuery);
1320 return OC_STACK_INVALID_PARAM;
1323 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1325 OIC_TRACE_MARK(%s:OCHandleResponse:%s, TAG, responseInfo->info.resourceUri);
1326 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1328 #ifdef WITH_PRESENCE
1329 if(responseInfo->info.resourceUri &&
1330 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1332 HandlePresenceResponse(endPoint, responseInfo);
1337 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1338 responseInfo->info.tokenLength, NULL, NULL);
1342 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1344 // check obs header option
1345 bool obsHeaderOpt = false;
1346 CAHeaderOption_t *options = responseInfo->info.options;
1347 for (uint8_t i = 0; i< responseInfo->info.numOptions; i++)
1349 if (options && options[i].protocolID == CA_COAP_ID &&
1350 options[i].optionID == COAP_OPTION_OBSERVE)
1352 obsHeaderOpt = true;
1357 if(responseInfo->result == CA_EMPTY)
1359 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1360 // We do not have a case for the client to receive a RESET
1361 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1363 //This is the case of receiving an ACK on a request to a slow resource!
1364 OIC_LOG(INFO, TAG, "This is a pure ACK");
1365 //TODO: should we inform the client
1366 // app that at least the request was received at the server?
1369 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1371 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1373 OCClientResponse response =
1374 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1375 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1376 FixUpClientResponse(&response);
1377 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1378 memcpy(response.identity.id, responseInfo->info.identity.id,
1379 sizeof (response.identity.id));
1380 response.identity.id_length = responseInfo->info.identity.id_length;
1382 response.result = CAResponseToOCStackResult(responseInfo->result);
1383 OIC_LOG(INFO, TAG, "Before calling into application address space for reTrans timeout");
1384 cbNode->callBack(cbNode->context,
1385 cbNode->handle, &response);
1386 OIC_LOG(INFO, TAG, "After calling into application address space for reTrans timeout");
1387 FindAndDeleteClientCB(cbNode);
1388 OICFree((void *)response.resourceUri);
1391 else if ((cbNode->method == OC_REST_OBSERVE || cbNode->method == OC_REST_OBSERVE_ALL)
1392 && (responseInfo->result == CA_CONTENT) && !obsHeaderOpt)
1394 OCClientResponse response =
1395 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1396 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1397 FixUpClientResponse(&response);
1398 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1399 memcpy(response.identity.id, responseInfo->info.identity.id,
1400 sizeof (response.identity.id));
1401 response.identity.id_length = responseInfo->info.identity.id_length;
1402 response.result = OC_STACK_UNAUTHORIZED_REQ;
1404 OIC_LOG(INFO, TAG, "Before calling into application address space for observe resp");
1405 cbNode->callBack(cbNode->context,
1408 OIC_LOG(INFO, TAG, "After calling into application address space for observe resp");
1410 FindAndDeleteClientCB(cbNode);
1411 OICFree(response.resourceUri);
1416 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1418 OCClientResponse response;
1419 memset(&response, 0, sizeof(OCClientResponse));
1420 response.devAddr.adapter = OC_DEFAULT_ADAPTER;
1422 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1423 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1424 FixUpClientResponse(&response);
1425 response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1426 memcpy(response.identity.id, responseInfo->info.identity.id,
1427 sizeof (response.identity.id));
1428 response.identity.id_length = responseInfo->info.identity.id_length;
1430 response.result = CAResponseToOCStackResult(responseInfo->result);
1432 if(responseInfo->info.payload &&
1433 responseInfo->info.payloadSize)
1435 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1436 // check the security resource
1437 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1439 type = PAYLOAD_TYPE_SECURITY;
1441 else if (cbNode->method == OC_REST_DISCOVER)
1443 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1444 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1446 type = PAYLOAD_TYPE_DISCOVERY;
1449 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1451 type = PAYLOAD_TYPE_DISCOVERY;
1454 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1456 type = PAYLOAD_TYPE_REPRESENTATION;
1458 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1460 type = PAYLOAD_TYPE_REPRESENTATION;
1463 #ifdef ROUTING_GATEWAY
1464 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1466 type = PAYLOAD_TYPE_REPRESENTATION;
1469 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1471 type = PAYLOAD_TYPE_REPRESENTATION;
1474 else if (strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1476 type = PAYLOAD_TYPE_REPRESENTATION;
1481 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1482 cbNode->method, cbNode->requestUri);
1483 OICFree((void *)response.resourceUri);
1487 else if (cbNode->method == OC_REST_GET ||
1488 cbNode->method == OC_REST_PUT ||
1489 cbNode->method == OC_REST_POST ||
1490 cbNode->method == OC_REST_OBSERVE ||
1491 cbNode->method == OC_REST_OBSERVE_ALL ||
1492 cbNode->method == OC_REST_DELETE)
1494 if (cbNode->requestUri)
1496 if (0 == strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri))
1498 type = PAYLOAD_TYPE_REPRESENTATION;
1500 else if (0 == strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri))
1502 type = PAYLOAD_TYPE_REPRESENTATION;
1504 if (type == PAYLOAD_TYPE_INVALID)
1506 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1507 cbNode->method, cbNode->requestUri);
1508 type = PAYLOAD_TYPE_REPRESENTATION;
1513 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1514 type = PAYLOAD_TYPE_REPRESENTATION;
1519 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1520 cbNode->method, cbNode->requestUri);
1521 OICFree((void *)response.resourceUri);
1525 // In case of error, still want application to receive the error message.
1526 if (OCResultToSuccess(response.result) || PAYLOAD_TYPE_REPRESENTATION == type)
1528 if(OC_STACK_OK != OCParsePayload(&response.payload,
1530 responseInfo->info.payload,
1531 responseInfo->info.payloadSize))
1533 OIC_LOG(ERROR, TAG, "Error converting payload");
1534 OCPayloadDestroy(response.payload);
1535 OICFree((void *)response.resourceUri);
1541 OICFree((void *)response.resourceUri);
1542 response.resourceUri = OICStrdup(cbNode->requestUri);
1546 response.numRcvdVendorSpecificHeaderOptions = 0;
1547 if(responseInfo->info.numOptions > 0)
1550 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1551 if(responseInfo->info.options
1552 && responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1555 uint32_t observationOption;
1556 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1557 for (observationOption=0, i=0;
1558 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1562 (observationOption << 8) | optionData[i];
1564 response.sequenceNumber = observationOption;
1565 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1570 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1573 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1575 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1576 OCPayloadDestroy(response.payload);
1577 OICFree((void *)response.resourceUri);
1581 if (response.numRcvdVendorSpecificHeaderOptions > 0)
1583 response.rcvdVendorSpecificHeaderOptions =
1584 (OCHeaderOption *) OICCalloc(response.numRcvdVendorSpecificHeaderOptions, sizeof(OCHeaderOption));
1585 if (NULL == response.rcvdVendorSpecificHeaderOptions)
1587 OIC_LOG(ERROR, TAG, "Failed to allocate memory for vendor header options");
1588 OCPayloadDestroy(response.payload);
1589 OICFree((void *)response.resourceUri);
1593 memcpy(response.rcvdVendorSpecificHeaderOptions, responseInfo->info.options + start,
1594 response.numRcvdVendorSpecificHeaderOptions*sizeof(OCHeaderOption));
1598 if (cbNode->method == OC_REST_OBSERVE &&
1599 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1600 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1601 response.sequenceNumber <= cbNode->sequenceNumber)
1603 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1604 response.sequenceNumber);
1609 if (cbNode->requestUri)
1611 // if request uri is '/oic/rd', update ins value of resource.
1612 char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
1615 OCUpdateResourceInsWithResponse(cbNode->requestUri, &response);
1619 // set remoteID(device ID) into OCClientResponse callback parameter
1620 if (OC_REST_DISCOVER == cbNode->method)
1622 OIC_LOG(INFO, TAG, "cbNode method is OC_REST_DISCOVER");
1623 OCDiscoveryPayload *payload = (OCDiscoveryPayload*) response.payload;
1624 // Payload can be empty in case of error message.
1625 if (payload && payload->sid)
1627 OICStrcpy(response.devAddr.remoteId, sizeof(response.devAddr.remoteId),
1629 OIC_LOG_V(INFO_PRIVATE, TAG, "Device ID of response : %s",
1630 response.devAddr.remoteId);
1633 if(NULL == response.resourceUri)
1635 response.resourceUri = OICStrdup(cbNode->requestUri);
1639 if (cbNode->requestUri)
1641 OIC_LOG_V(INFO, TAG, "cbNode requestUri is %s", cbNode->requestUri);
1642 if (cbNode->method == OC_REST_POST &&
1643 strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1645 OCHandleKeepAliveResponse(endPoint, response.payload);
1649 if (response.payload && response.payload->type == PAYLOAD_TYPE_REPRESENTATION)
1651 OIC_LOG(INFO, TAG, "Handle batch response");
1652 HandleBatchResponse(cbNode->requestUri, (OCRepPayload **)&response.payload);
1655 OIC_LOG(INFO, TAG, "Before calling into application address space for handleResponse");
1656 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1659 OIC_LOG(INFO, TAG, "After calling into application address space for handleResponse");
1661 cbNode->sequenceNumber = response.sequenceNumber;
1663 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1665 FindAndDeleteClientCB(cbNode);
1669 // To keep discovery callbacks active.
1670 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1671 MILLISECONDS_PER_SECOND);
1675 //Need to send ACK when the response is CON
1676 if(responseInfo->info.type == CA_MSG_CONFIRM)
1678 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1680 OIC_LOG(INFO, TAG, "Received a confirmable message. Sending EMPTY");
1681 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1682 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1686 OICFree((void *)response.resourceUri);
1687 OCPayloadDestroy(response.payload);
1688 OICFree(response.rcvdVendorSpecificHeaderOptions);
1693 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1694 responseInfo->info.tokenLength);
1698 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1699 if(responseInfo->result == CA_EMPTY)
1701 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1702 if(responseInfo->info.type == CA_MSG_RESET)
1704 OIC_LOG(INFO, TAG, "This is a RESET");
1705 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1706 OC_OBSERVER_NOT_INTERESTED);
1708 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1710 OIC_LOG(INFO, TAG, "This is a pure ACK");
1711 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1712 OC_OBSERVER_STILL_INTERESTED);
1715 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1717 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1718 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1719 OC_OBSERVER_FAILED_COMM);
1722 FreeObserver(observer);
1726 if(!cbNode && !observer)
1728 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1729 || myStackMode == OC_GATEWAY)
1731 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1732 if(responseInfo->result == CA_EMPTY)
1734 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1738 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1740 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1741 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1742 CA_MSG_RESET, 0, NULL, NULL, 0, NULL,
1743 CA_RESPONSE_FOR_RES);
1748 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1749 || myStackMode == OC_GATEWAY)
1751 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1752 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1754 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1755 responseInfo->info.messageId);
1757 if (responseInfo->info.type == CA_MSG_RESET)
1759 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1760 responseInfo->info.messageId);
1768 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1770 VERIFY_NON_NULL_NR(endPoint, FATAL);
1771 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1773 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1774 OIC_TRACE_BEGIN(%s:HandleCAResponses, TAG);
1776 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1777 #ifdef ROUTING_GATEWAY
1778 bool needRIHandling = false;
1780 * Routing manager is going to update either of endpoint or response or both.
1781 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1782 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1785 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1787 if(ret != OC_STACK_OK || !needRIHandling)
1789 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1796 * Put source in sender endpoint so that the next packet from application can be routed to
1797 * proper destination and remove "RM" coap header option before passing request / response to
1798 * RI as this option will make no sense to either RI or application.
1800 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1801 (uint8_t *) &(responseInfo->info.numOptions),
1802 (CAEndpoint_t *) endPoint);
1805 OCHandleResponse(endPoint, responseInfo);
1807 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1811 * This function handles error response from CA
1812 * code shall be added to handle the errors
1814 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1816 VERIFY_NON_NULL_NR(endPoint, FATAL);
1817 VERIFY_NON_NULL_NR(errorInfo, FATAL);
1819 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1820 OIC_TRACE_BEGIN(%s:HandleCAErrorResponse, TAG);
1822 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1823 errorInfo->info.tokenLength, NULL, NULL);
1826 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1827 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1828 FixUpClientResponse(&response);
1829 response.resourceUri = errorInfo->info.resourceUri;
1830 memcpy(response.identity.id, errorInfo->info.identity.id,
1831 sizeof (response.identity.id));
1832 response.identity.id_length = errorInfo->info.identity.id_length;
1833 response.result = CAResultToOCResult(errorInfo->result);
1835 OIC_LOG(INFO, TAG, "Before calling into application address space for error response");
1836 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1837 OIC_LOG(INFO, TAG, "After calling into application address space for error response");
1840 ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1841 errorInfo->info.tokenLength);
1844 OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1845 OCStackResult result = CAResultToOCResult(errorInfo->result);
1846 if (OC_STACK_COMM_ERROR == result)
1848 OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1849 OC_OBSERVER_FAILED_COMM);
1853 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1858 * This function sends out Direct Stack Responses. These are responses that are not coming
1859 * from the application entity handler. These responses have no payload and are usually ACKs,
1860 * RESETs or some error conditions that were caught by the stack.
1862 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1863 const CAResponseResult_t responseResult, const CAMessageType_t type,
1864 const uint8_t numOptions, const CAHeaderOption_t *options,
1865 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1866 CADataType_t dataType)
1868 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1870 if (endPoint->flags & CA_MULTICAST)
1872 OIC_LOG(ERROR, TAG, "It is unnecessary to respond to a multicast request");
1876 CAResponseInfo_t respInfo = { .result = responseResult };
1877 respInfo.info.messageId = coapID;
1878 respInfo.info.numOptions = numOptions;
1880 if (respInfo.info.numOptions)
1882 respInfo.info.options =
1883 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1884 memcpy (respInfo.info.options, options,
1885 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1889 respInfo.info.payload = NULL;
1890 respInfo.info.token = token;
1891 respInfo.info.tokenLength = tokenLength;
1892 respInfo.info.type = type;
1893 respInfo.info.resourceUri = OICStrdup (resourceUri);
1894 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1895 respInfo.info.dataType = dataType;
1897 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1898 // Add the destination to route option from the endpoint->routeData.
1899 bool doPost = false;
1900 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1901 if(OC_STACK_OK != result)
1903 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1904 OICFree (respInfo.info.resourceUri);
1905 OICFree (respInfo.info.options);
1910 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1911 CARequestInfo_t reqInfo = {.method = CA_POST };
1912 /* The following initialization is not done in a single initializer block as in
1913 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1914 * does not have designated initalizers. This is a work-around for now.
1916 reqInfo.info.type = CA_MSG_NONCONFIRM;
1917 reqInfo.info.messageId = coapID;
1918 reqInfo.info.tokenLength = tokenLength;
1919 reqInfo.info.token = token;
1920 reqInfo.info.numOptions = respInfo.info.numOptions;
1921 reqInfo.info.payload = NULL;
1922 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1923 if (reqInfo.info.numOptions)
1925 reqInfo.info.options =
1926 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1927 if (NULL == reqInfo.info.options)
1929 OIC_LOG(ERROR, TAG, "Calloc failed");
1930 OICFree (reqInfo.info.resourceUri);
1931 OICFree (respInfo.info.resourceUri);
1932 OICFree (respInfo.info.options);
1933 return OC_STACK_NO_MEMORY;
1935 memcpy (reqInfo.info.options, respInfo.info.options,
1936 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1939 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1940 OICFree (reqInfo.info.resourceUri);
1941 OICFree (reqInfo.info.options);
1942 OICFree (respInfo.info.resourceUri);
1943 OICFree (respInfo.info.options);
1944 if (CA_STATUS_OK != caResult)
1946 OIC_LOG(ERROR, TAG, "CASendRequest error");
1947 return CAResultToOCResult(caResult);
1953 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1955 // resourceUri in the info field is cloned in the CA layer and
1956 // thus ownership is still here.
1957 OICFree (respInfo.info.resourceUri);
1958 OICFree (respInfo.info.options);
1959 if(CA_STATUS_OK != caResult)
1961 OIC_LOG(ERROR, TAG, "CASendResponse error");
1962 return CAResultToOCResult(caResult);
1965 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1969 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1971 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1972 OCStackResult result = OC_STACK_ERROR;
1973 if(!protocolRequest)
1975 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1976 return OC_STACK_INVALID_PARAM;
1979 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1980 protocolRequest->tokenLength);
1983 OIC_LOG(INFO, TAG, "This is a new Server Request");
1984 result = AddServerRequest(&request, protocolRequest->coapID,
1985 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1986 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1987 protocolRequest->observationOption, protocolRequest->qos,
1988 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1989 protocolRequest->payload, protocolRequest->requestToken,
1990 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1991 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1992 &protocolRequest->devAddr);
1993 if (OC_STACK_OK != result)
1995 OIC_LOG(ERROR, TAG, "Error adding server request");
2001 OIC_LOG(ERROR, TAG, "Out of Memory");
2002 return OC_STACK_NO_MEMORY;
2005 if(!protocolRequest->reqMorePacket)
2007 request->requestComplete = 1;
2012 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
2015 if(request->requestComplete)
2017 OIC_LOG(INFO, TAG, "This Server Request is complete");
2018 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2019 OCResource *resource = NULL;
2020 result = DetermineResourceHandling (request, &resHandling, &resource);
2021 if (result == OC_STACK_OK)
2023 result = ProcessRequest(resHandling, resource, request);
2028 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2029 result = OC_STACK_CONTINUE;
2034 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2036 OIC_TRACE_MARK(%s:OCHandleRequests:%s, TAG, requestInfo->info.resourceUri);
2037 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2039 OCStackResult requestResult = OC_STACK_ERROR;
2041 if(myStackMode == OC_CLIENT)
2043 //TODO: should the client be responding to requests?
2047 OCServerProtocolRequest serverRequest = {0};
2049 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2051 char * uriWithoutQuery = NULL;
2052 char * query = NULL;
2054 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2056 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2058 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2061 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2062 OIC_LOG_V(INFO, TAG, "Query : %s", query);
2064 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2066 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2067 OICFree(uriWithoutQuery);
2071 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2072 OICFree(uriWithoutQuery);
2079 if(strlen(query) < MAX_QUERY_LENGTH)
2081 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2086 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2092 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2094 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2095 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2096 if (!serverRequest.payload)
2098 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2101 memcpy (serverRequest.payload, requestInfo->info.payload,
2102 requestInfo->info.payloadSize);
2106 serverRequest.reqTotalSize = 0;
2109 switch (requestInfo->method)
2112 serverRequest.method = OC_REST_GET;
2115 serverRequest.method = OC_REST_PUT;
2118 serverRequest.method = OC_REST_POST;
2121 serverRequest.method = OC_REST_DELETE;
2124 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2125 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2126 requestInfo->info.type, requestInfo->info.numOptions,
2127 requestInfo->info.options, requestInfo->info.token,
2128 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2130 OICFree(serverRequest.payload);
2134 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2135 requestInfo->info.tokenLength);
2137 serverRequest.tokenLength = requestInfo->info.tokenLength;
2138 if (serverRequest.tokenLength) {
2140 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2142 if (!serverRequest.requestToken)
2144 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2145 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2146 requestInfo->info.type, requestInfo->info.numOptions,
2147 requestInfo->info.options, requestInfo->info.token,
2148 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2150 OICFree(serverRequest.payload);
2153 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2156 switch (requestInfo->info.acceptFormat)
2158 case CA_FORMAT_APPLICATION_CBOR:
2159 serverRequest.acceptFormat = OC_FORMAT_CBOR;
2161 case CA_FORMAT_UNDEFINED:
2162 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2165 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2168 if (requestInfo->info.type == CA_MSG_CONFIRM)
2170 serverRequest.qos = OC_HIGH_QOS;
2174 serverRequest.qos = OC_LOW_QOS;
2176 // CA does not need the following field
2177 // Are we sure CA does not need them? how is it responding to multicast
2178 serverRequest.delayedResNeeded = 0;
2180 serverRequest.coapID = requestInfo->info.messageId;
2182 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2184 // copy vendor specific header options
2185 uint8_t tempNum = (requestInfo->info.numOptions);
2187 // Assume no observation requested and it is a pure GET.
2188 // If obs registration/de-registration requested it'll be fetched from the
2189 // options in GetObserveHeaderOption()
2190 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2192 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2193 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2196 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2197 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2198 requestInfo->info.type, requestInfo->info.numOptions,
2199 requestInfo->info.options, requestInfo->info.token,
2200 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2202 OICFree(serverRequest.payload);
2203 OICFree(serverRequest.requestToken);
2207 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2208 if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2210 serverRequest.rcvdVendorSpecificHeaderOptions = (OCHeaderOption*) OICCalloc(tempNum, sizeof(OCHeaderOption));
2211 if (NULL == serverRequest.rcvdVendorSpecificHeaderOptions)
2213 OIC_LOG(ERROR, TAG, "Failed to allocated memory to vnd header options!");
2214 OICFree(serverRequest.payload);
2215 OICFree(serverRequest.requestToken);
2219 memcpy (serverRequest.rcvdVendorSpecificHeaderOptions, requestInfo->info.options,
2220 sizeof(CAHeaderOption_t)*tempNum);
2223 requestResult = HandleStackRequests (&serverRequest);
2225 // Send ACK to client as precursor to slow response
2226 if (requestResult == OC_STACK_SLOW_RESOURCE)
2228 if (requestInfo->info.type == CA_MSG_CONFIRM)
2230 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2231 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2236 if (requestResult == OC_STACK_RESOURCE_ERROR
2237 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2239 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2242 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2244 if (requestResult == OC_STACK_RESOURCE_ERROR)
2246 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2248 else if (!OCResultToSuccess(requestResult))
2250 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2254 else if(!OCResultToSuccess(requestResult))
2256 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2258 // Delete observer node if it is OBSERVE failure from app
2259 if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2261 DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2264 CAResponseResult_t stackResponse =
2265 OCToCAStackResult(requestResult, serverRequest.method);
2267 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2268 requestInfo->info.type, requestInfo->info.numOptions,
2269 requestInfo->info.options, requestInfo->info.token,
2270 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2273 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2274 // The token is copied in there, and is thus still owned by this function.
2275 OICFree(serverRequest.payload);
2276 OICFree(serverRequest.requestToken);
2277 OICFree(serverRequest.rcvdVendorSpecificHeaderOptions);
2278 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2281 //This function will be called back by CA layer when a request is received
2282 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2284 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2285 OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2288 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2295 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2300 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2301 #ifdef ROUTING_GATEWAY
2302 bool needRIHandling = false;
2303 bool isEmptyMsg = false;
2305 * Routing manager is going to update either of endpoint or request or both.
2306 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2307 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2308 * destination. It can also remove "RM" coap header option before passing request / response to
2309 * RI as this option will make no sense to either RI or application.
2311 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2312 &needRIHandling, &isEmptyMsg);
2313 if(OC_STACK_OK != ret || !needRIHandling)
2315 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2322 * Put source in sender endpoint so that the next packet from application can be routed to
2323 * proper destination and remove RM header option.
2325 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2326 (uint8_t *) &(requestInfo->info.numOptions),
2327 (CAEndpoint_t *) endPoint);
2329 #ifdef ROUTING_GATEWAY
2333 * In Gateways, the MSGType in route option is used to check if the actual
2334 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2335 * EMPTY response is sent in the form of POST request which need to be changed
2336 * to a EMPTY response by RM. This translation is done in this part of the code.
2338 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2339 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2340 .info.messageId = requestInfo->info.messageId,
2341 .info.type = CA_MSG_ACKNOWLEDGE};
2342 OCHandleResponse(endPoint, &respInfo);
2348 // Normal handling of the packet
2349 OCHandleRequests(endPoint, requestInfo);
2351 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2355 //-----------------------------------------------------------------------------
2357 //-----------------------------------------------------------------------------
2359 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2362 !raInfo->username ||
2363 !raInfo->hostname ||
2364 !raInfo->xmpp_domain)
2367 return OC_STACK_INVALID_PARAM;
2369 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2370 gRASetInfo = (result == OC_STACK_OK)? true : false;
2376 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2380 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2383 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2385 OC_UNUSED(serverFlags);
2386 OC_UNUSED(clientFlags);
2388 OIC_LOG(DEBUG, TAG, "call OCInit1");
2389 return OCInit2(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS, OC_DEFAULT_ADAPTER);
2392 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2393 OCTransportAdapter transportType)
2395 if(stackState == OC_STACK_INITIALIZED)
2397 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2398 OCStop() between them are ignored.");
2402 #ifndef ROUTING_GATEWAY
2403 if (OC_GATEWAY == mode)
2405 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2406 return OC_STACK_INVALID_PARAM;
2413 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2414 return OC_STACK_ERROR;
2418 OCStackResult result = OC_STACK_ERROR;
2419 OIC_LOG(INFO, TAG, "Entering OCInit");
2422 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2423 || (mode == OC_GATEWAY)))
2425 OIC_LOG(ERROR, TAG, "Invalid mode");
2426 return OC_STACK_ERROR;
2430 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2432 caglobals.client = true;
2434 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2436 caglobals.server = true;
2439 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2440 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2442 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2444 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2445 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2447 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2450 defaultDeviceHandler = NULL;
2451 defaultDeviceHandlerCallbackParameter = NULL;
2453 result = InitializeScheduleResourceList();
2454 VERIFY_SUCCESS(result, OC_STACK_OK);
2456 result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2457 VERIFY_SUCCESS(result, OC_STACK_OK);
2459 result = CAResultToOCResult(OCSelectNetwork(transportType));
2460 VERIFY_SUCCESS(result, OC_STACK_OK);
2462 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2463 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2464 VERIFY_SUCCESS(result, OC_STACK_OK);
2466 switch (myStackMode)
2469 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2470 result = CAResultToOCResult(CAStartDiscoveryServer());
2471 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2474 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2475 result = CAResultToOCResult(CAStartListeningServer());
2476 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2478 case OC_CLIENT_SERVER:
2480 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2481 result = CAResultToOCResult(CAStartListeningServer());
2482 if(result == OC_STACK_OK)
2484 result = CAResultToOCResult(CAStartDiscoveryServer());
2488 VERIFY_SUCCESS(result, OC_STACK_OK);
2491 CARegisterKeepAliveHandler(OCHandleKeepAliveConnCB);
2494 #ifdef WITH_PRESENCE
2495 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2496 #endif // WITH_PRESENCE
2498 //Update Stack state to initialized
2499 stackState = OC_STACK_INITIALIZED;
2501 // Initialize resource
2502 if(myStackMode != OC_CLIENT)
2504 result = initResources();
2507 // Initialize the SRM Policy Engine
2508 if(result == OC_STACK_OK)
2510 result = SRMInitPolicyEngine();
2511 // TODO after BeachHead delivery: consolidate into single SRMInit()
2513 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2514 RMSetStackMode(mode);
2515 #ifdef ROUTING_GATEWAY
2516 if (OC_GATEWAY == myStackMode)
2518 result = RMInitialize();
2524 if (result == OC_STACK_OK)
2526 result = OCInitializeKeepAlive(myStackMode);
2530 InitializeObserverList();
2533 if(result != OC_STACK_OK)
2535 OIC_LOG(ERROR, TAG, "Stack initialization error");
2536 TerminateScheduleResourceList();
2537 deleteAllResources();
2539 stackState = OC_STACK_UNINITIALIZED;
2544 OCStackResult OCStop()
2546 OIC_LOG(INFO, TAG, "Entering OCStop");
2548 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2550 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2553 else if (stackState != OC_STACK_INITIALIZED)
2555 OIC_LOG(INFO, TAG, "Stack not initialized");
2556 return OC_STACK_ERROR;
2559 // unset cautil config
2560 CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2561 CAUtilSetBTConfigure(configs);
2563 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2565 CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2566 OCDefaultConnectionStateChangedHandler);
2568 #ifdef WITH_PRESENCE
2569 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2570 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2571 presenceResource.presenceTTL = 0;
2572 presenceState = OC_PRESENCE_UNINITIALIZED;
2573 #endif // WITH_PRESENCE
2575 #ifdef ROUTING_GATEWAY
2576 if (OC_GATEWAY == myStackMode)
2583 OCTerminateKeepAlive(myStackMode);
2586 TerminateScheduleResourceList();
2587 // Remove all observers
2588 DeleteObserverList();
2589 // Free memory dynamically allocated for resources
2590 deleteAllResources();
2591 // Remove all the client callbacks
2592 DeleteClientCBList();
2593 // Terminate connectivity-abstraction layer.
2596 // De-init the SRM Policy Engine
2597 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2598 SRMDeInitPolicyEngine();
2600 // Destroy Observer List Mutex
2601 TerminateObserverList();
2603 stackState = OC_STACK_UNINITIALIZED;
2607 OCStackResult OCStartMulticastServer()
2609 if(stackState != OC_STACK_INITIALIZED)
2611 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2612 return OC_STACK_ERROR;
2614 CAResult_t ret = CAStartListeningServer();
2615 if (CA_STATUS_OK != ret)
2617 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2618 return OC_STACK_ERROR;
2623 OCStackResult OCStopMulticastServer()
2625 CAResult_t ret = CAStopListeningServer();
2626 if (CA_STATUS_OK != ret)
2628 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2629 return OC_STACK_ERROR;
2634 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2639 return CA_MSG_CONFIRM;
2644 return CA_MSG_NONCONFIRM;
2648 OCStackResult ParseRequestUri(const char *fullUri,
2649 OCTransportAdapter adapter,
2650 OCTransportFlags flags,
2651 OCDevAddr **devAddr,
2653 char **resourceType)
2655 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2657 OCStackResult result = OC_STACK_OK;
2658 OCDevAddr *da = NULL;
2662 // provide defaults for all returned values
2669 *resourceUri = NULL;
2673 *resourceType = NULL;
2676 // delimit url prefix, if any
2677 const char *start = fullUri;
2678 char *slash2 = strstr(start, "//");
2683 char *slash = strchr(start, '/');
2686 return OC_STACK_INVALID_URI;
2689 // process url scheme
2690 size_t prefixLen = slash2 - fullUri;
2694 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2695 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2701 // TODO: this logic should come in with unit tests exercising the various strings
2702 // processs url prefix, if any
2703 size_t urlLen = slash - start;
2707 if (urlLen && devAddr)
2708 { // construct OCDevAddr
2709 if (start[0] == '[')
2711 char *close = strchr(++start, ']');
2712 if (!close || close > slash)
2714 return OC_STACK_INVALID_URI;
2717 if (close[1] == ':')
2724 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2728 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2730 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2734 char *dot = strchr(start, '.');
2735 if (dot && dot < slash)
2737 colon = strchr(start, ':');
2738 end = (colon && colon < slash) ? colon : slash;
2743 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2747 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2749 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2757 if (len >= sizeof(da->addr))
2759 return OC_STACK_INVALID_URI;
2761 // collect port, if any
2762 if (colon && colon < slash)
2764 for (colon++; colon < slash; colon++)
2767 if (c < '0' || c > '9')
2769 return OC_STACK_INVALID_URI;
2771 port = 10 * port + c - '0';
2776 if (len >= sizeof(da->addr))
2778 return OC_STACK_INVALID_URI;
2781 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2784 return OC_STACK_NO_MEMORY;
2787 // Decode address per RFC 6874.
2788 result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2789 if (result != OC_STACK_OK)
2796 da->adapter = adapter;
2798 if (!strncmp(fullUri, "coaps", 5))
2800 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2805 // process resource uri, if any
2807 { // request uri and query
2808 size_t ulen = strlen(slash); // resource uri length
2809 size_t tlen = 0; // resource type length
2812 static const char strPresence[] = "/oic/ad?rt=";
2813 static const size_t lenPresence = sizeof(strPresence) - 1;
2814 if (!strncmp(slash, strPresence, lenPresence))
2816 type = slash + lenPresence;
2817 tlen = ulen - lenPresence;
2822 *resourceUri = (char *)OICMalloc(ulen + 1);
2825 result = OC_STACK_NO_MEMORY;
2828 OICStrcpy(*resourceUri, (ulen + 1), slash);
2831 if (type && resourceType)
2833 *resourceType = (char *)OICMalloc(tlen + 1);
2836 result = OC_STACK_NO_MEMORY;
2840 OICStrcpy(*resourceType, (tlen+1), type);
2847 // free all returned values
2854 OICFree(*resourceUri);
2858 OICFree(*resourceType);
2863 #ifdef WITH_PRESENCE
2864 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2868 char uri[CA_MAX_URI_LENGTH];
2870 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2872 *requestUri = OICStrdup(uri);
2875 return OC_STACK_NO_MEMORY;
2880 #endif // WITH_PRESENCE
2883 * Discover or Perform requests on a specified resource
2885 OCStackResult OCDoResource(OCDoHandle *handle,
2887 const char *requestUri,
2888 const OCDevAddr *destination,
2890 OCConnectivityType connectivityType,
2891 OCQualityOfService qos,
2892 OCCallbackData *cbData,
2893 OCHeaderOption *options,
2896 OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
2897 connectivityType, qos, cbData, options, numOptions);
2899 // This is the owner of the payload object, so we free it
2900 OCPayloadDestroy(payload);
2905 * Discover or Perform requests on a specified resource
2907 OCStackResult OCDoRequest(OCDoHandle *handle,
2909 const char *requestUri,
2910 const OCDevAddr *destination,
2912 OCConnectivityType connectivityType,
2913 OCQualityOfService qos,
2914 OCCallbackData *cbData,
2915 OCHeaderOption *options,
2918 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2919 OIC_TRACE_BEGIN(%s:OCDoRequest, TAG);
2921 // Validate input parameters
2922 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2923 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2925 OCStackResult result = OC_STACK_ERROR;
2926 CAResult_t caResult;
2927 CAToken_t token = NULL;
2928 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2929 ClientCB *clientCB = NULL;
2930 OCDoHandle resHandle = NULL;
2931 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2932 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2934 OCTransportAdapter adapter;
2935 OCTransportFlags flags;
2936 // the request contents are put here
2937 CARequestInfo_t requestInfo = {.method = CA_GET};
2938 // requestUri will be parsed into the following three variables
2939 OCDevAddr *devAddr = NULL;
2940 char *resourceUri = NULL;
2941 char *resourceType = NULL;
2944 * Support original behavior with address on resourceUri argument.
2946 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2947 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2951 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2952 if (result != OC_STACK_OK)
2954 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2958 else if (!checkProxyUri(options, numOptions))
2960 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2967 case OC_REST_OBSERVE:
2968 case OC_REST_OBSERVE_ALL:
2969 requestInfo.method = CA_GET;
2972 requestInfo.method = CA_PUT;
2975 requestInfo.method = CA_POST;
2977 case OC_REST_DELETE:
2978 requestInfo.method = CA_DELETE;
2980 case OC_REST_DISCOVER:
2981 #ifdef WITH_PRESENCE
2982 case OC_REST_PRESENCE:
2984 if (destination || devAddr)
2986 requestInfo.isMulticast = false;
2990 tmpDevAddr.adapter = adapter;
2991 tmpDevAddr.flags = flags;
2992 destination = &tmpDevAddr;
2993 requestInfo.isMulticast = true;
2996 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
2997 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
2998 // replacing method type with GET.
2999 requestInfo.method = CA_GET;
3002 result = OC_STACK_INVALID_METHOD;
3006 if (!devAddr && !destination)
3008 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
3009 result = OC_STACK_INVALID_PARAM;
3013 /* If not original behavior, use destination argument */
3014 if (destination && !devAddr)
3016 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
3019 result = OC_STACK_NO_MEMORY;
3022 OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
3023 *devAddr = *destination;
3028 OIC_LOG_V(INFO_PRIVATE, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
3029 if (!requestInfo.isMulticast)
3031 OIC_LOG_V(DEBUG, TAG, "remoteAddr of devAddr : [%s]:[%d]",
3032 devAddr->addr, devAddr->port);
3036 resHandle = GenerateInvocationHandle();
3039 result = OC_STACK_NO_MEMORY;
3043 caResult = CAGenerateToken(&token, tokenLength);
3044 if (caResult != CA_STATUS_OK)
3046 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3047 result= OC_STACK_ERROR;
3051 // fill in request data
3052 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3053 requestInfo.info.token = token;
3054 requestInfo.info.tokenLength = tokenLength;
3056 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3058 result = CreateObserveHeaderOption (&(requestInfo.info.options),
3059 options, numOptions, OC_OBSERVE_REGISTER);
3060 if (result != OC_STACK_OK)
3064 requestInfo.info.numOptions = numOptions + 1;
3068 requestInfo.info.numOptions = numOptions;
3069 requestInfo.info.options =
3070 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3071 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3072 numOptions * sizeof(CAHeaderOption_t));
3075 CopyDevAddrToEndpoint(devAddr, &endpoint);
3080 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3083 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3086 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3090 requestInfo.info.payload = NULL;
3091 requestInfo.info.payloadSize = 0;
3092 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3095 // prepare for response
3096 #ifdef WITH_PRESENCE
3097 if (method == OC_REST_PRESENCE)
3099 char *presenceUri = NULL;
3100 result = OCPreparePresence(&endpoint, &presenceUri,
3101 requestInfo.isMulticast);
3102 if (OC_STACK_OK != result)
3107 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3108 // Presence notification will form a canonical uri to
3109 // look for callbacks into the application.
3112 OICFree(resourceUri);
3114 resourceUri = presenceUri;
3118 // update resourceUri onto requestInfo after check presence uri
3119 requestInfo.info.resourceUri = resourceUri;
3121 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3122 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3123 method, devAddr, resourceUri, resourceType, ttl);
3124 if (OC_STACK_OK != result)
3129 devAddr = NULL; // Client CB list entry now owns it
3130 resourceUri = NULL; // Client CB list entry now owns it
3131 resourceType = NULL; // Client CB list entry now owns it
3133 #ifdef WITH_PRESENCE
3134 if (method == OC_REST_PRESENCE)
3136 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3140 *handle = resHandle;
3148 result = OCSendRequest(&endpoint, &requestInfo);
3149 if (OC_STACK_OK != result)
3156 *handle = resHandle;
3160 if (result != OC_STACK_OK)
3162 OIC_LOG(ERROR, TAG, "OCDoResource error");
3163 FindAndDeleteClientCB(clientCB);
3164 CADestroyToken(token);
3172 OICFree(requestInfo.info.payload);
3174 OICFree(resourceUri);
3175 OICFree(resourceType);
3176 OICFree(requestInfo.info.options);
3181 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3185 * This ftn is implemented one of two ways in the case of observation:
3187 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3188 * Remove the callback associated on client side.
3189 * When the next notification comes in from server,
3190 * reply with RESET message to server.
3191 * Keep in mind that the server will react to RESET only
3192 * if the last notification was sent as CON
3194 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3195 * and it is associated with an observe request
3196 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3197 * Send CON Observe request to server with
3198 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3199 * Remove the callback associated on client side.
3201 OCStackResult ret = OC_STACK_OK;
3202 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3203 CARequestInfo_t requestInfo = {.method = CA_GET};
3207 return OC_STACK_INVALID_PARAM;
3210 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3213 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3214 return OC_STACK_ERROR;
3217 switch (clientCB->method)
3219 case OC_REST_OBSERVE:
3220 case OC_REST_OBSERVE_ALL:
3222 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3224 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3226 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
3228 FindAndDeleteClientCB(clientCB);
3232 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3234 requestInfo.info.type = qualityOfServiceToMessageType(qos);
3235 requestInfo.info.token = clientCB->token;
3236 requestInfo.info.tokenLength = clientCB->tokenLength;
3238 if (CreateObserveHeaderOption (&(requestInfo.info.options),
3239 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3241 return OC_STACK_ERROR;
3243 requestInfo.info.numOptions = numOptions + 1;
3244 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3247 ret = OCSendRequest(&endpoint, &requestInfo);
3249 if (requestInfo.info.options)
3251 OICFree (requestInfo.info.options);
3253 if (requestInfo.info.resourceUri)
3255 OICFree (requestInfo.info.resourceUri);
3260 case OC_REST_DISCOVER:
3261 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3262 clientCB->requestUri);
3263 FindAndDeleteClientCB(clientCB);
3266 #ifdef WITH_PRESENCE
3267 case OC_REST_PRESENCE:
3268 FindAndDeleteClientCB(clientCB);
3274 case OC_REST_DELETE:
3275 OIC_LOG_V(INFO, TAG, "Cancelling request callback for resource %s",
3276 clientCB->requestUri);
3277 FindAndDeleteClientCB(clientCB);
3281 ret = OC_STACK_INVALID_METHOD;
3289 * @brief Register Persistent storage callback.
3290 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3292 * OC_STACK_OK - No errors; Success
3293 * OC_STACK_INVALID_PARAM - Invalid parameter
3295 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3297 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3298 if(!persistentStorageHandler)
3300 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3301 return OC_STACK_INVALID_PARAM;
3305 if( !persistentStorageHandler->open ||
3306 !persistentStorageHandler->close ||
3307 !persistentStorageHandler->read ||
3308 !persistentStorageHandler->unlink ||
3309 !persistentStorageHandler->write)
3311 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3312 return OC_STACK_INVALID_PARAM;
3315 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3318 #ifdef WITH_PRESENCE
3320 OCStackResult OCProcessPresence()
3322 OCStackResult result = OC_STACK_OK;
3324 // the following line floods the log with messages that are irrelevant
3325 // to most purposes. Uncomment as needed.
3326 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3327 ClientCB* cbNode = NULL;
3328 OCClientResponse clientResponse;
3329 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3331 LL_FOREACH(cbList, cbNode)
3333 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3338 uint32_t now = GetTicks(0);
3339 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3340 cbNode->presence->TTLlevel);
3341 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3343 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3348 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3350 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3351 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3353 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3355 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3357 clientResponse.sequenceNumber = 0;
3358 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3359 clientResponse.devAddr = *cbNode->devAddr;
3360 FixUpClientResponse(&clientResponse);
3361 clientResponse.payload = NULL;
3363 // Increment the TTLLevel (going to a next state), so we don't keep
3364 // sending presence notification to client.
3365 cbNode->presence->TTLlevel++;
3366 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3367 cbNode->presence->TTLlevel);
3369 OIC_LOG(INFO, TAG, "Before calling into application address space for presence timeout");
3370 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3371 OIC_LOG(INFO, TAG, "After calling into application address space for presence timeout");
3373 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3375 FindAndDeleteClientCB(cbNode);
3379 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3384 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3385 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3386 CARequestInfo_t requestInfo = {.method = CA_GET};
3388 OIC_LOG(DEBUG, TAG, "time to test server presence");
3390 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3392 requestData.type = CA_MSG_NONCONFIRM;
3393 requestData.token = cbNode->token;
3394 requestData.tokenLength = cbNode->tokenLength;
3395 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3396 requestInfo.method = CA_GET;
3397 requestInfo.info = requestData;
3399 result = OCSendRequest(&endpoint, &requestInfo);
3400 if (OC_STACK_OK != result)
3405 cbNode->presence->TTLlevel++;
3406 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3409 if (result != OC_STACK_OK)
3411 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3416 #endif // WITH_PRESENCE
3418 OCStackResult OCProcess()
3420 if (stackState == OC_STACK_UNINITIALIZED)
3422 OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3423 return OC_STACK_ERROR;
3425 #ifdef WITH_PRESENCE
3426 OCProcessPresence();
3428 CAHandleRequestResponse();
3430 #ifdef ROUTING_GATEWAY
3435 OCProcessKeepAlive();
3440 #ifdef WITH_PRESENCE
3441 OCStackResult OCStartPresence(const uint32_t ttl)
3443 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3444 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3445 OCChangeResourceProperty(
3446 &(((OCResource *)presenceResource.handle)->resourceProperties),
3449 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3451 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3452 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3456 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3457 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3461 presenceResource.presenceTTL = ttl;
3464 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3467 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3469 presenceState = OC_PRESENCE_INITIALIZED;
3471 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3473 CAToken_t caToken = NULL;
3474 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3475 if (caResult != CA_STATUS_OK)
3477 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3478 CADestroyToken(caToken);
3479 return OC_STACK_ERROR;
3482 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3483 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3484 CADestroyToken(caToken);
3487 // Each time OCStartPresence is called
3488 // a different random 32-bit integer number is used
3489 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3491 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3492 OC_PRESENCE_TRIGGER_CREATE);
3495 OCStackResult OCStopPresence()
3497 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3498 OCStackResult result = OC_STACK_ERROR;
3500 if(presenceResource.handle)
3502 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3504 // make resource inactive
3505 result = OCChangeResourceProperty(
3506 &(((OCResource *) presenceResource.handle)->resourceProperties),
3510 if(result != OC_STACK_OK)
3513 "Changing the presence resource properties to ACTIVE not successful");
3517 return SendStopNotification();
3521 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3522 void* callbackParameter)
3524 defaultDeviceHandler = entityHandler;
3525 defaultDeviceHandlerCallbackParameter = callbackParameter;
3530 OCStackResult OCCreateResource(OCResourceHandle *handle,
3531 const char *resourceTypeName,
3532 const char *resourceInterfaceName,
3533 const char *uri, OCEntityHandler entityHandler,
3534 void* callbackParam,
3535 uint8_t resourceProperties)
3538 OCResource *pointer = NULL;
3539 OCStackResult result = OC_STACK_ERROR;
3541 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3543 if(myStackMode == OC_CLIENT)
3545 return OC_STACK_INVALID_PARAM;
3547 // Validate parameters
3548 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3550 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3551 return OC_STACK_INVALID_URI;
3553 // Is it presented during resource discovery?
3554 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3556 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3557 return OC_STACK_INVALID_PARAM;
3560 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3562 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3566 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3568 // Make sure resourceProperties bitmask has allowed properties specified
3569 if (resourceProperties
3570 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3571 OC_EXPLICIT_DISCOVERABLE
3580 OIC_LOG(ERROR, TAG, "Invalid property");
3581 return OC_STACK_INVALID_PARAM;
3584 // If the headResource is NULL, then no resources have been created...
3585 pointer = headResource;
3588 // At least one resources is in the resource list, so we need to search for
3589 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3592 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3594 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3595 return OC_STACK_INVALID_PARAM;
3597 pointer = pointer->next;
3600 // Create the pointer and insert it into the resource list
3601 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3604 result = OC_STACK_NO_MEMORY;
3607 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3609 insertResource(pointer);
3612 pointer->uri = OICStrdup(uri);
3615 result = OC_STACK_NO_MEMORY;
3619 // Set properties. Set OC_ACTIVE
3620 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3623 // Add the resourcetype to the resource
3624 result = BindResourceTypeToResource(pointer, resourceTypeName);
3625 if (result != OC_STACK_OK)
3627 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3631 // Add the resourceinterface to the resource
3632 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3633 if (result != OC_STACK_OK)
3635 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3639 // If an entity handler has been passed, attach it to the newly created
3640 // resource. Otherwise, set the default entity handler.
3643 pointer->entityHandler = entityHandler;
3644 pointer->entityHandlerCallbackParam = callbackParam;
3648 pointer->entityHandler = defaultResourceEHandler;
3649 pointer->entityHandlerCallbackParam = NULL;
3652 // Initialize a pointer indicating child resources in case of collection
3653 pointer->rsrcChildResourcesHead = NULL;
3656 result = OC_STACK_OK;
3658 #ifdef WITH_PRESENCE
3659 if (presenceResource.handle)
3661 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3662 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3666 if (result != OC_STACK_OK)
3668 // Deep delete of resource and other dynamic elements that it contains
3669 deleteResource(pointer);
3674 OCStackResult OCBindResource(
3675 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3677 OCResource *resource = NULL;
3678 OCChildResource *tempChildResource = NULL;
3679 OCChildResource *newChildResource = NULL;
3681 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3683 // Validate parameters
3684 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3685 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3686 // Container cannot contain itself
3687 if (collectionHandle == resourceHandle)
3689 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3690 return OC_STACK_INVALID_PARAM;
3693 // Use the handle to find the resource in the resource linked list
3694 resource = findResource((OCResource *) collectionHandle);
3697 OIC_LOG(ERROR, TAG, "Collection handle not found");
3698 return OC_STACK_INVALID_PARAM;
3701 // Look for an open slot to add add the child resource.
3702 // If found, add it and return success
3704 tempChildResource = resource->rsrcChildResourcesHead;
3706 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3708 // TODO: what if one of child resource was deregistered without unbinding?
3709 tempChildResource = tempChildResource->next;
3712 // Do memory allocation for child resource
3713 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3714 if(!newChildResource)
3716 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3717 return OC_STACK_ERROR;
3720 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3721 newChildResource->next = NULL;
3723 if(!resource->rsrcChildResourcesHead)
3725 resource->rsrcChildResourcesHead = newChildResource;
3728 tempChildResource->next = newChildResource;
3731 OIC_LOG(INFO, TAG, "resource bound");
3733 #ifdef WITH_PRESENCE
3734 if (presenceResource.handle)
3736 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3737 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3738 OC_PRESENCE_TRIGGER_CHANGE);
3745 OCStackResult OCUnBindResource(
3746 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3748 OCResource *resource = NULL;
3749 OCChildResource *tempChildResource = NULL;
3750 OCChildResource *tempLastChildResource = NULL;
3752 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3754 // Validate parameters
3755 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3756 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3757 // Container cannot contain itself
3758 if (collectionHandle == resourceHandle)
3760 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3761 return OC_STACK_INVALID_PARAM;
3764 // Use the handle to find the resource in the resource linked list
3765 resource = findResource((OCResource *) collectionHandle);
3768 OIC_LOG(ERROR, TAG, "Collection handle not found");
3769 return OC_STACK_INVALID_PARAM;
3772 // Look for an open slot to add add the child resource.
3773 // If found, add it and return success
3774 if(!resource->rsrcChildResourcesHead)
3776 OIC_LOG(INFO, TAG, "resource not found in collection");
3778 // Unable to add resourceHandle, so return error
3779 return OC_STACK_ERROR;
3783 tempChildResource = resource->rsrcChildResourcesHead;
3785 while (tempChildResource)
3787 if(tempChildResource->rsrcResource == resourceHandle)
3789 // if resource going to be unbinded is the head one.
3790 if( tempChildResource == resource->rsrcChildResourcesHead )
3792 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3793 OICFree(resource->rsrcChildResourcesHead);
3794 resource->rsrcChildResourcesHead = temp;
3799 OCChildResource *temp = tempChildResource->next;
3800 OICFree(tempChildResource);
3801 if (tempLastChildResource)
3803 tempLastChildResource->next = temp;
3808 OIC_LOG(INFO, TAG, "resource unbound");
3810 // Send notification when resource is unbounded successfully.
3811 #ifdef WITH_PRESENCE
3812 if (presenceResource.handle)
3814 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3815 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3816 OC_PRESENCE_TRIGGER_CHANGE);
3819 tempChildResource = NULL;
3820 tempLastChildResource = NULL;
3826 tempLastChildResource = tempChildResource;
3827 tempChildResource = tempChildResource->next;
3830 OIC_LOG(INFO, TAG, "resource not found in collection");
3832 tempChildResource = NULL;
3833 tempLastChildResource = NULL;
3835 // Unable to add resourceHandle, so return error
3836 return OC_STACK_ERROR;
3839 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3841 if (!resourceItemName)
3845 // Per RFC 6690 only registered values must follow the first rule below.
3846 // At this point in time the only values registered begin with "core", and
3847 // all other values are specified as opaque strings where multiple values
3848 // are separated by a space.
3849 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3851 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3853 if (resourceItemName[index] != '.'
3854 && resourceItemName[index] != '-'
3855 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3856 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3864 for (size_t index = 0; resourceItemName[index]; ++index)
3866 if (resourceItemName[index] == ' '
3867 || resourceItemName[index] == '\t'
3868 || resourceItemName[index] == '\r'
3869 || resourceItemName[index] == '\n')
3879 OCStackResult BindResourceTypeToResource(OCResource* resource,
3880 const char *resourceTypeName)
3882 OCResourceType *pointer = NULL;
3884 OCStackResult result = OC_STACK_ERROR;
3886 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3888 if (!ValidateResourceTypeInterface(resourceTypeName))
3890 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3891 return OC_STACK_INVALID_PARAM;
3894 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3897 result = OC_STACK_NO_MEMORY;
3901 str = OICStrdup(resourceTypeName);
3904 result = OC_STACK_NO_MEMORY;
3907 pointer->resourcetypename = str;
3908 pointer->next = NULL;
3910 insertResourceType(resource, pointer);
3911 result = OC_STACK_OK;
3914 if (result != OC_STACK_OK)
3923 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3924 const char *resourceInterfaceName)
3926 OCResourceInterface *pointer = NULL;
3928 OCStackResult result = OC_STACK_ERROR;
3930 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3932 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3934 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3935 return OC_STACK_INVALID_PARAM;
3938 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3940 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3943 result = OC_STACK_NO_MEMORY;
3947 str = OICStrdup(resourceInterfaceName);
3950 result = OC_STACK_NO_MEMORY;
3953 pointer->name = str;
3955 // Bind the resourceinterface to the resource
3956 insertResourceInterface(resource, pointer);
3958 result = OC_STACK_OK;
3961 if (result != OC_STACK_OK)
3970 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3971 const char *resourceTypeName)
3974 OCStackResult result = OC_STACK_ERROR;
3975 OCResource *resource = NULL;
3977 resource = findResource((OCResource *) handle);
3980 OIC_LOG(ERROR, TAG, "Resource not found");
3981 return OC_STACK_ERROR;
3984 result = BindResourceTypeToResource(resource, resourceTypeName);
3986 #ifdef WITH_PRESENCE
3987 if(presenceResource.handle)
3989 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3990 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3997 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3998 const char *resourceInterfaceName)
4001 OCStackResult result = OC_STACK_ERROR;
4002 OCResource *resource = NULL;
4004 resource = findResource((OCResource *) handle);
4007 OIC_LOG(ERROR, TAG, "Resource not found");
4008 return OC_STACK_ERROR;
4011 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
4013 #ifdef WITH_PRESENCE
4014 if (presenceResource.handle)
4016 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4017 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4024 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
4026 OCResource *pointer = headResource;
4028 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
4032 *numResources = *numResources + 1;
4033 pointer = pointer->next;
4038 OCResourceHandle OCGetResourceHandle(uint8_t index)
4040 OCResource *pointer = headResource;
4042 for( uint8_t i = 0; i < index && pointer; ++i)
4044 pointer = pointer->next;
4046 return (OCResourceHandle) pointer;
4049 OCStackResult OCDeleteResource(OCResourceHandle handle)
4053 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4054 return OC_STACK_INVALID_PARAM;
4057 OCResource *resource = findResource((OCResource *) handle);
4058 if (resource == NULL)
4060 OIC_LOG(ERROR, TAG, "Resource not found");
4061 return OC_STACK_NO_RESOURCE;
4064 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4066 OIC_LOG(ERROR, TAG, "Error deleting resource");
4067 return OC_STACK_ERROR;
4073 const char *OCGetResourceUri(OCResourceHandle handle)
4075 OCResource *resource = NULL;
4077 resource = findResource((OCResource *) handle);
4080 return resource->uri;
4082 return (const char *) NULL;
4085 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4087 OCResource *resource = NULL;
4089 resource = findResource((OCResource *) handle);
4092 return resource->resourceProperties;
4094 return (OCResourceProperty)-1;
4097 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4098 uint8_t *numResourceTypes)
4100 OCResource *resource = NULL;
4101 OCResourceType *pointer = NULL;
4103 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4104 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4106 *numResourceTypes = 0;
4108 resource = findResource((OCResource *) handle);
4111 pointer = resource->rsrcType;
4114 *numResourceTypes = *numResourceTypes + 1;
4115 pointer = pointer->next;
4121 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4123 OCResourceType *resourceType = NULL;
4125 resourceType = findResourceTypeAtIndex(handle, index);
4128 return resourceType->resourcetypename;
4130 return (const char *) NULL;
4133 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4134 uint8_t *numResourceInterfaces)
4136 OCResourceInterface *pointer = NULL;
4137 OCResource *resource = NULL;
4139 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4140 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4142 *numResourceInterfaces = 0;
4143 resource = findResource((OCResource *) handle);
4146 pointer = resource->rsrcInterface;
4149 *numResourceInterfaces = *numResourceInterfaces + 1;
4150 pointer = pointer->next;
4156 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4158 OCResourceInterface *resourceInterface = NULL;
4160 resourceInterface = findResourceInterfaceAtIndex(handle, index);
4161 if (resourceInterface)
4163 return resourceInterface->name;
4165 return (const char *) NULL;
4168 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4171 OCResource *resource = NULL;
4172 OCChildResource *tempChildResource = NULL;
4175 resource = findResource((OCResource *) collectionHandle);
4181 tempChildResource = resource->rsrcChildResourcesHead;
4183 while(tempChildResource)
4187 return tempChildResource->rsrcResource;
4190 tempChildResource = tempChildResource->next;
4193 // In this case, the number of resource handles in the collection exceeds the index
4194 tempChildResource = NULL;
4198 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4199 OCEntityHandler entityHandler,
4200 void* callbackParam)
4202 OCResource *resource = NULL;
4204 // Validate parameters
4205 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4207 // Use the handle to find the resource in the resource linked list
4208 resource = findResource((OCResource *)handle);
4211 OIC_LOG(ERROR, TAG, "Resource not found");
4212 return OC_STACK_ERROR;
4216 resource->entityHandler = entityHandler;
4217 resource->entityHandlerCallbackParam = callbackParam;
4219 #ifdef WITH_PRESENCE
4220 if (presenceResource.handle)
4222 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4223 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4230 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4232 OCResource *resource = NULL;
4234 resource = findResource((OCResource *)handle);
4237 OIC_LOG(ERROR, TAG, "Resource not found");
4242 return resource->entityHandler;
4245 void incrementSequenceNumber(OCResource * resPtr)
4247 // Increment the sequence number
4248 resPtr->sequenceNum += 1;
4249 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4251 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4256 #ifdef WITH_PRESENCE
4257 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4258 OCPresenceTrigger trigger)
4260 OIC_LOG(INFO, TAG, "SendPresenceNotification");
4261 OCResource *resPtr = NULL;
4262 OCStackResult result = OC_STACK_ERROR;
4263 OCMethod method = OC_REST_PRESENCE;
4264 uint32_t maxAge = 0;
4265 resPtr = findResource((OCResource *) presenceResource.handle);
4268 return OC_STACK_NO_RESOURCE;
4271 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4273 maxAge = presenceResource.presenceTTL;
4275 result = SendAllObserverNotification(method, resPtr, maxAge,
4276 trigger, resourceType, OC_LOW_QOS);
4282 OCStackResult SendStopNotification()
4284 OIC_LOG(INFO, TAG, "SendStopNotification");
4285 OCResource *resPtr = NULL;
4286 OCStackResult result = OC_STACK_ERROR;
4287 OCMethod method = OC_REST_PRESENCE;
4288 resPtr = findResource((OCResource *) presenceResource.handle);
4291 return OC_STACK_NO_RESOURCE;
4294 // maxAge is 0. ResourceType is NULL.
4295 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4301 #endif // WITH_PRESENCE
4302 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4304 OCResource *resPtr = NULL;
4305 OCStackResult result = OC_STACK_ERROR;
4306 OCMethod method = OC_REST_NOMETHOD;
4307 uint32_t maxAge = 0;
4309 OIC_LOG(INFO, TAG, "Notifying all observers");
4310 #ifdef WITH_PRESENCE
4311 if(handle == presenceResource.handle)
4315 #endif // WITH_PRESENCE
4316 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4318 // Verify that the resource exists
4319 resPtr = findResource ((OCResource *) handle);
4322 return OC_STACK_NO_RESOURCE;
4326 //only increment in the case of regular observing (not presence)
4327 incrementSequenceNumber(resPtr);
4328 method = OC_REST_OBSERVE;
4329 maxAge = MAX_OBSERVE_AGE;
4330 #ifdef WITH_PRESENCE
4331 result = SendAllObserverNotification (method, resPtr, maxAge,
4332 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4334 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4341 OCNotifyListOfObservers (OCResourceHandle handle,
4342 OCObservationId *obsIdList,
4343 uint8_t numberOfIds,
4344 const OCRepPayload *payload,
4345 OCQualityOfService qos)
4347 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4349 OCResource *resPtr = NULL;
4350 //TODO: we should allow the server to define this
4351 uint32_t maxAge = MAX_OBSERVE_AGE;
4353 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4354 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4355 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4357 resPtr = findResource ((OCResource *) handle);
4358 if (NULL == resPtr || myStackMode == OC_CLIENT)
4360 return OC_STACK_NO_RESOURCE;
4364 incrementSequenceNumber(resPtr);
4366 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4367 payload, maxAge, qos));
4370 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4372 OIC_TRACE_BEGIN(%s:OCDoResponse, TAG);
4373 OCStackResult result = OC_STACK_ERROR;
4374 OCServerRequest *serverRequest = NULL;
4376 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4378 // Validate input parameters
4379 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4380 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4383 // Get pointer to request info
4384 serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
4387 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4388 result = serverRequest->ehResponseHandler(ehResponse);
4395 //#ifdef DIRECT_PAIRING
4396 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4398 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4399 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4401 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4405 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4408 const OCDPDev_t* OCGetDirectPairedDevices()
4410 return (const OCDPDev_t*)DPGetPairedDevices();
4413 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4414 OCDirectPairingCB resultCallback)
4416 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4417 if(NULL == peer || NULL == pinNumber)
4419 OIC_LOG(ERROR, TAG, "Invalid parameters");
4420 return OC_STACK_INVALID_PARAM;
4422 if (NULL == resultCallback)
4424 OIC_LOG(ERROR, TAG, "Invalid callback");
4425 return OC_STACK_INVALID_CALLBACK;
4428 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4429 pinNumber, (OCDirectPairingResultCB)resultCallback);
4431 //#endif // DIRECT_PAIRING
4433 //-----------------------------------------------------------------------------
4434 // Private internal function definitions
4435 //-----------------------------------------------------------------------------
4436 static OCDoHandle GenerateInvocationHandle()
4438 OCDoHandle handle = NULL;
4439 // Generate token here, it will be deleted when the transaction is deleted
4440 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4443 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4449 #ifdef WITH_PRESENCE
4450 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4451 OCResourceProperty resourceProperties, uint8_t enable)
4455 return OC_STACK_INVALID_PARAM;
4457 if (resourceProperties
4458 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4460 OIC_LOG(ERROR, TAG, "Invalid property");
4461 return OC_STACK_INVALID_PARAM;
4465 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4469 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4475 OCStackResult initResources()
4477 OCStackResult result = OC_STACK_OK;
4479 headResource = NULL;
4480 tailResource = NULL;
4481 // Init Virtual Resources
4482 #ifdef WITH_PRESENCE
4483 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4485 result = OCCreateResource(&presenceResource.handle,
4486 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4488 OC_RSRVD_PRESENCE_URI,
4492 //make resource inactive
4493 result = OCChangeResourceProperty(
4494 &(((OCResource *) presenceResource.handle)->resourceProperties),
4497 #ifndef WITH_ARDUINO
4498 if (result == OC_STACK_OK)
4500 result = SRMInitSecureResources();
4504 if(result == OC_STACK_OK)
4506 CreateResetProfile();
4507 result = OCCreateResource(&deviceResource,
4508 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4509 OC_RSRVD_INTERFACE_DEFAULT,
4510 OC_RSRVD_DEVICE_URI,
4514 if(result == OC_STACK_OK)
4516 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4517 OC_RSRVD_INTERFACE_READ);
4521 if(result == OC_STACK_OK)
4523 result = OCCreateResource(&platformResource,
4524 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4525 OC_RSRVD_INTERFACE_DEFAULT,
4526 OC_RSRVD_PLATFORM_URI,
4530 if(result == OC_STACK_OK)
4532 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4533 OC_RSRVD_INTERFACE_READ);
4540 void insertResource(OCResource *resource)
4544 headResource = resource;
4545 tailResource = resource;
4549 tailResource->next = resource;
4550 tailResource = resource;
4552 resource->next = NULL;
4555 OCResource *findResource(OCResource *resource)
4557 OCResource *pointer = headResource;
4561 if (pointer == resource)
4565 pointer = pointer->next;
4570 void deleteAllResources()
4572 OCResource *pointer = headResource;
4573 OCResource *temp = NULL;
4577 temp = pointer->next;
4578 #ifdef WITH_PRESENCE
4579 if (pointer != (OCResource *) presenceResource.handle)
4581 #endif // WITH_PRESENCE
4582 deleteResource(pointer);
4583 #ifdef WITH_PRESENCE
4585 #endif // WITH_PRESENCE
4588 memset(&platformResource, 0, sizeof(platformResource));
4589 memset(&deviceResource, 0, sizeof(deviceResource));
4591 memset(&brokerResource, 0, sizeof(brokerResource));
4594 SRMDeInitSecureResources();
4596 #ifdef WITH_PRESENCE
4597 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4598 // presence notification attributed to their deletion to be processed.
4599 deleteResource((OCResource *) presenceResource.handle);
4600 memset(&presenceResource, 0, sizeof(presenceResource));
4601 #endif // WITH_PRESENCE
4604 OCStackResult deleteResource(OCResource *resource)
4606 OCResource *prev = NULL;
4607 OCResource *temp = NULL;
4610 OIC_LOG(DEBUG,TAG,"resource is NULL");
4611 return OC_STACK_INVALID_PARAM;
4614 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4616 temp = headResource;
4619 if (temp == resource)
4621 // Invalidate all Resource Properties.
4622 resource->resourceProperties = (OCResourceProperty) 0;
4623 #ifdef WITH_PRESENCE
4624 if(resource != (OCResource *) presenceResource.handle)
4626 #endif // WITH_PRESENCE
4627 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4628 #ifdef WITH_PRESENCE
4631 if(presenceResource.handle)
4633 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4634 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4637 // Only resource in list.
4638 if (temp == headResource && temp == tailResource)
4640 headResource = NULL;
4641 tailResource = NULL;
4644 else if (temp == headResource)
4646 headResource = temp->next;
4649 else if (temp == tailResource && prev)
4651 tailResource = prev;
4652 tailResource->next = NULL;
4656 prev->next = temp->next;
4659 deleteResourceElements(temp);
4670 return OC_STACK_ERROR;
4673 void deleteResourceElements(OCResource *resource)
4682 OICFree(resource->uri);
4683 resource->uri = NULL;
4685 if (resource->rsrcType)
4687 deleteResourceType(resource->rsrcType);
4688 resource->rsrcType = NULL;
4690 if (resource->rsrcInterface)
4692 deleteResourceInterface(resource->rsrcInterface);
4693 resource->rsrcInterface = NULL;
4695 if (resource->rsrcChildResourcesHead)
4697 unbindChildResources(resource->rsrcChildResourcesHead);
4698 resource->rsrcChildResourcesHead = NULL;
4700 if (resource->rsrcAttributes)
4702 OCDeleteResourceAttributes(resource->rsrcAttributes);
4703 resource->rsrcAttributes = NULL;
4708 void deleteResourceType(OCResourceType *resourceType)
4710 OCResourceType *next = NULL;
4712 for (OCResourceType *pointer = resourceType; pointer; pointer = next)
4714 next = pointer->next ? pointer->next : NULL;
4715 if (pointer->resourcetypename)
4717 OICFree(pointer->resourcetypename);
4718 pointer->resourcetypename = NULL;
4724 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4726 OCResourceInterface *next = NULL;
4727 for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
4729 next = pointer->next ? pointer->next : NULL;
4732 OICFree(pointer->name);
4733 pointer->name = NULL;
4739 void unbindChildResources(OCChildResource *head)
4741 OCChildResource *next = NULL;
4742 for (OCChildResource *current = head; current; current = next)
4744 next = current->next;
4749 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
4751 OCAttribute *next = NULL;
4752 for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
4754 next = pointer->next ? pointer->next : NULL;
4755 if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
4757 OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
4758 pointer->attrValue = NULL;
4760 else if (pointer->attrValue)
4762 OICFree(pointer->attrValue);
4763 pointer->attrValue = NULL;
4765 if (pointer->attrName)
4767 OICFree(pointer->attrName);
4768 pointer->attrName = NULL;
4774 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4776 OCResourceType *pointer = NULL;
4777 OCResourceType *previous = NULL;
4778 if (!resource || !resourceType)
4782 // resource type list is empty.
4783 else if (!resource->rsrcType)
4785 resource->rsrcType = resourceType;
4789 pointer = resource->rsrcType;
4793 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4795 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4796 OICFree(resourceType->resourcetypename);
4797 OICFree(resourceType);
4801 pointer = pointer->next;
4806 previous->next = resourceType;
4809 resourceType->next = NULL;
4811 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4814 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4816 OCResource *resource = NULL;
4817 OCResourceType *pointer = NULL;
4819 // Find the specified resource
4820 resource = findResource((OCResource *) handle);
4826 // Make sure a resource has a resourcetype
4827 if (!resource->rsrcType)
4832 // Iterate through the list
4833 pointer = resource->rsrcType;
4834 for(uint8_t i = 0; i< index && pointer; ++i)
4836 pointer = pointer->next;
4841 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4843 if(resourceTypeList && resourceTypeName)
4845 OCResourceType * rtPointer = resourceTypeList;
4846 while(resourceTypeName && rtPointer)
4848 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4849 if(rtPointer->resourcetypename &&
4850 strcmp(resourceTypeName, (const char *)
4851 (rtPointer->resourcetypename)) == 0)
4855 rtPointer = rtPointer->next;
4863 * Insert a new interface into interface linked list only if not already present.
4864 * If alredy present, 2nd arg is free'd.
4865 * Default interface will always be first if present.
4867 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4869 OCResourceInterface *pointer = NULL;
4870 OCResourceInterface *previous = NULL;
4872 newInterface->next = NULL;
4874 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4876 if (!*firstInterface)
4878 // If first interface is not oic.if.baseline, by default add it as first interface type.
4879 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4881 *firstInterface = newInterface;
4885 OCStackResult result = BindResourceInterfaceToResource(resource,
4886 OC_RSRVD_INTERFACE_DEFAULT);
4887 if (result != OC_STACK_OK)
4889 OICFree(newInterface->name);
4890 OICFree(newInterface);
4893 if (*firstInterface)
4895 (*firstInterface)->next = newInterface;
4899 // If once add oic.if.baseline, later too below code take care of freeing memory.
4900 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4902 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4904 OICFree(newInterface->name);
4905 OICFree(newInterface);
4908 // This code will not hit anymore, keeping
4911 newInterface->next = *firstInterface;
4912 *firstInterface = newInterface;
4917 pointer = *firstInterface;
4920 if (strcmp(newInterface->name, pointer->name) == 0)
4922 OICFree(newInterface->name);
4923 OICFree(newInterface);
4927 pointer = pointer->next;
4932 previous->next = newInterface;
4937 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4940 OCResource *resource = NULL;
4941 OCResourceInterface *pointer = NULL;
4943 // Find the specified resource
4944 resource = findResource((OCResource *) handle);
4950 // Make sure a resource has a resourceinterface
4951 if (!resource->rsrcInterface)
4956 // Iterate through the list
4957 pointer = resource->rsrcInterface;
4959 for (uint8_t i = 0; i < index && pointer; ++i)
4961 pointer = pointer->next;
4967 * This function splits the uri using the '?' delimiter.
4968 * "uriWithoutQuery" is the block of characters between the beginning
4969 * till the delimiter or '\0' which ever comes first.
4970 * "query" is whatever is to the right of the delimiter if present.
4971 * No delimiter sets the query to NULL.
4972 * If either are present, they will be malloc'ed into the params 2, 3.
4973 * The first param, *uri is left untouched.
4975 * NOTE: This function does not account for whitespace at the end of the uri NOR
4976 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4977 * part of the query.
4979 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4983 return OC_STACK_INVALID_URI;
4985 if(!query || !uriWithoutQuery)
4987 return OC_STACK_INVALID_PARAM;
4991 *uriWithoutQuery = NULL;
4993 size_t uriWithoutQueryLen = 0;
4994 size_t queryLen = 0;
4995 size_t uriLen = strlen(uri);
4997 char *pointerToDelimiter = strstr(uri, "?");
4999 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
5000 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
5002 if (uriWithoutQueryLen)
5004 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
5005 if (!*uriWithoutQuery)
5009 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
5013 *query = (char *) OICCalloc(queryLen + 1, 1);
5016 OICFree(*uriWithoutQuery);
5017 *uriWithoutQuery = NULL;
5020 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5026 return OC_STACK_NO_MEMORY;
5029 const char* OCGetServerInstanceIDString(void)
5031 static char sidStr[UUID_STRING_SIZE];
5033 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5035 OIC_LOG(FATAL, TAG, "GetDoxmDeviceID failed!");
5039 if (OCConvertUuidToString(sid.id, sidStr) != RAND_UUID_OK)
5041 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5048 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5050 OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5051 CAResult_t retResult = CA_STATUS_FAILED;
5052 CAResult_t caResult = CA_STATUS_OK;
5054 CATransportAdapter_t connTypes[] = {
5056 CA_ADAPTER_RFCOMM_BTEDR,
5057 CA_ADAPTER_GATT_BTLE,
5060 ,CA_ADAPTER_REMOTE_ACCESS
5067 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5069 for(int i = 0; i < numConnTypes; i++)
5071 // If CA status is not initialized, CASelectNetwork() will not be called.
5072 if (caResult != CA_STATUS_NOT_INITIALIZED)
5074 if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5076 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5077 caResult = CASelectNetwork(connTypes[i]);
5078 if (caResult == CA_STATUS_OK)
5080 retResult = CA_STATUS_OK;
5085 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5090 if (retResult != CA_STATUS_OK)
5092 return caResult; // Returns error of appropriate transport that failed fatally.
5098 OCStackResult CAResultToOCResult(CAResult_t caResult)
5104 case CA_STATUS_INVALID_PARAM:
5105 return OC_STACK_INVALID_PARAM;
5106 case CA_ADAPTER_NOT_ENABLED:
5107 return OC_STACK_ADAPTER_NOT_ENABLED;
5108 case CA_SERVER_STARTED_ALREADY:
5110 case CA_SERVER_NOT_STARTED:
5111 return OC_STACK_ERROR;
5112 case CA_DESTINATION_NOT_REACHABLE:
5113 return OC_STACK_COMM_ERROR;
5114 case CA_SOCKET_OPERATION_FAILED:
5115 return OC_STACK_COMM_ERROR;
5116 case CA_SEND_FAILED:
5117 return OC_STACK_COMM_ERROR;
5118 case CA_RECEIVE_FAILED:
5119 return OC_STACK_COMM_ERROR;
5120 case CA_MEMORY_ALLOC_FAILED:
5121 return OC_STACK_NO_MEMORY;
5122 case CA_REQUEST_TIMEOUT:
5123 return OC_STACK_TIMEOUT;
5124 case CA_DESTINATION_DISCONNECTED:
5125 return OC_STACK_COMM_ERROR;
5126 case CA_STATUS_FAILED:
5127 return OC_STACK_ERROR;
5128 case CA_NOT_SUPPORTED:
5129 return OC_STACK_NOTIMPL;
5131 return OC_STACK_ERROR;
5135 bool OCResultToSuccess(OCStackResult ocResult)
5140 case OC_STACK_RESOURCE_CREATED:
5141 case OC_STACK_RESOURCE_DELETED:
5142 case OC_STACK_CONTINUE:
5143 case OC_STACK_RESOURCE_CHANGED:
5144 case OC_STACK_SLOW_RESOURCE:
5152 OCStackResult OCSetProxyURI(const char *uri)
5154 return CAResultToOCResult(CASetProxyUri(uri));
5158 #if defined(RD_CLIENT) || defined(RD_SERVER)
5159 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5161 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5163 OCResource *resource = NULL;
5165 resource = findResource((OCResource *) handle);
5168 OIC_LOG(ERROR, TAG, "Resource not found");
5169 return OC_STACK_ERROR;
5172 resource->ins = ins;
5178 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5179 const OCClientResponse *response)
5181 // Validate input parameters
5182 VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5183 VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5185 char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5188 return OC_STACK_NO_MEMORY;
5190 strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5192 if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5194 OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5196 char rdPubUri[MAX_URI_LENGTH] = { 0 };
5197 snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5198 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5200 if (strcmp(rdPubUri, targetUri) == 0)
5202 // Update resource unique id in stack.
5205 if (response->payload)
5207 OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5208 OCRepPayload **links = NULL;
5209 size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5210 if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5211 &links, dimensions))
5214 for (; i < dimensions[0]; i++)
5217 if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5219 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5221 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5223 OCBindResourceInsToResource(handle, ins);
5232 size_t count = calcDimTotal(dimensions);
5233 for (size_t k = 0; k < count; k++)
5235 OCRepPayloadDestroy(links[k]);
5243 else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5245 OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5247 uint8_t numResources = 0;
5248 OCGetNumberOfResources(&numResources);
5250 char *ins = strstr(targetUri, OC_RSRVD_INS);
5253 for (uint8_t i = 0; i < numResources; i++)
5255 OCResourceHandle resHandle = OCGetResourceHandle(i);
5258 OCBindResourceInsToResource(resHandle, 0);
5264 const char *token = "&";
5265 char *iterTokenPtr = NULL;
5266 char *start = strtok_r(targetUri, token, &iterTokenPtr);
5268 while (start != NULL)
5270 char *query = start;
5271 query = strstr(query, OC_RSRVD_INS);
5274 int64_t queryIns = atoi(query + 4);
5275 for (uint8_t i = 0; i < numResources; i++)
5277 OCResourceHandle resHandle = OCGetResourceHandle(i);
5281 OCGetResourceIns(resHandle, &resIns);
5282 if (queryIns && queryIns == resIns)
5284 OCBindResourceInsToResource(resHandle, 0);
5290 start = strtok_r(NULL, token, &iterTokenPtr);
5299 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5303 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5307 OCResource *pointer = headResource;
5311 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5313 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5316 pointer = pointer->next;
5321 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t *ins)
5323 OCResource *resource = NULL;
5325 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5326 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5328 resource = findResource((OCResource *) handle);
5331 *ins = resource->ins;
5334 return OC_STACK_ERROR;
5338 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5339 const void* optionData, size_t optionDataLength)
5343 OIC_LOG (INFO, TAG, "Header options are NULL");
5344 return OC_STACK_INVALID_PARAM;
5349 OIC_LOG (INFO, TAG, "optionData are NULL");
5350 return OC_STACK_INVALID_PARAM;
5355 OIC_LOG (INFO, TAG, "numOptions is NULL");
5356 return OC_STACK_INVALID_PARAM;
5359 if (*numOptions >= MAX_HEADER_OPTIONS)
5361 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5362 return OC_STACK_NO_MEMORY;
5365 ocHdrOpt += *numOptions;
5366 ocHdrOpt->protocolID = OC_COAP_ID;
5367 ocHdrOpt->optionID = optionID;
5368 ocHdrOpt->optionLength =
5369 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
5370 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5371 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5377 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5378 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5380 if (!ocHdrOpt || !numOptions)
5382 OIC_LOG (INFO, TAG, "No options present");
5388 OIC_LOG (INFO, TAG, "optionData are NULL");
5389 return OC_STACK_INVALID_PARAM;
5392 if (!receivedDataLength)
5394 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5395 return OC_STACK_INVALID_PARAM;
5398 for (uint8_t i = 0; i < numOptions; i++)
5400 if (ocHdrOpt[i].optionID == optionID)
5402 if (optionDataLength >= ocHdrOpt->optionLength)
5404 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5405 *receivedDataLength = ocHdrOpt->optionLength;
5410 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5411 return OC_STACK_ERROR;
5418 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5420 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5421 if (g_adapterHandler)
5423 g_adapterHandler(adapter, enabled);
5427 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5429 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5430 if (g_connectionHandler)
5432 g_connectionHandler(info, isConnected);
5436 * If the client observes one or more resources over a reliable connection,
5437 * then the CoAP server (or intermediary in the role of the CoAP server)
5438 * MUST remove all entries associated with the client endpoint from the lists
5439 * of observers when the connection is either closed or times out.
5443 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5444 CopyEndpointToDevAddr(info, &devAddr);
5446 // remove observer list with remote device address.
5447 DeleteObserverUsingDevAddr(&devAddr);
5451 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5454 OCStackResult ret = OC_STACK_ERROR;
5456 ret = GetDoxmDeviceID(&oicUuid);
5457 if (OC_STACK_OK == ret)
5459 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5463 OIC_LOG(ERROR, TAG, "Device ID Get error");
5468 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5471 OCStackResult ret = OC_STACK_ERROR;
5473 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5474 for (int i = 0; i < UUID_LENGTH; i++)
5476 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5478 ret = SetDoxmDeviceID(&oicUuid);
5482 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5484 bool isDeviceOwned = true;
5485 OCStackResult ret = OC_STACK_ERROR;
5487 ret = GetDoxmIsOwned(&isDeviceOwned);
5488 if (OC_STACK_OK == ret)
5490 *isOwned = isDeviceOwned;
5494 OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5499 void OCClearCallBackList()
5501 DeleteClientCBList();
5504 void OCClearObserverlist()
5506 DeleteObserverList();
5509 int OCEncrypt(const unsigned char *pt, size_t pt_len,
5510 unsigned char **ct, size_t *ct_len)
5512 #ifndef __SECURE_PSI__
5513 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5516 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5518 return psiEncrypt(pt, pt_len, ct, ct_len);
5519 #endif // __SECURE_PSI__
5522 int OCDecrypt(const unsigned char *ct, size_t ct_len,
5523 unsigned char **pt, size_t *pt_len)
5525 #ifndef __SECURE_PSI__
5526 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5529 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5531 return psiDecrypt(ct, ct_len, pt, pt_len);
5532 #endif // __SECURE_PSI__
5535 OCStackResult OCSetKey(const unsigned char* key)
5537 #ifndef __SECURE_PSI__
5538 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5541 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5543 return psiSetKey(key);
5544 #endif // __SECURE_PSI__
5547 OCStackResult OCGetKey(unsigned char* key)
5549 #ifndef __SECURE_PSI__
5550 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5553 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5555 return psiGetKey(key);
5556 #endif // __SECURE_PSI__
5559 OCStackResult OCSetSecurePSI(const unsigned char *key, const OCPersistentStorage *psPlain,
5560 const OCPersistentStorage *psEnc, const OCPersistentStorage *psRescue)
5562 #ifndef __SECURE_PSI__
5563 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5566 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5568 return setSecurePSI(key, psPlain, psEnc, psRescue);
5569 #endif // __SECURE_PSI__
5572 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5573 static void OtmEventHandler(const char *addr, uint16_t port, const char *uuid, int event)
5575 if (g_otmEventHandler.cb)
5577 g_otmEventHandler.cb(g_otmEventHandler.ctx, addr, port, uuid, event);
5582 * It is already declared in srmutility.h.
5583 * We can't include the header file, because of "redefined VERIFY_NON_NULL"
5585 typedef void (*OicSecOtmEventHandler_t)(const char* addr, uint16_t port,
5586 const char* uuid, int event);
5587 void SetOtmEventHandler(OicSecOtmEventHandler_t otmEventHandler);
5590 OCStackResult OCSetOtmEventHandler(void *ctx, OCOtmEventHandler cb)
5592 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5593 OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5595 g_otmEventHandler.cb = cb;
5596 g_otmEventHandler.ctx = ctx;
5598 if (g_otmEventHandler.cb)
5600 OIC_LOG(DEBUG, TAG, "SET OCOtmEventHandler");
5601 SetOtmEventHandler(OtmEventHandler);
5605 OIC_LOG(DEBUG, TAG, "UNSET OCOtmEventHandler");
5606 SetOtmEventHandler(NULL);
5609 OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);