CONPRO-1320] Cleanup observers of deleted resource.
[platform/upstream/iotivity.git] / resource / csdk / stack / src / ocstack.c
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
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
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
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.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21
22 //-----------------------------------------------------------------------------
23 // Includes
24 //-----------------------------------------------------------------------------
25
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
35 #endif
36 #ifndef __STDC_LIMIT_MACROS
37 #define __STDC_LIMIT_MACROS
38 #endif
39 #include "iotivity_config.h"
40 #include <inttypes.h>
41 #include <string.h>
42 #include <ctype.h>
43
44 #include "ocstack.h"
45 #include "ocstackinternal.h"
46 #include "ocresourcehandler.h"
47 #include "occlientcb.h"
48 #include "ocobserve.h"
49 #include "ocrandom.h"
50 #include "oic_malloc.h"
51 #include "oic_string.h"
52 #include "logger.h"
53 #include "trace.h"
54 #include "ocserverrequest.h"
55 #include "secureresourcemanager.h"
56 #include "psinterface.h"
57 #include "psiutils.h"
58 #include "doxmresource.h"
59 #include "cacommon.h"
60 #include "cainterface.h"
61 #include "ocpayload.h"
62 #include "ocpayloadcbor.h"
63 #include "cautilinterface.h"
64 #include "oicgroup.h"
65
66 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
67 #include "routingutility.h"
68 #ifdef ROUTING_GATEWAY
69 #include "routingmanager.h"
70 #endif
71 #endif
72
73 #ifdef TCP_ADAPTER
74 #include "oickeepaliveinternal.h"
75 #endif
76
77 //#ifdef DIRECT_PAIRING
78 #include "directpairing.h"
79 //#endif
80
81 #ifdef HAVE_ARDUINO_TIME_H
82 #include "Time.h"
83 #endif
84 #ifdef HAVE_SYS_TIME_H
85 #include <sys/time.h>
86 #endif
87 #include <coap/coap.h>
88
89 #ifdef HAVE_ARPA_INET_H
90 #include <arpa/inet.h>
91 #endif
92
93 #ifndef UINT32_MAX
94 #define UINT32_MAX   (0xFFFFFFFFUL)
95 #endif
96
97 //-----------------------------------------------------------------------------
98 // Typedefs
99 //-----------------------------------------------------------------------------
100 typedef enum
101 {
102     OC_STACK_UNINITIALIZED = 0,
103     OC_STACK_INITIALIZED,
104     OC_STACK_UNINIT_IN_PROGRESS
105 } OCStackState;
106
107 #ifdef WITH_PRESENCE
108 typedef enum
109 {
110     OC_PRESENCE_UNINITIALIZED = 0,
111     OC_PRESENCE_INITIALIZED
112 } OCPresenceState;
113 #endif
114
115 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
116 typedef struct
117 {
118     OCOtmEventHandler cb;
119     void *ctx;
120 } OCOtmEventHandler_t;
121 #endif
122
123 //-----------------------------------------------------------------------------
124 // Private variables
125 //-----------------------------------------------------------------------------
126 static OCStackState stackState = OC_STACK_UNINITIALIZED;
127
128 OCResource *headResource = NULL;
129 static OCResource *tailResource = NULL;
130 static OCResourceHandle platformResource = {0};
131 static OCResourceHandle deviceResource = {0};
132 #ifdef MQ_BROKER
133 static OCResourceHandle brokerResource = {0};
134 #endif
135
136 #ifdef WITH_PRESENCE
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};
141 #endif
142
143 static OCMode myStackMode;
144 #ifdef RA_ADAPTER
145 //TODO: revisit this design
146 static bool gRASetInfo = false;
147 #endif
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";
153
154 CAAdapterStateChangedCB g_adapterHandler = NULL;
155 CAConnectionStateChangedCB g_connectionHandler = NULL;
156
157 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
158 static OCOtmEventHandler_t g_otmEventHandler = {NULL, NULL};
159 #endif
160
161 //-----------------------------------------------------------------------------
162 // Macros
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");\
172     goto exit;} }
173
174 //TODO: we should allow the server to define this
175 #define MAX_OBSERVE_AGE (0x2FFFFUL)
176
177 #define MILLISECONDS_PER_SECOND   (1000)
178
179 //-----------------------------------------------------------------------------
180 // Private internal function prototypes
181 //-----------------------------------------------------------------------------
182
183 /**
184  * Generate handle of OCDoResource invocation for callback management.
185  *
186  * @return Generated OCDoResource handle.
187  */
188 static OCDoHandle GenerateInvocationHandle();
189
190 /**
191  * Initialize resource data structures, variables, etc.
192  *
193  * @return ::OC_STACK_OK on success, some other value upon failure.
194  */
195 static OCStackResult initResources();
196
197 /**
198  * Add a resource to the end of the linked list of resources.
199  *
200  * @param resource Resource to be added
201  */
202 static void insertResource(OCResource *resource);
203
204 /**
205  * Find a resource in the linked list of resources.
206  *
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
209  *         found.
210  */
211 static OCResource *findResource(OCResource *resource);
212
213 /**
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.
219  *
220  * @param resource Resource where resource type is to be inserted.
221  * @param resourceType Resource type to be inserted.
222  */
223 static void insertResourceType(OCResource *resource,
224         OCResourceType *resourceType);
225
226 /**
227  * Get a resource type at the specified index within a resource.
228  *
229  * @param handle Handle of resource.
230  * @param index Index of resource type.
231  *
232  * @return Pointer to resource type if found, NULL otherwise.
233  */
234 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
235         uint8_t index);
236
237 /**
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.
242  *
243  * @param resource Resource where resource interface is to be inserted.
244  * @param resourceInterface Resource interface to be inserted.
245  */
246 static void insertResourceInterface(OCResource *resource,
247         OCResourceInterface *resourceInterface);
248
249 /**
250  * Get a resource interface at the specified index within a resource.
251  *
252  * @param handle Handle of resource.
253  * @param index Index of resource interface.
254  *
255  * @return Pointer to resource interface if found, NULL otherwise.
256  */
257 static OCResourceInterface *findResourceInterfaceAtIndex(
258         OCResourceHandle handle, uint8_t index);
259
260 /**
261  * Delete all of the dynamically allocated elements that were created for the resource type.
262  *
263  * @param resourceType Specified resource type.
264  */
265 static void deleteResourceType(OCResourceType *resourceType);
266
267 /**
268  * Delete all of the dynamically allocated elements that were created for the resource interface.
269  *
270  * @param resourceInterface Specified resource interface.
271  */
272 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
273
274 /**
275  * Unbind all child resources.
276  *
277  * @param resourceChild Specified binded resource head is deleted from parent.
278  */
279 static void unbindChildResources(OCChildResource *resourceChild);
280
281 /**
282  * Delete all of the dynamically allocated elements that were created for the resource.
283  *
284  * @param resource Specified resource.
285  */
286 static void deleteResourceElements(OCResource *resource);
287
288 /**
289  * Delete resource specified by handle.  Deletes resource and all resourcetype and resourceinterface
290  * linked lists.
291  *
292  * @param handle Handle of resource to be deleted.
293  *
294  * @return ::OC_STACK_OK on success, some other value upon failure.
295  */
296 static OCStackResult deleteResource(OCResource *resource);
297
298 /**
299  * Delete all of the resources in the resource list.
300  */
301 static void deleteAllResources();
302
303 /**
304  * Increment resource sequence number.  Handles rollover.
305  *
306  * @param resPtr Pointer to resource.
307  */
308 static void incrementSequenceNumber(OCResource * resPtr);
309
310 /*
311  * Attempts to initialize every network interface that the CA Layer might have compiled in.
312  *
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.
317  */
318 static CAResult_t OCSelectNetwork(OCTransportAdapter transportType);
319
320 /**
321  * Convert CAResponseResult_t to OCStackResult.
322  *
323  * @param caCode CAResponseResult_t code.
324  * @return ::OC_STACK_OK on success, some other value upon failure.
325  */
326 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
327
328 /**
329  * Convert OCTransportFlags_t to CATransportModifiers_t.
330  *
331  * @param ocConType OCTransportFlags_t input.
332  * @return CATransportFlags
333  */
334 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
335
336 /**
337  * Convert CATransportFlags_t to OCTransportModifiers_t.
338  *
339  * @param caConType CATransportFlags_t input.
340  * @return OCTransportFlags
341  */
342 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
343
344 /**
345  * Handle response from presence request.
346  *
347  * @param endPoint CA remote endpoint.
348  * @param responseInfo CA response info.
349  * @return ::OC_STACK_OK on success, some other value upon failure.
350  */
351 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
352         const CAResponseInfo_t *responseInfo);
353
354 /**
355  * This function will be called back by CA layer when a response is received.
356  *
357  * @param endPoint CA remote endpoint.
358  * @param responseInfo CA response info.
359  */
360 static void HandleCAResponses(const CAEndpoint_t* endPoint,
361         const CAResponseInfo_t* responseInfo);
362
363 /**
364  * This function will be called back by CA layer when a request is received.
365  *
366  * @param endPoint CA remote endpoint.
367  * @param requestInfo CA request info.
368  */
369 static void HandleCARequests(const CAEndpoint_t* endPoint,
370         const CARequestInfo_t* requestInfo);
371
372 /**
373  * Extract query from a URI.
374  *
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.
379  */
380 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
381
382 /**
383  * Finds a resource type in an OCResourceType link-list.
384  *
385  * @param resourceTypeList The link-list to be searched through.
386  * @param resourceTypeName The key to search for.
387  *
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.
390  */
391 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
392         const char * resourceTypeName);
393
394 #ifdef WITH_PRESENCE
395 /**
396  * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
397  * TTL will be set to maxAge.
398  *
399  * @param cbNode Callback Node for which presence ttl is to be reset.
400  * @param maxAge New value of ttl in seconds.
401
402  * @return ::OC_STACK_OK on success, some other value upon failure.
403  */
404 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
405 #endif
406
407 /**
408  * Ensure the accept header option is set appropriatly before sending the requests and routing
409  * header option is updated with destination.
410  *
411  * @param object CA remote endpoint.
412  * @param requestInfo CA request info.
413  *
414  * @return ::OC_STACK_OK on success, some other value upon failure.
415  */
416 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
417
418 /**
419  * default adapter state change callback method
420  *
421  * @param adapter   CA network adapter type.
422  * @param enabled   current adapter state.
423  */
424 static void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled);
425
426 /**
427  * default connection state change callback method
428  *
429  * @param info          CAEndpoint which has address, port and etc.
430  * @param isConnected   current connection state.
431  */
432 static void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected);
433
434 //-----------------------------------------------------------------------------
435 // Internal functions
436 //-----------------------------------------------------------------------------
437
438 bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
439 {
440     if (!options || 0 == numOptions)
441     {
442         OIC_LOG (INFO, TAG, "No options present");
443         return false;
444     }
445
446     for (uint8_t i = 0; i < numOptions; i++)
447     {
448         if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
449         {
450             OIC_LOG(DEBUG, TAG, "Proxy URI is present");
451             return true;
452         }
453     }
454     return false;
455 }
456
457 uint32_t GetTicks(uint32_t milliSeconds)
458 {
459     coap_tick_t now;
460     coap_ticks(&now);
461
462     // Guard against overflow of uint32_t
463     if (milliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
464                              COAP_TICKS_PER_SECOND)
465     {
466         return now + (milliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
467     }
468     else
469     {
470         return UINT32_MAX;
471     }
472 }
473
474 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
475 {
476     VERIFY_NON_NULL_NR(in, FATAL);
477     VERIFY_NON_NULL_NR(out, FATAL);
478
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));
490 #endif
491 }
492
493 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
494 {
495     VERIFY_NON_NULL_NR(in, FATAL);
496     VERIFY_NON_NULL_NR(out, FATAL);
497
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));
508 #endif
509     out->port = in->port;
510     out->ifindex = in->ifindex;
511 }
512
513 void FixUpClientResponse(OCClientResponse *cr)
514 {
515     VERIFY_NON_NULL_NR(cr, FATAL);
516
517     cr->addr = &cr->devAddr;
518     cr->connType = (OCConnectivityType)
519         ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
520 }
521
522 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
523 {
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);
527
528 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
529     OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
530     if (OC_STACK_OK != rmResult)
531     {
532         OIC_LOG(ERROR, TAG, "Add destination option failed");
533         OIC_TRACE_END();
534         return rmResult;
535     }
536 #endif
537
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)
542     {
543         OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
544         OIC_TRACE_END();
545         return CAResultToOCResult(result);
546     }
547
548     OIC_TRACE_END();
549     return OC_STACK_OK;
550 }
551 //-----------------------------------------------------------------------------
552 // Internal API function
553 //-----------------------------------------------------------------------------
554
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)
558 {
559     OCStackResult result = OC_STACK_ERROR;
560     ResourceObserver * observer = NULL;
561     OCEntityHandlerRequest ehRequest = {0};
562
563     switch(status)
564     {
565     case OC_OBSERVER_NOT_INTERESTED:
566         OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
567         observer = GetObserverUsingToken(token, tokenLength);
568         if (observer)
569         {
570             result = FormOCEntityHandlerRequest(&ehRequest,
571                                                 0,
572                                                 OC_REST_NOMETHOD,
573                                                 &observer->devAddr,
574                                                 (OCResourceHandle)NULL,
575                                                 NULL, PAYLOAD_TYPE_REPRESENTATION,
576                                                 NULL, 0, 0, NULL,
577                                                 OC_OBSERVE_DEREGISTER,
578                                                 observer->observeId,
579                                                 0);
580             if (result != OC_STACK_OK)
581             {
582                 FreeObserver(observer);
583                 return result;
584             }
585
586             if (observer->resource && observer->resource->entityHandler)
587             {
588                 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
589                                                   observer->resource->entityHandlerCallbackParam);
590             }
591
592             FreeObserver(observer);
593         }
594
595         result = DeleteObserverUsingToken(token, tokenLength);
596         if (result == OC_STACK_OK)
597         {
598             OIC_LOG(DEBUG, TAG, "Removed observer successfully");
599         }
600         else
601         {
602             result = OC_STACK_OK;
603             OIC_LOG(DEBUG, TAG, "Observer Removal failed");
604         }
605         break;
606
607     case OC_OBSERVER_STILL_INTERESTED:
608         OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
609         observer = GetObserverUsingToken(token, tokenLength);
610         if (observer)
611         {
612             observer->forceHighQos = 0;
613             observer->failedCommCount = 0;
614             result = OC_STACK_OK;
615             FreeObserver(observer);
616         }
617         else
618         {
619             result = OC_STACK_OBSERVER_NOT_FOUND;
620         }
621         break;
622
623     case OC_OBSERVER_FAILED_COMM:
624         OIC_LOG(DEBUG, TAG, "observer is unreachable");
625         observer = GetObserverUsingToken (token, tokenLength);
626         if (observer)
627         {
628             if (observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
629             {
630                 result = FormOCEntityHandlerRequest(&ehRequest,
631                                                     0,
632                                                     OC_REST_NOMETHOD,
633                                                     &observer->devAddr,
634                                                     (OCResourceHandle)NULL,
635                                                     NULL, PAYLOAD_TYPE_REPRESENTATION,
636                                                     NULL, 0, 0, NULL,
637                                                     OC_OBSERVE_DEREGISTER,
638                                                     observer->observeId,
639                                                     0);
640                 if (result != OC_STACK_OK)
641                 {
642                     FreeObserver(observer);
643                     return OC_STACK_ERROR;
644                 }
645
646                 if (observer->resource && observer->resource->entityHandler)
647                 {
648                     observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
649                                         observer->resource->entityHandlerCallbackParam);
650                 }
651
652                 result = DeleteObserverUsingToken(token, tokenLength);
653                 if (result == OC_STACK_OK)
654                 {
655                     OIC_LOG(DEBUG, TAG, "Removed observer successfully");
656                 }
657                 else
658                 {
659                     result = OC_STACK_OK;
660                     OIC_LOG(DEBUG, TAG, "Observer Removal failed");
661                 }
662             }
663             else
664             {
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;
670             }
671
672             FreeObserver(observer);
673         }
674         break;
675     default:
676         OIC_LOG(ERROR, TAG, "Unknown status");
677         result = OC_STACK_ERROR;
678         break;
679         }
680     return result;
681 }
682
683 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
684 {
685     OCStackResult ret = OC_STACK_ERROR;
686     switch(caCode)
687     {
688         case CA_CREATED:
689             ret = OC_STACK_RESOURCE_CREATED;
690             break;
691         case CA_DELETED:
692             ret = OC_STACK_RESOURCE_DELETED;
693             break;
694         case CA_CHANGED:
695             ret = OC_STACK_RESOURCE_CHANGED;
696             break;
697         case CA_CONTENT:
698         case CA_VALID:
699             ret = OC_STACK_OK;
700             break;
701         case CA_BAD_REQ:
702             ret = OC_STACK_INVALID_QUERY;
703             break;
704         case CA_UNAUTHORIZED_REQ:
705             ret = OC_STACK_UNAUTHORIZED_REQ;
706             break;
707         case CA_BAD_OPT:
708             ret = OC_STACK_INVALID_OPTION;
709             break;
710         case CA_NOT_FOUND:
711             ret = OC_STACK_NO_RESOURCE;
712             break;
713         case CA_REQUEST_ENTITY_TOO_LARGE:
714             ret = OC_STACK_TOO_LARGE_REQ;
715             break;
716         case CA_METHOD_NOT_ALLOWED:
717             ret = OC_STACK_METHOD_NOT_ALLOWED;
718             break;
719         case CA_NOT_ACCEPTABLE:
720             ret = OC_STACK_NOT_ACCEPTABLE;
721             break;
722         case CA_FORBIDDEN_REQ:
723             ret = OC_STACK_FORBIDDEN_REQ;
724             break;
725         case CA_TOO_MANY_REQUESTS:
726             ret = OC_STACK_TOO_MANY_REQUESTS;
727             break;
728         case CA_INTERNAL_SERVER_ERROR:
729             ret = OC_STACK_INTERNAL_SERVER_ERROR;
730             break;
731         case CA_NOT_IMPLEMENTED:
732             ret = OC_STACK_NOT_IMPLEMENTED;
733             break;
734         case CA_BAD_GATEWAY:
735             ret = OC_STACK_BAD_GATEWAY;
736             break;
737         case CA_SERVICE_UNAVAILABLE:
738             ret = OC_STACK_SERVICE_UNAVAILABLE;
739             break;
740         case CA_RETRANSMIT_TIMEOUT:
741             ret = OC_STACK_GATEWAY_TIMEOUT;
742             break;
743         case CA_PROXY_NOT_SUPPORTED:
744             ret = OC_STACK_PROXY_NOT_SUPPORTED;
745             break;
746         default:
747             break;
748     }
749     return ret;
750 }
751
752 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
753 {
754     CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
755
756     switch(ocCode)
757     {
758         case OC_STACK_OK:
759            switch (method)
760            {
761                case OC_REST_PUT:
762                case OC_REST_POST:
763                    // This Response Code is like HTTP 204 "No Content" but only used in
764                    // response to POST and PUT requests.
765                    ret = CA_CHANGED;
766                    break;
767                case OC_REST_GET:
768                    // This Response Code is like HTTP 200 "OK" but only used in response to
769                    // GET requests.
770                    ret = CA_CONTENT;
771                    break;
772                default:
773                    // This should not happen but,
774                    // give it a value just in case but output an error
775                    ret = CA_CONTENT;
776                    OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
777                             method);
778             }
779             break;
780         case OC_STACK_RESOURCE_CREATED:
781             ret = CA_CREATED;
782             break;
783         case OC_STACK_RESOURCE_DELETED:
784             ret = CA_DELETED;
785             break;
786         case OC_STACK_RESOURCE_CHANGED:
787             ret = CA_CHANGED;
788             break;
789         case OC_STACK_INVALID_QUERY:
790             ret = CA_BAD_REQ;
791             break;
792         case OC_STACK_INVALID_OPTION:
793             ret = CA_BAD_OPT;
794             break;
795         case OC_STACK_NO_RESOURCE:
796             ret = CA_NOT_FOUND;
797             break;
798         case OC_STACK_COMM_ERROR:
799             ret = CA_RETRANSMIT_TIMEOUT;
800             break;
801         case OC_STACK_METHOD_NOT_ALLOWED:
802             ret = CA_METHOD_NOT_ALLOWED;
803             break;
804         case OC_STACK_NOT_ACCEPTABLE:
805             ret = CA_NOT_ACCEPTABLE;
806             break;
807         case OC_STACK_UNAUTHORIZED_REQ:
808             ret = CA_UNAUTHORIZED_REQ;
809             break;
810         case OC_STACK_FORBIDDEN_REQ:
811             ret = CA_FORBIDDEN_REQ;
812             break;
813         case OC_STACK_TOO_MANY_REQUESTS:
814             ret = CA_TOO_MANY_REQUESTS;
815             break;
816         case OC_STACK_INTERNAL_SERVER_ERROR:
817             ret = CA_INTERNAL_SERVER_ERROR;
818             break;
819         case OC_STACK_NOT_IMPLEMENTED:
820             ret = CA_NOT_IMPLEMENTED;
821             break;
822         case OC_STACK_BAD_GATEWAY:
823             ret = CA_BAD_GATEWAY;
824             break;
825         case OC_STACK_SERVICE_UNAVAILABLE:
826             ret = CA_SERVICE_UNAVAILABLE;
827             break;
828         case OC_STACK_GATEWAY_TIMEOUT:
829             ret = CA_RETRANSMIT_TIMEOUT;
830             break;
831         case OC_STACK_PROXY_NOT_SUPPORTED:
832             ret = CA_PROXY_NOT_SUPPORTED;
833             break;
834         default:
835             break;
836     }
837     return ret;
838 }
839
840 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
841 {
842     CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
843
844     // supply default behavior.
845     if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
846     {
847         caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
848     }
849     if ((caFlags & OC_MASK_SCOPE) == 0)
850     {
851         caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
852     }
853     return caFlags;
854 }
855
856 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
857 {
858     return (OCTransportFlags)caFlags;
859 }
860
861 #ifdef WITH_PRESENCE
862 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
863 {
864     uint32_t lowerBound  = 0;
865     uint32_t higherBound = 0;
866
867     if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
868     {
869         return OC_STACK_INVALID_PARAM;
870     }
871
872     OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
873
874     cbNode->presence->TTL = maxAgeSeconds;
875
876     for (int index = 0; index < PresenceTimeOutSize; index++)
877     {
878         // Guard against overflow
879         if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
880                                      * 100)
881         {
882             lowerBound = GetTicks((PresenceTimeOut[index] *
883                                   cbNode->presence->TTL *
884                                   MILLISECONDS_PER_SECOND)/100);
885         }
886         else
887         {
888             lowerBound = GetTicks(UINT32_MAX);
889         }
890
891         if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
892                                      * 100)
893         {
894             higherBound = GetTicks((PresenceTimeOut[index + 1] *
895                                    cbNode->presence->TTL *
896                                    MILLISECONDS_PER_SECOND)/100);
897         }
898         else
899         {
900             higherBound = GetTicks(UINT32_MAX);
901         }
902
903         cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
904
905         OIC_LOG_V(DEBUG, TAG, "lowerBound timeout  %d", lowerBound);
906         OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
907         OIC_LOG_V(DEBUG, TAG, "timeOut entry  %d", cbNode->presence->timeOut[index]);
908     }
909
910     cbNode->presence->TTLlevel = 0;
911
912     OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
913     return OC_STACK_OK;
914 }
915
916 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
917 {
918     if (trigger == OC_PRESENCE_TRIGGER_CREATE)
919     {
920         return OC_RSRVD_TRIGGER_CREATE;
921     }
922     else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
923     {
924         return OC_RSRVD_TRIGGER_CHANGE;
925     }
926     else
927     {
928         return OC_RSRVD_TRIGGER_DELETE;
929     }
930 }
931
932 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
933 {
934     if(!triggerStr)
935     {
936         return OC_PRESENCE_TRIGGER_CREATE;
937     }
938     else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
939     {
940         return OC_PRESENCE_TRIGGER_CREATE;
941     }
942     else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
943     {
944         return OC_PRESENCE_TRIGGER_CHANGE;
945     }
946     else
947     {
948         return OC_PRESENCE_TRIGGER_DELETE;
949     }
950 }
951 #endif // WITH_PRESENCE
952
953 OCStackResult OCEncodeAddressForRFC6874(char *outputAddress,
954                                         size_t outputSize,
955                                         const char *inputAddress)
956 {
957     VERIFY_NON_NULL(inputAddress,  FATAL, OC_STACK_INVALID_PARAM);
958     VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
959
960     size_t inputLength = strnlen(inputAddress, outputSize);
961
962     // inputSize includes the null terminator
963     size_t inputSize = inputLength + 1;
964
965     if (inputSize > outputSize)
966     {
967         OIC_LOG_V(ERROR, TAG,
968                   "OCEncodeAddressForRFC6874 failed: "
969                   "outputSize (%zu) < inputSize (%zu)",
970                   outputSize, inputSize);
971
972         return OC_STACK_ERROR;
973     }
974
975     char* percentChar = strchr(inputAddress, '%');
976
977     // If there is no '%' character, then no change is required to the string.
978     if (NULL == percentChar)
979     {
980         OICStrcpy(outputAddress, outputSize, inputAddress);
981         return OC_STACK_OK;
982     }
983
984     const char* addressPart = &inputAddress[0];
985     const char* scopeIdPart = percentChar + 1;
986
987     // Sanity check to make sure this string doesn't have more '%' characters
988     if (NULL != strchr(scopeIdPart, '%'))
989     {
990         return OC_STACK_ERROR;
991     }
992
993     // If no string follows the first '%', then the input was invalid.
994     if (scopeIdPart[0] == '\0')
995     {
996         OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
997         return OC_STACK_ERROR;
998     }
999
1000     // Check to see if the string is already encoded
1001     if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
1002     {
1003         OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Input string is already encoded");
1004         return OC_STACK_ERROR;
1005     }
1006
1007     // Fail if we don't have room for encoded string's two additional chars
1008     if (outputSize < (inputSize + 2))
1009     {
1010         OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: encoded output will not fit!");
1011         return OC_STACK_ERROR;
1012     }
1013
1014     // Restore the null terminator with an escaped '%' character, per RFC 6874
1015     OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
1016     OICStrcat(outputAddress, outputSize, "%25");
1017     OICStrcat(outputAddress, outputSize, scopeIdPart);
1018
1019     return OC_STACK_OK;
1020 }
1021
1022 OCStackResult OCDecodeAddressForRFC6874(char *outputAddress,
1023                                         size_t outputSize,
1024                                         const char *inputAddress,
1025                                         const char *end)
1026 {
1027     VERIFY_NON_NULL(inputAddress,  FATAL, OC_STACK_INVALID_PARAM);
1028     VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
1029
1030     if (NULL == end)
1031     {
1032         end = inputAddress + strlen(inputAddress);
1033     }
1034     size_t inputLength = end - inputAddress;
1035
1036     const char *percent = strchr(inputAddress, '%');
1037     if (!percent || (percent > end))
1038     {
1039         OICStrcpyPartial(outputAddress, outputSize, inputAddress, inputLength);
1040     }
1041     else
1042     {
1043         if (percent[1] != '2' || percent[2] != '5')
1044         {
1045             return OC_STACK_INVALID_URI;
1046         }
1047
1048         int addrlen = percent - inputAddress + 1;
1049         OICStrcpyPartial(outputAddress, outputSize, inputAddress, addrlen);
1050         OICStrcpyPartial(outputAddress + addrlen, outputSize - addrlen,
1051                          percent + 3, end - percent - 3);
1052     }
1053
1054     return OC_STACK_OK;
1055 }
1056
1057 #ifdef WITH_PRESENCE
1058 /**
1059  * The cononical presence allows constructed URIs to be string compared.
1060  *
1061  * requestUri must be a char array of size CA_MAX_URI_LENGTH
1062  */
1063 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
1064                                     char *presenceUri, bool isMulticast)
1065 {
1066     VERIFY_NON_NULL(endpoint   , FATAL, OC_STACK_INVALID_PARAM);
1067     VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1068
1069     if (isMulticast)
1070     {
1071         OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1072         return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1073     }
1074
1075     CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1076     if (ep->adapter == CA_ADAPTER_IP)
1077     {
1078         if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1079         {
1080             if ('\0' == ep->addr[0])  // multicast
1081             {
1082                 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1083             }
1084             else
1085             {
1086                 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1087
1088                 OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1089                                                                  sizeof(addressEncoded),
1090                                                                  ep->addr);
1091
1092                 if (OC_STACK_OK != result)
1093                 {
1094                     return -1;
1095                 }
1096
1097                 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1098                         addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1099             }
1100         }
1101         else
1102         {
1103             if ('\0' == ep->addr[0])  // multicast
1104             {
1105                 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1106                 ep->port = OC_MULTICAST_PORT;
1107             }
1108             return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1109                     ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1110         }
1111     }
1112
1113     // might work for other adapters (untested, but better than nothing)
1114     return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1115                     OC_RSRVD_PRESENCE_URI);
1116 }
1117
1118
1119 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1120                             const CAResponseInfo_t *responseInfo)
1121 {
1122     VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1123     VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1124
1125     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1126     ClientCB * cbNode = NULL;
1127     char *resourceTypeName = NULL;
1128     OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1129     OCStackResult result = OC_STACK_ERROR;
1130     uint32_t maxAge = 0;
1131     int uriLen;
1132     char presenceUri[CA_MAX_URI_LENGTH];
1133
1134     int presenceSubscribe = 0;
1135     int multicastPresenceSubscribe = 0;
1136
1137     if (responseInfo->result != CA_CONTENT)
1138     {
1139         OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1140         return OC_STACK_ERROR;
1141     }
1142
1143     response.payload = NULL;
1144     response.result = OC_STACK_OK;
1145
1146     CopyEndpointToDevAddr(endpoint, &response.devAddr);
1147     FixUpClientResponse(&response);
1148
1149     if (responseInfo->info.payload)
1150     {
1151         result = OCParsePayload(&response.payload,
1152                 PAYLOAD_TYPE_PRESENCE,
1153                 responseInfo->info.payload,
1154                 responseInfo->info.payloadSize);
1155
1156         if(result != OC_STACK_OK)
1157         {
1158             OIC_LOG(ERROR, TAG, "Presence parse failed");
1159             goto exit;
1160         }
1161         if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1162         {
1163             OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1164             result = OC_STACK_ERROR;
1165             goto exit;
1166         }
1167         response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1168         resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1169         maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1170     }
1171
1172     // check for unicast presence
1173     uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1174                                       responseInfo->isMulticast);
1175     if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1176     {
1177         return OC_STACK_INVALID_URI;
1178     }
1179     OIC_LOG(INFO, TAG, "check for unicast presence");
1180     cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1181     if (cbNode)
1182     {
1183         presenceSubscribe = 1;
1184     }
1185     else
1186     {
1187         // check for multicast presence
1188         OIC_LOG(INFO, TAG, "check for multicast presence");
1189         cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1190         if (cbNode)
1191         {
1192             multicastPresenceSubscribe = 1;
1193         }
1194     }
1195
1196     if (!presenceSubscribe && !multicastPresenceSubscribe)
1197     {
1198         OIC_LOG(INFO, TAG, "Received a presence notification, "
1199                 "but need to register presence callback, ignoring");
1200         goto exit;
1201     }
1202
1203     if (presenceSubscribe)
1204     {
1205         if(cbNode->sequenceNumber == response.sequenceNumber)
1206         {
1207             OIC_LOG(INFO, TAG, "No presence change");
1208             ResetPresenceTTL(cbNode, maxAge);
1209             OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1210             goto exit;
1211         }
1212
1213         if(maxAge == 0)
1214         {
1215             OIC_LOG(INFO, TAG, "Stopping presence");
1216             response.result = OC_STACK_PRESENCE_STOPPED;
1217             if(cbNode->presence)
1218             {
1219                 OICFree(cbNode->presence->timeOut);
1220                 OICFree(cbNode->presence);
1221                 cbNode->presence = NULL;
1222             }
1223         }
1224         else
1225         {
1226             if(!cbNode->presence)
1227             {
1228                 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1229
1230                 if(!(cbNode->presence))
1231                 {
1232                     OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1233                     result = OC_STACK_NO_MEMORY;
1234                     goto exit;
1235                 }
1236
1237                 VERIFY_NON_NULL_V(cbNode->presence);
1238                 cbNode->presence->timeOut = NULL;
1239                 cbNode->presence->timeOut = (uint32_t *)
1240                         OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1241                 if(!(cbNode->presence->timeOut)){
1242                     OIC_LOG(ERROR, TAG,
1243                                   "Could not allocate memory for cbNode->presence->timeOut");
1244                     OICFree(cbNode->presence);
1245                     cbNode->presence = NULL;
1246                     result = OC_STACK_NO_MEMORY;
1247                     goto exit;
1248                 }
1249             }
1250
1251             ResetPresenceTTL(cbNode, maxAge);
1252
1253             cbNode->sequenceNumber = response.sequenceNumber;
1254         }
1255     }
1256     else
1257     {
1258         // This is the multicast case
1259         OIC_LOG(INFO, TAG, "this is the multicast presence");
1260         if (0 == maxAge)
1261         {
1262             OIC_LOG(INFO, TAG, "Stopping presence");
1263             response.result = OC_STACK_PRESENCE_STOPPED;
1264         }
1265     }
1266
1267     // Ensure that a filter is actually applied.
1268     if (resourceTypeName && cbNode->filterResourceType)
1269     {
1270         OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1271         if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1272         {
1273             goto exit;
1274         }
1275     }
1276
1277     OIC_LOG(INFO, TAG, "Before calling into application address space for presence");
1278     cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1279     OIC_LOG(INFO, TAG, "After calling into application address space for presence");
1280
1281     if (cbResult == OC_STACK_DELETE_TRANSACTION)
1282     {
1283         FindAndDeleteClientCB(cbNode);
1284     }
1285
1286 exit:
1287     OCPayloadDestroy(response.payload);
1288     return result;
1289 }
1290 #endif // WITH_PRESENCE
1291
1292 OCStackResult HandleBatchResponse(char *requestUri, OCRepPayload **payload)
1293 {
1294     if (requestUri && *payload)
1295     {
1296         char *interfaceName = NULL;
1297         char *rtTypeName = NULL;
1298         char *uriQuery = NULL;
1299         char *uriWithoutQuery = NULL;
1300         if (OC_STACK_OK == getQueryFromUri(requestUri, &uriQuery, &uriWithoutQuery))
1301         {
1302             if (OC_STACK_OK == ExtractFiltersFromQuery(uriQuery, &interfaceName, &rtTypeName))
1303             {
1304                 if (interfaceName && (0 == strcmp(OC_RSRVD_INTERFACE_BATCH, interfaceName)))
1305                 {
1306                     char *uri = (*payload)->uri;
1307                     if (uri && 0 != strcmp(uriWithoutQuery, uri))
1308                     {
1309                         OCRepPayload *newPayload = OCRepPayloadCreate();
1310                         if (newPayload)
1311                         {
1312                             OCRepPayloadSetUri(newPayload, uri);
1313                             newPayload->next = *payload;
1314                             *payload = newPayload;
1315                         }
1316                     }
1317                 }
1318             }
1319         }
1320
1321         OICFree(interfaceName);
1322         OICFree(rtTypeName);
1323         OICFree(uriQuery);
1324         OICFree(uriWithoutQuery);
1325         return OC_STACK_OK;
1326     }
1327     return OC_STACK_INVALID_PARAM;
1328 }
1329
1330 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1331 {
1332     OIC_TRACE_MARK(%s:OCHandleResponse:%s, TAG, responseInfo->info.resourceUri);
1333     OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1334
1335 #ifdef WITH_PRESENCE
1336     if(responseInfo->info.resourceUri &&
1337         strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1338     {
1339         HandlePresenceResponse(endPoint, responseInfo);
1340         return;
1341     }
1342 #endif
1343
1344     ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1345             responseInfo->info.tokenLength, NULL, NULL);
1346
1347     if(cbNode)
1348     {
1349         OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1350 #ifdef __TIZENRT__
1351         // check obs header option
1352         bool obsHeaderOpt = false;
1353         CAHeaderOption_t *options = responseInfo->info.options;
1354         for (uint8_t i = 0; i< responseInfo->info.numOptions; i++)
1355         {
1356             if (options && options[i].protocolID == CA_COAP_ID &&
1357                            options[i].optionID == COAP_OPTION_OBSERVE)
1358             {
1359                 obsHeaderOpt = true;
1360                 break;
1361             }
1362         }
1363 #endif
1364         if(responseInfo->result == CA_EMPTY)
1365         {
1366             OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1367             // We do not have a case for the client to receive a RESET
1368             if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1369             {
1370                 //This is the case of receiving an ACK on a request to a slow resource!
1371                 OIC_LOG(INFO, TAG, "This is a pure ACK");
1372                 //TODO: should we inform the client
1373                 //      app that at least the request was received at the server?
1374             }
1375         }
1376         else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1377         {
1378             OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1379
1380             OCClientResponse response =
1381                 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1382             CopyEndpointToDevAddr(endPoint, &response.devAddr);
1383             FixUpClientResponse(&response);
1384             response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1385             memcpy(response.identity.id, responseInfo->info.identity.id,
1386                                                 sizeof (response.identity.id));
1387             response.identity.id_length = responseInfo->info.identity.id_length;
1388
1389             response.result = CAResponseToOCStackResult(responseInfo->result);
1390             OIC_LOG(INFO, TAG, "Before calling into application address space for reTrans timeout");
1391             cbNode->callBack(cbNode->context,
1392                     cbNode->handle, &response);
1393             OIC_LOG(INFO, TAG, "After calling into application address space for reTrans timeout");
1394             FindAndDeleteClientCB(cbNode);
1395             OICFree((void *)response.resourceUri);
1396         }
1397 #ifdef __TIZENRT__
1398         else if ((cbNode->method == OC_REST_OBSERVE || cbNode->method == OC_REST_OBSERVE_ALL)
1399                 && (responseInfo->result == CA_CONTENT) && !obsHeaderOpt)
1400         {
1401             OCClientResponse response =
1402                 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1403             CopyEndpointToDevAddr(endPoint, &response.devAddr);
1404             FixUpClientResponse(&response);
1405             response.resourceUri =  OICStrdup(responseInfo->info.resourceUri);
1406             memcpy(response.identity.id, responseInfo->info.identity.id,
1407                                     sizeof (response.identity.id));
1408             response.identity.id_length = responseInfo->info.identity.id_length;
1409             response.result = OC_STACK_UNAUTHORIZED_REQ;
1410
1411             OIC_LOG(INFO, TAG, "Before calling into application address space for observe resp");
1412             cbNode->callBack(cbNode->context,
1413                              cbNode->handle,
1414                              &response);
1415             OIC_LOG(INFO, TAG, "After calling into application address space for observe resp");
1416
1417             FindAndDeleteClientCB(cbNode);
1418             OICFree(response.resourceUri);
1419         }
1420 #endif
1421         else
1422         {
1423             OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1424
1425             OCClientResponse response;
1426             memset(&response, 0, sizeof(OCClientResponse));
1427             response.devAddr.adapter = OC_DEFAULT_ADAPTER;
1428
1429             response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1430             CopyEndpointToDevAddr(endPoint, &response.devAddr);
1431             FixUpClientResponse(&response);
1432             response.resourceUri = OICStrdup(responseInfo->info.resourceUri);
1433             memcpy(response.identity.id, responseInfo->info.identity.id,
1434                                                 sizeof (response.identity.id));
1435             response.identity.id_length = responseInfo->info.identity.id_length;
1436
1437             response.result = CAResponseToOCStackResult(responseInfo->result);
1438
1439             if(responseInfo->info.payload &&
1440                responseInfo->info.payloadSize)
1441             {
1442                 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1443                 // check the security resource
1444                 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1445                 {
1446                     type = PAYLOAD_TYPE_SECURITY;
1447                 }
1448                 else if (cbNode->method == OC_REST_DISCOVER)
1449                 {
1450                     if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1451                                 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1452                     {
1453                         type = PAYLOAD_TYPE_DISCOVERY;
1454                     }
1455 #ifdef WITH_MQ
1456                     else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1457                     {
1458                         type = PAYLOAD_TYPE_DISCOVERY;
1459                     }
1460 #endif
1461                     else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1462                     {
1463                         type = PAYLOAD_TYPE_REPRESENTATION;
1464                     }
1465                     else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1466                     {
1467                         type = PAYLOAD_TYPE_REPRESENTATION;
1468                     }
1469
1470 #ifdef ROUTING_GATEWAY
1471                     else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1472                     {
1473                         type = PAYLOAD_TYPE_REPRESENTATION;
1474                     }
1475 #endif
1476                     else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1477                     {
1478                         type = PAYLOAD_TYPE_REPRESENTATION;
1479                     }
1480 #ifdef TCP_ADAPTER
1481                     else if (strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1482                     {
1483                         type = PAYLOAD_TYPE_REPRESENTATION;
1484                     }
1485 #endif
1486                     else
1487                     {
1488                         OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1489                                 cbNode->method, cbNode->requestUri);
1490                         OICFree((void *)response.resourceUri);
1491                         return;
1492                     }
1493                 }
1494                 else if (cbNode->method == OC_REST_GET ||
1495                          cbNode->method == OC_REST_PUT ||
1496                          cbNode->method == OC_REST_POST ||
1497                          cbNode->method == OC_REST_OBSERVE ||
1498                          cbNode->method == OC_REST_OBSERVE_ALL ||
1499                          cbNode->method == OC_REST_DELETE)
1500                 {
1501                     if (cbNode->requestUri)
1502                     {
1503                         if (0 == strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri))
1504                         {
1505                             type = PAYLOAD_TYPE_REPRESENTATION;
1506                         }
1507                         else if (0 == strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri))
1508                         {
1509                             type = PAYLOAD_TYPE_REPRESENTATION;
1510                         }
1511                         if (type == PAYLOAD_TYPE_INVALID)
1512                         {
1513                             OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1514                                     cbNode->method, cbNode->requestUri);
1515                             type = PAYLOAD_TYPE_REPRESENTATION;
1516                         }
1517                     }
1518                     else
1519                     {
1520                         OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1521                         type = PAYLOAD_TYPE_REPRESENTATION;
1522                     }
1523                 }
1524                 else
1525                 {
1526                     OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1527                             cbNode->method, cbNode->requestUri);
1528                     OICFree((void *)response.resourceUri);
1529                     return;
1530                 }
1531
1532                 // In case of error, still want application to receive the error message.
1533                 if (OCResultToSuccess(response.result) || PAYLOAD_TYPE_REPRESENTATION == type)
1534                 {
1535                     if(OC_STACK_OK != OCParsePayload(&response.payload,
1536                             type,
1537                             responseInfo->info.payload,
1538                             responseInfo->info.payloadSize))
1539                     {
1540                         OIC_LOG(ERROR, TAG, "Error converting payload");
1541                         OCPayloadDestroy(response.payload);
1542                         OICFree((void *)response.resourceUri);
1543                         return;
1544                     }
1545                 }
1546                 else
1547                 {
1548                     OICFree((void *)response.resourceUri);
1549                     response.resourceUri = OICStrdup(cbNode->requestUri);
1550                 }
1551             }
1552
1553             response.numRcvdVendorSpecificHeaderOptions = 0;
1554             if(responseInfo->info.numOptions > 0)
1555             {
1556                 int start = 0;
1557                 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1558                 if(responseInfo->info.options
1559                    && responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1560                 {
1561                     size_t i;
1562                     uint32_t observationOption;
1563                     uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1564                     for (observationOption=0, i=0;
1565                             i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1566                             i++)
1567                     {
1568                         observationOption =
1569                             (observationOption << 8) | optionData[i];
1570                     }
1571                     response.sequenceNumber = observationOption;
1572                     response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1573                     start = 1;
1574                 }
1575                 else
1576                 {
1577                     response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1578                 }
1579
1580                 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1581                 {
1582                     OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1583                     OCPayloadDestroy(response.payload);
1584                     OICFree((void *)response.resourceUri);
1585                     return;
1586                 }
1587
1588                 if (response.numRcvdVendorSpecificHeaderOptions > 0)
1589                 {
1590                     response.rcvdVendorSpecificHeaderOptions =
1591                         (OCHeaderOption *) OICCalloc(response.numRcvdVendorSpecificHeaderOptions, sizeof(OCHeaderOption));
1592                     if (NULL == response.rcvdVendorSpecificHeaderOptions)
1593                     {
1594                         OIC_LOG(ERROR, TAG, "Failed to allocate memory for vendor header options");
1595                         OCPayloadDestroy(response.payload);
1596                         OICFree((void *)response.resourceUri);
1597                         return;
1598                     }
1599
1600                     memcpy(response.rcvdVendorSpecificHeaderOptions, responseInfo->info.options + start,
1601                         response.numRcvdVendorSpecificHeaderOptions*sizeof(OCHeaderOption));
1602                 }
1603             }
1604
1605             if (cbNode->method == OC_REST_OBSERVE &&
1606                 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1607                 cbNode->sequenceNumber <=  MAX_SEQUENCE_NUMBER &&
1608                 response.sequenceNumber <= cbNode->sequenceNumber)
1609             {
1610                 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1611                                                  response.sequenceNumber);
1612             }
1613             else
1614             {
1615 #ifdef RD_CLIENT
1616                 if (cbNode->requestUri)
1617                 {
1618                     // if request uri is '/oic/rd', update ins value of resource.
1619                     char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
1620                     if (targetUri)
1621                     {
1622                         OCUpdateResourceInsWithResponse(cbNode->requestUri, &response);
1623                     }
1624                 }
1625 #endif
1626                 // set remoteID(device ID) into OCClientResponse callback parameter
1627                 if (OC_REST_DISCOVER == cbNode->method)
1628                 {
1629                     OIC_LOG(INFO, TAG, "cbNode method is OC_REST_DISCOVER");
1630                     OCDiscoveryPayload *payload = (OCDiscoveryPayload*) response.payload;
1631                     // Payload can be empty in case of error message.
1632                     if (payload && payload->sid)
1633                     {
1634                         OICStrcpy(response.devAddr.remoteId, sizeof(response.devAddr.remoteId),
1635                                   payload->sid);
1636                         OIC_LOG_V(INFO_PRIVATE, TAG, "Device ID of response : %s",
1637                                   response.devAddr.remoteId);
1638                     }
1639
1640                     if(NULL == response.resourceUri)
1641                     {
1642                         response.resourceUri = OICStrdup(cbNode->requestUri);
1643                     }
1644                 }
1645 #ifdef TCP_ADAPTER
1646                 if (cbNode->requestUri)
1647                 {
1648                     OIC_LOG_V(INFO, TAG, "cbNode requestUri is %s", cbNode->requestUri);
1649                     if (cbNode->method == OC_REST_POST &&
1650                             strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1651                     {
1652                         OCHandleKeepAliveResponse(endPoint, response.payload);
1653                     }
1654                 }
1655 #endif
1656                 if (response.payload && response.payload->type == PAYLOAD_TYPE_REPRESENTATION)
1657                 {
1658                     OIC_LOG(INFO, TAG, "Handle batch response");
1659                     HandleBatchResponse(cbNode->requestUri, (OCRepPayload **)&response.payload);
1660                 }
1661
1662                 OIC_LOG(INFO, TAG, "Before calling into application address space for handleResponse");
1663                 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1664                                                                         cbNode->handle,
1665                                                                         &response);
1666                 OIC_LOG(INFO, TAG, "After calling into application address space for handleResponse");
1667
1668                 cbNode->sequenceNumber = response.sequenceNumber;
1669
1670                 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1671                 {
1672                     FindAndDeleteClientCB(cbNode);
1673                 }
1674                 else
1675                 {
1676                     // To keep discovery callbacks active.
1677                     cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1678                                             MILLISECONDS_PER_SECOND);
1679                 }
1680             }
1681
1682             //Need to send ACK when the response is CON
1683             if(responseInfo->info.type == CA_MSG_CONFIRM)
1684             {
1685                 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1686                 {
1687                     OIC_LOG(INFO, TAG, "Received a confirmable message. Sending EMPTY");
1688                     SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1689                         CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1690                 }
1691             }
1692
1693             OICFree((void *)response.resourceUri);
1694             OCPayloadDestroy(response.payload);
1695             OICFree(response.rcvdVendorSpecificHeaderOptions);
1696         }
1697         return;
1698     }
1699
1700     ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1701             responseInfo->info.tokenLength);
1702
1703     if(observer)
1704     {
1705         OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1706         if(responseInfo->result == CA_EMPTY)
1707         {
1708             OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1709             if(responseInfo->info.type == CA_MSG_RESET)
1710             {
1711                 OIC_LOG(INFO, TAG, "This is a RESET");
1712                 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1713                         OC_OBSERVER_NOT_INTERESTED);
1714             }
1715             else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1716             {
1717                 OIC_LOG(INFO, TAG, "This is a pure ACK");
1718                 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1719                         OC_OBSERVER_STILL_INTERESTED);
1720             }
1721         }
1722         else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1723         {
1724             OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1725             OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1726                     OC_OBSERVER_FAILED_COMM);
1727         }
1728
1729         FreeObserver(observer);
1730         return;
1731     }
1732
1733     if(!cbNode && !observer)
1734     {
1735         if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1736            || myStackMode == OC_GATEWAY)
1737         {
1738             OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1739             if(responseInfo->result == CA_EMPTY)
1740             {
1741                 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1742             }
1743             else
1744             {
1745                 if (!(endPoint->adapter & CA_ADAPTER_TCP))
1746                 {
1747                     OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1748                     SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1749                                             CA_MSG_RESET, 0, NULL, NULL, 0, NULL,
1750                                             CA_RESPONSE_FOR_RES);
1751                 }
1752             }
1753         }
1754
1755         if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1756            || myStackMode == OC_GATEWAY)
1757         {
1758             OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1759             if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1760             {
1761                 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1762                                             responseInfo->info.messageId);
1763             }
1764             if (responseInfo->info.type == CA_MSG_RESET)
1765             {
1766                 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1767                                             responseInfo->info.messageId);
1768             }
1769         }
1770
1771         return;
1772     }
1773 }
1774
1775 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1776 {
1777     VERIFY_NON_NULL_NR(endPoint, FATAL);
1778     VERIFY_NON_NULL_NR(responseInfo, FATAL);
1779
1780     OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1781     OIC_TRACE_BEGIN(%s:HandleCAResponses, TAG);
1782
1783 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1784 #ifdef ROUTING_GATEWAY
1785     bool needRIHandling = false;
1786     /*
1787      * Routing manager is going to update either of endpoint or response or both.
1788      * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1789      * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1790      * destination.
1791      */
1792     OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1793                                          &needRIHandling);
1794     if(ret != OC_STACK_OK || !needRIHandling)
1795     {
1796         OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1797         OIC_TRACE_END();
1798         return;
1799     }
1800 #endif
1801
1802     /*
1803      * Put source in sender endpoint so that the next packet from application can be routed to
1804      * proper destination and remove "RM" coap header option before passing request / response to
1805      * RI as this option will make no sense to either RI or application.
1806      */
1807     RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1808                  (uint8_t *) &(responseInfo->info.numOptions),
1809                  (CAEndpoint_t *) endPoint);
1810 #endif
1811
1812     OCHandleResponse(endPoint, responseInfo);
1813     OIC_TRACE_END();
1814     OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1815 }
1816
1817 /*
1818  * This function handles error response from CA
1819  * code shall be added to handle the errors
1820  */
1821 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1822 {
1823     VERIFY_NON_NULL_NR(endPoint, FATAL);
1824     VERIFY_NON_NULL_NR(errorInfo, FATAL);
1825
1826     OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1827     OIC_TRACE_BEGIN(%s:HandleCAErrorResponse, TAG);
1828
1829     ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1830                                    errorInfo->info.tokenLength, NULL, NULL);
1831     if (cbNode)
1832     {
1833         OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1834         CopyEndpointToDevAddr(endPoint, &response.devAddr);
1835         FixUpClientResponse(&response);
1836         response.resourceUri = errorInfo->info.resourceUri;
1837         memcpy(response.identity.id, errorInfo->info.identity.id,
1838                sizeof (response.identity.id));
1839         response.identity.id_length = errorInfo->info.identity.id_length;
1840         response.result = CAResultToOCResult(errorInfo->result);
1841
1842         OIC_LOG(INFO, TAG, "Before calling into application address space for error response");
1843         cbNode->callBack(cbNode->context, cbNode->handle, &response);
1844         OIC_LOG(INFO, TAG, "After calling into application address space for error response");
1845     }
1846
1847     ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1848                                                        errorInfo->info.tokenLength);
1849     if (observer)
1850     {
1851         OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1852         OCStackResult result = CAResultToOCResult(errorInfo->result);
1853         if (OC_STACK_COMM_ERROR == result)
1854         {
1855             OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1856                             OC_OBSERVER_FAILED_COMM);
1857         }
1858     }
1859
1860     OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1861     OIC_TRACE_END();
1862 }
1863
1864 /*
1865  * This function sends out Direct Stack Responses. These are responses that are not coming
1866  * from the application entity handler. These responses have no payload and are usually ACKs,
1867  * RESETs or some error conditions that were caught by the stack.
1868  */
1869 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1870         const CAResponseResult_t responseResult, const CAMessageType_t type,
1871         const uint8_t numOptions, const CAHeaderOption_t *options,
1872         CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1873         CADataType_t dataType)
1874 {
1875     OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1876
1877     if (endPoint->flags & CA_MULTICAST)
1878     {
1879         OIC_LOG(ERROR, TAG, "It is unnecessary to respond to a multicast request");
1880         return OC_STACK_OK;
1881     }
1882
1883     CAResponseInfo_t respInfo = { .result = responseResult };
1884     respInfo.info.messageId = coapID;
1885     respInfo.info.numOptions = numOptions;
1886
1887     if (respInfo.info.numOptions)
1888     {
1889         respInfo.info.options =
1890             (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1891         memcpy (respInfo.info.options, options,
1892                 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1893
1894     }
1895
1896     respInfo.info.payload = NULL;
1897     respInfo.info.token = token;
1898     respInfo.info.tokenLength = tokenLength;
1899     respInfo.info.type = type;
1900     respInfo.info.resourceUri = OICStrdup (resourceUri);
1901     respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1902     respInfo.info.dataType = dataType;
1903
1904 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1905     // Add the destination to route option from the endpoint->routeData.
1906     bool doPost = false;
1907     OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1908     if(OC_STACK_OK != result)
1909     {
1910         OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1911         OICFree (respInfo.info.resourceUri);
1912         OICFree (respInfo.info.options);
1913         return result;
1914     }
1915     if (doPost)
1916     {
1917         OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1918         CARequestInfo_t reqInfo = {.method = CA_POST };
1919         /* The following initialization is not done in a single initializer block as in
1920          * arduino, .c file is compiled as .cpp and moves it from C99 to C++11.  The latter
1921          * does not have designated initalizers. This is a work-around for now.
1922          */
1923         reqInfo.info.type = CA_MSG_NONCONFIRM;
1924         reqInfo.info.messageId = coapID;
1925         reqInfo.info.tokenLength = tokenLength;
1926         reqInfo.info.token = token;
1927         reqInfo.info.numOptions = respInfo.info.numOptions;
1928         reqInfo.info.payload = NULL;
1929         reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1930         if (reqInfo.info.numOptions)
1931         {
1932             reqInfo.info.options =
1933                 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1934             if (NULL == reqInfo.info.options)
1935             {
1936                 OIC_LOG(ERROR, TAG, "Calloc failed");
1937                 OICFree (reqInfo.info.resourceUri);
1938                 OICFree (respInfo.info.resourceUri);
1939                 OICFree (respInfo.info.options);
1940                 return OC_STACK_NO_MEMORY;
1941             }
1942             memcpy (reqInfo.info.options, respInfo.info.options,
1943                     sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1944
1945         }
1946         CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1947         OICFree (reqInfo.info.resourceUri);
1948         OICFree (reqInfo.info.options);
1949         OICFree (respInfo.info.resourceUri);
1950         OICFree (respInfo.info.options);
1951         if (CA_STATUS_OK != caResult)
1952         {
1953             OIC_LOG(ERROR, TAG, "CASendRequest error");
1954             return CAResultToOCResult(caResult);
1955         }
1956     }
1957     else
1958 #endif
1959     {
1960         CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1961
1962         // resourceUri in the info field is cloned in the CA layer and
1963         // thus ownership is still here.
1964         OICFree (respInfo.info.resourceUri);
1965         OICFree (respInfo.info.options);
1966         if(CA_STATUS_OK != caResult)
1967         {
1968             OIC_LOG(ERROR, TAG, "CASendResponse error");
1969             return CAResultToOCResult(caResult);
1970         }
1971     }
1972     OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1973     return OC_STACK_OK;
1974 }
1975
1976 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1977 {
1978     OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1979     OCStackResult result = OC_STACK_ERROR;
1980     if(!protocolRequest)
1981     {
1982         OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1983         return OC_STACK_INVALID_PARAM;
1984     }
1985
1986     OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1987             protocolRequest->tokenLength);
1988     if(!request)
1989     {
1990         OIC_LOG(INFO, TAG, "This is a new Server Request");
1991         result = AddServerRequest(&request, protocolRequest->coapID,
1992                 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1993                 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1994                 protocolRequest->observationOption, protocolRequest->qos,
1995                 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1996                 protocolRequest->payload, protocolRequest->requestToken,
1997                 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1998                 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1999                 &protocolRequest->devAddr);
2000         if (OC_STACK_OK != result)
2001         {
2002             OIC_LOG(ERROR, TAG, "Error adding server request");
2003             return result;
2004         }
2005
2006         if(!request)
2007         {
2008             OIC_LOG(ERROR, TAG, "Out of Memory");
2009             return OC_STACK_NO_MEMORY;
2010         }
2011
2012         if(!protocolRequest->reqMorePacket)
2013         {
2014             request->requestComplete = 1;
2015         }
2016     }
2017     else
2018     {
2019         OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
2020     }
2021
2022     if(request->requestComplete)
2023     {
2024         OIC_LOG(INFO, TAG, "This Server Request is complete");
2025         ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2026         OCResource *resource = NULL;
2027         result = DetermineResourceHandling (request, &resHandling, &resource);
2028         if (result == OC_STACK_OK)
2029         {
2030             result = ProcessRequest(resHandling, resource, request);
2031         }
2032     }
2033     else
2034     {
2035         OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2036         result = OC_STACK_CONTINUE;
2037     }
2038     return result;
2039 }
2040
2041 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2042 {
2043     OIC_TRACE_MARK(%s:OCHandleRequests:%s, TAG, requestInfo->info.resourceUri);
2044     OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2045
2046     OCStackResult requestResult = OC_STACK_ERROR;
2047
2048     if(myStackMode == OC_CLIENT)
2049     {
2050         //TODO: should the client be responding to requests?
2051         return;
2052     }
2053
2054     OCServerProtocolRequest serverRequest = {0};
2055
2056     OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2057
2058     char * uriWithoutQuery = NULL;
2059     char * query  = NULL;
2060
2061     requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2062
2063     if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2064     {
2065         OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2066         return;
2067     }
2068     OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2069     OIC_LOG_V(INFO, TAG, "Query : %s", query);
2070
2071     if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2072     {
2073         OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2074         OICFree(uriWithoutQuery);
2075     }
2076     else
2077     {
2078         OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2079         OICFree(uriWithoutQuery);
2080         OICFree(query);
2081         return;
2082     }
2083
2084     if(query)
2085     {
2086         if(strlen(query) < MAX_QUERY_LENGTH)
2087         {
2088             OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2089             OICFree(query);
2090         }
2091         else
2092         {
2093             OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2094             OICFree(query);
2095             return;
2096         }
2097     }
2098
2099     if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2100     {
2101         serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2102         serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2103         if (!serverRequest.payload)
2104         {
2105             OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2106             return;
2107         }
2108         memcpy (serverRequest.payload, requestInfo->info.payload,
2109                 requestInfo->info.payloadSize);
2110     }
2111     else
2112     {
2113         serverRequest.reqTotalSize = 0;
2114     }
2115
2116     switch (requestInfo->method)
2117     {
2118         case CA_GET:
2119             serverRequest.method = OC_REST_GET;
2120             break;
2121         case CA_PUT:
2122             serverRequest.method = OC_REST_PUT;
2123             break;
2124         case CA_POST:
2125             serverRequest.method = OC_REST_POST;
2126             break;
2127         case CA_DELETE:
2128             serverRequest.method = OC_REST_DELETE;
2129             break;
2130         default:
2131             OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2132             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2133                         requestInfo->info.type, requestInfo->info.numOptions,
2134                         requestInfo->info.options, requestInfo->info.token,
2135                         requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2136                         CA_RESPONSE_DATA);
2137             OICFree(serverRequest.payload);
2138             return;
2139     }
2140
2141     OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2142             requestInfo->info.tokenLength);
2143
2144     serverRequest.tokenLength = requestInfo->info.tokenLength;
2145     if (serverRequest.tokenLength) {
2146         // Non empty token
2147         serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2148
2149         if (!serverRequest.requestToken)
2150         {
2151             OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2152             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2153                     requestInfo->info.type, requestInfo->info.numOptions,
2154                     requestInfo->info.options, requestInfo->info.token,
2155                     requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2156                     CA_RESPONSE_DATA);
2157             OICFree(serverRequest.payload);
2158             return;
2159         }
2160         memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2161     }
2162
2163     switch (requestInfo->info.acceptFormat)
2164     {
2165         case CA_FORMAT_APPLICATION_CBOR:
2166             serverRequest.acceptFormat = OC_FORMAT_CBOR;
2167             break;
2168         case CA_FORMAT_UNDEFINED:
2169             serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2170             break;
2171         default:
2172             serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2173     }
2174
2175     if (requestInfo->info.type == CA_MSG_CONFIRM)
2176     {
2177         serverRequest.qos = OC_HIGH_QOS;
2178     }
2179     else
2180     {
2181         serverRequest.qos = OC_LOW_QOS;
2182     }
2183     // CA does not need the following field
2184     // Are we sure CA does not need them? how is it responding to multicast
2185     serverRequest.delayedResNeeded = 0;
2186
2187     serverRequest.coapID = requestInfo->info.messageId;
2188
2189     CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2190
2191     // copy vendor specific header options
2192     uint8_t tempNum = (requestInfo->info.numOptions);
2193
2194     // Assume no observation requested and it is a pure GET.
2195     // If obs registration/de-registration requested it'll be fetched from the
2196     // options in GetObserveHeaderOption()
2197     serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2198
2199     GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2200     if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2201     {
2202         OIC_LOG(ERROR, TAG,
2203                 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2204         SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2205                 requestInfo->info.type, requestInfo->info.numOptions,
2206                 requestInfo->info.options, requestInfo->info.token,
2207                 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2208                 CA_RESPONSE_DATA);
2209         OICFree(serverRequest.payload);
2210         OICFree(serverRequest.requestToken);
2211         return;
2212     }
2213
2214     serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2215     if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2216     {
2217         serverRequest.rcvdVendorSpecificHeaderOptions = (OCHeaderOption*) OICCalloc(tempNum, sizeof(OCHeaderOption));
2218         if (NULL == serverRequest.rcvdVendorSpecificHeaderOptions)
2219         {
2220             OIC_LOG(ERROR, TAG, "Failed to allocated memory to vnd header options!");
2221             OICFree(serverRequest.payload);
2222             OICFree(serverRequest.requestToken);
2223             return;
2224         }
2225
2226         memcpy (serverRequest.rcvdVendorSpecificHeaderOptions, requestInfo->info.options,
2227             sizeof(CAHeaderOption_t)*tempNum);
2228     }
2229
2230     requestResult = HandleStackRequests (&serverRequest);
2231
2232     // Send ACK to client as precursor to slow response
2233     if (requestResult == OC_STACK_SLOW_RESOURCE)
2234     {
2235         if (requestInfo->info.type == CA_MSG_CONFIRM)
2236         {
2237             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2238                                     CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2239                                     CA_RESPONSE_DATA);
2240         }
2241     }
2242 #ifndef __TIZENRT__
2243     if (requestResult == OC_STACK_RESOURCE_ERROR
2244             && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2245     {
2246         OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2247     }
2248 #else
2249     if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2250     {
2251         if (requestResult == OC_STACK_RESOURCE_ERROR)
2252         {
2253             OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2254         }
2255         else if (!OCResultToSuccess(requestResult))
2256         {
2257             DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2258         }
2259     }
2260 #endif
2261     else if(!OCResultToSuccess(requestResult))
2262     {
2263         OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2264
2265         // Delete observer node if it is OBSERVE failure from app
2266         if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2267         {
2268             DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2269         }
2270
2271         CAResponseResult_t stackResponse =
2272             OCToCAStackResult(requestResult, serverRequest.method);
2273
2274         SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2275                 requestInfo->info.type, requestInfo->info.numOptions,
2276                 requestInfo->info.options, requestInfo->info.token,
2277                 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2278                 CA_RESPONSE_DATA);
2279     }
2280     // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2281     // The token is copied in there, and is thus still owned by this function.
2282     OICFree(serverRequest.payload);
2283     OICFree(serverRequest.requestToken);
2284     OICFree(serverRequest.rcvdVendorSpecificHeaderOptions);
2285     OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2286 }
2287
2288 //This function will be called back by CA layer when a request is received
2289 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2290 {
2291     OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2292     OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2293     if(!endPoint)
2294     {
2295         OIC_LOG(ERROR, TAG, "endPoint is NULL");
2296         OIC_TRACE_END();
2297         return;
2298     }
2299
2300     if(!requestInfo)
2301     {
2302         OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2303         OIC_TRACE_END();
2304         return;
2305     }
2306
2307 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2308 #ifdef ROUTING_GATEWAY
2309     bool needRIHandling = false;
2310     bool isEmptyMsg = false;
2311     /*
2312      * Routing manager is going to update either of endpoint or request or both.
2313      * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2314      * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2315      * destination. It can also remove "RM" coap header option before passing request / response to
2316      * RI as this option will make no sense to either RI or application.
2317      */
2318     OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2319                                         &needRIHandling, &isEmptyMsg);
2320     if(OC_STACK_OK != ret || !needRIHandling)
2321     {
2322         OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2323         OIC_TRACE_END();
2324         return;
2325     }
2326 #endif
2327
2328     /*
2329      * Put source in sender endpoint so that the next packet from application can be routed to
2330      * proper destination and remove RM header option.
2331      */
2332     RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2333                  (uint8_t *) &(requestInfo->info.numOptions),
2334                  (CAEndpoint_t *) endPoint);
2335
2336 #ifdef ROUTING_GATEWAY
2337     if (isEmptyMsg)
2338     {
2339         /*
2340          * In Gateways, the MSGType in route option is used to check if the actual
2341          * response is EMPTY message(4 bytes CoAP Header).  In case of Client, the
2342          * EMPTY response is sent in the form of POST request which need to be changed
2343          * to a EMPTY response by RM.  This translation is done in this part of the code.
2344          */
2345         OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2346         CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2347                                      .info.messageId = requestInfo->info.messageId,
2348                                      .info.type = CA_MSG_ACKNOWLEDGE};
2349         OCHandleResponse(endPoint, &respInfo);
2350     }
2351     else
2352 #endif
2353 #endif
2354     {
2355         // Normal handling of the packet
2356         OCHandleRequests(endPoint, requestInfo);
2357     }
2358     OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2359     OIC_TRACE_END();
2360 }
2361
2362 //-----------------------------------------------------------------------------
2363 // Public APIs
2364 //-----------------------------------------------------------------------------
2365 #ifdef RA_ADAPTER
2366 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2367 {
2368     if (!raInfo           ||
2369         !raInfo->username ||
2370         !raInfo->hostname ||
2371         !raInfo->xmpp_domain)
2372     {
2373
2374         return OC_STACK_INVALID_PARAM;
2375     }
2376     OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2377     gRASetInfo = (result == OC_STACK_OK)? true : false;
2378
2379     return result;
2380 }
2381 #endif
2382
2383 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2384 {
2385     (void) ipAddr;
2386     (void) port;
2387     return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2388 }
2389
2390 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2391 {
2392     OC_UNUSED(serverFlags);
2393     OC_UNUSED(clientFlags);
2394
2395     OIC_LOG(DEBUG, TAG, "call OCInit1");
2396     return OCInit2(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS, OC_DEFAULT_ADAPTER);
2397 }
2398
2399 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2400                       OCTransportAdapter transportType)
2401 {
2402     if(stackState == OC_STACK_INITIALIZED)
2403     {
2404         OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2405                 OCStop() between them are ignored.");
2406         return OC_STACK_OK;
2407     }
2408
2409 #ifndef ROUTING_GATEWAY
2410     if (OC_GATEWAY == mode)
2411     {
2412         OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2413         return OC_STACK_INVALID_PARAM;
2414     }
2415 #endif
2416
2417 #ifdef RA_ADAPTER
2418     if(!gRASetInfo)
2419     {
2420         OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2421         return OC_STACK_ERROR;
2422     }
2423 #endif
2424
2425     OCStackResult result = OC_STACK_ERROR;
2426     OIC_LOG(INFO, TAG, "Entering OCInit");
2427
2428     // Validate mode
2429     if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2430         || (mode == OC_GATEWAY)))
2431     {
2432         OIC_LOG(ERROR, TAG, "Invalid mode");
2433         return OC_STACK_ERROR;
2434     }
2435     myStackMode = mode;
2436
2437     if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2438     {
2439         caglobals.client = true;
2440     }
2441     if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2442     {
2443         caglobals.server = true;
2444     }
2445
2446     caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2447     if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2448     {
2449         caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2450     }
2451     caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2452     if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2453     {
2454         caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2455     }
2456
2457     defaultDeviceHandler = NULL;
2458     defaultDeviceHandlerCallbackParameter = NULL;
2459
2460     result = InitializeScheduleResourceList();
2461     VERIFY_SUCCESS(result, OC_STACK_OK);
2462
2463     result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2464     VERIFY_SUCCESS(result, OC_STACK_OK);
2465
2466     result = CAResultToOCResult(OCSelectNetwork(transportType));
2467     VERIFY_SUCCESS(result, OC_STACK_OK);
2468
2469     result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2470       OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2471     VERIFY_SUCCESS(result, OC_STACK_OK);
2472
2473     switch (myStackMode)
2474     {
2475         case OC_CLIENT:
2476             CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2477             result = CAResultToOCResult(CAStartDiscoveryServer());
2478             OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2479             break;
2480         case OC_SERVER:
2481             SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2482             result = CAResultToOCResult(CAStartListeningServer());
2483             OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2484             break;
2485         case OC_CLIENT_SERVER:
2486         case OC_GATEWAY:
2487             SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2488             result = CAResultToOCResult(CAStartListeningServer());
2489             if(result == OC_STACK_OK)
2490             {
2491                 result = CAResultToOCResult(CAStartDiscoveryServer());
2492             }
2493             break;
2494     }
2495     VERIFY_SUCCESS(result, OC_STACK_OK);
2496
2497 #ifdef TCP_ADAPTER
2498     CARegisterKeepAliveHandler(OCHandleKeepAliveConnCB);
2499 #endif
2500
2501 #ifdef WITH_PRESENCE
2502     PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2503 #endif // WITH_PRESENCE
2504
2505     //Update Stack state to initialized
2506     stackState = OC_STACK_INITIALIZED;
2507
2508     // Initialize resource
2509     if(myStackMode != OC_CLIENT)
2510     {
2511         result = initResources();
2512     }
2513
2514     // Initialize the SRM Policy Engine
2515     if(result == OC_STACK_OK)
2516     {
2517         result = SRMInitPolicyEngine();
2518         // TODO after BeachHead delivery: consolidate into single SRMInit()
2519     }
2520 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2521     RMSetStackMode(mode);
2522 #ifdef ROUTING_GATEWAY
2523     if (OC_GATEWAY == myStackMode)
2524     {
2525         result = RMInitialize();
2526     }
2527 #endif
2528 #endif
2529
2530 #ifdef TCP_ADAPTER
2531     if (result == OC_STACK_OK)
2532     {
2533         result = OCInitializeKeepAlive(myStackMode);
2534     }
2535 #endif
2536
2537     InitializeObserverList();
2538
2539 exit:
2540     if(result != OC_STACK_OK)
2541     {
2542         OIC_LOG(ERROR, TAG, "Stack initialization error");
2543         TerminateScheduleResourceList();
2544         deleteAllResources();
2545         CATerminate();
2546         stackState = OC_STACK_UNINITIALIZED;
2547     }
2548     return result;
2549 }
2550
2551 OCStackResult OCStop()
2552 {
2553     OIC_LOG(INFO, TAG, "Entering OCStop");
2554
2555     if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2556     {
2557         OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2558         return OC_STACK_OK;
2559     }
2560     else if (stackState != OC_STACK_INITIALIZED)
2561     {
2562         OIC_LOG(INFO, TAG, "Stack not initialized");
2563         return OC_STACK_ERROR;
2564     }
2565
2566     // unset cautil config
2567     CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2568     CAUtilSetBTConfigure(configs);
2569
2570     stackState = OC_STACK_UNINIT_IN_PROGRESS;
2571
2572     CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2573                                       OCDefaultConnectionStateChangedHandler);
2574
2575 #ifdef WITH_PRESENCE
2576     // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2577     // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2578     presenceResource.presenceTTL = 0;
2579     presenceState = OC_PRESENCE_UNINITIALIZED;
2580 #endif // WITH_PRESENCE
2581
2582 #ifdef ROUTING_GATEWAY
2583     if (OC_GATEWAY == myStackMode)
2584     {
2585         RMTerminate();
2586     }
2587 #endif
2588
2589 #ifdef TCP_ADAPTER
2590     OCTerminateKeepAlive(myStackMode);
2591 #endif
2592
2593     TerminateScheduleResourceList();
2594     // Remove all observers
2595     DeleteObserverList();
2596     // Free memory dynamically allocated for resources
2597     deleteAllResources();
2598     // Remove all the client callbacks
2599     DeleteClientCBList();
2600     // Terminate connectivity-abstraction layer.
2601     CATerminate();
2602
2603     // De-init the SRM Policy Engine
2604     // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2605     SRMDeInitPolicyEngine();
2606
2607     // Destroy Observer List Mutex
2608     TerminateObserverList();
2609
2610     stackState = OC_STACK_UNINITIALIZED;
2611     return OC_STACK_OK;
2612 }
2613
2614 OCStackResult OCStartMulticastServer()
2615 {
2616     if(stackState != OC_STACK_INITIALIZED)
2617     {
2618         OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2619         return OC_STACK_ERROR;
2620     }
2621     CAResult_t ret = CAStartListeningServer();
2622     if (CA_STATUS_OK != ret)
2623     {
2624         OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2625         return OC_STACK_ERROR;
2626     }
2627     return OC_STACK_OK;
2628 }
2629
2630 OCStackResult OCStopMulticastServer()
2631 {
2632     CAResult_t ret = CAStopListeningServer();
2633     if (CA_STATUS_OK != ret)
2634     {
2635         OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2636         return OC_STACK_ERROR;
2637     }
2638     return OC_STACK_OK;
2639 }
2640
2641 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2642 {
2643     switch (qos)
2644     {
2645         case OC_HIGH_QOS:
2646             return CA_MSG_CONFIRM;
2647         case OC_LOW_QOS:
2648         case OC_MEDIUM_QOS:
2649         case OC_NA_QOS:
2650         default:
2651             return CA_MSG_NONCONFIRM;
2652     }
2653 }
2654
2655 OCStackResult ParseRequestUri(const char *fullUri,
2656                               OCTransportAdapter adapter,
2657                               OCTransportFlags flags,
2658                               OCDevAddr **devAddr,
2659                               char **resourceUri,
2660                               char **resourceType)
2661 {
2662     VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2663
2664     OCStackResult result = OC_STACK_OK;
2665     OCDevAddr *da = NULL;
2666     char *colon = NULL;
2667     char *end;
2668
2669     // provide defaults for all returned values
2670     if (devAddr)
2671     {
2672         *devAddr = NULL;
2673     }
2674     if (resourceUri)
2675     {
2676         *resourceUri = NULL;
2677     }
2678     if (resourceType)
2679     {
2680         *resourceType = NULL;
2681     }
2682
2683     // delimit url prefix, if any
2684     const char *start = fullUri;
2685     char *slash2 = strstr(start, "//");
2686     if (slash2)
2687     {
2688         start = slash2 + 2;
2689     }
2690     char *slash = strchr(start, '/');
2691     if (!slash)
2692     {
2693         return OC_STACK_INVALID_URI;
2694     }
2695
2696     // process url scheme
2697     size_t prefixLen = slash2 - fullUri;
2698     bool istcp = false;
2699     if (prefixLen)
2700     {
2701         if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2702         || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2703         {
2704             istcp = true;
2705         }
2706     }
2707
2708     // TODO: this logic should come in with unit tests exercising the various strings
2709     // processs url prefix, if any
2710     size_t urlLen = slash - start;
2711     // port
2712     uint16_t port = 0;
2713     size_t len = 0;
2714     if (urlLen && devAddr)
2715     {   // construct OCDevAddr
2716         if (start[0] == '[')
2717         {   // ipv6 address
2718             char *close = strchr(++start, ']');
2719             if (!close || close > slash)
2720             {
2721                 return OC_STACK_INVALID_URI;
2722             }
2723             end = close;
2724             if (close[1] == ':')
2725             {
2726                 colon = close + 1;
2727             }
2728
2729             if (istcp)
2730             {
2731                 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2732             }
2733             else
2734             {
2735                 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2736             }
2737             flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2738         }
2739         else
2740         {
2741             char *dot = strchr(start, '.');
2742             if (dot && dot < slash)
2743             {   // ipv4 address
2744                 colon = strchr(start, ':');
2745                 end = (colon && colon < slash) ? colon : slash;
2746
2747                 if (istcp)
2748                 {
2749                     // coap over tcp
2750                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2751                 }
2752                 else
2753                 {
2754                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2755                 }
2756                 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2757             }
2758             else
2759             {   // MAC address
2760                 end = slash;
2761             }
2762         }
2763         len = end - start;
2764         if (len >= sizeof(da->addr))
2765         {
2766             return OC_STACK_INVALID_URI;
2767         }
2768         // collect port, if any
2769         if (colon && colon < slash)
2770         {
2771             for (colon++; colon < slash; colon++)
2772             {
2773                 char c = colon[0];
2774                 if (c < '0' || c > '9')
2775                 {
2776                     return OC_STACK_INVALID_URI;
2777                 }
2778                 port = 10 * port + c - '0';
2779             }
2780         }
2781
2782         len = end - start;
2783         if (len >= sizeof(da->addr))
2784         {
2785             return OC_STACK_INVALID_URI;
2786         }
2787
2788         da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2789         if (!da)
2790         {
2791             return OC_STACK_NO_MEMORY;
2792         }
2793
2794         // Decode address per RFC 6874.
2795         result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2796         if (result != OC_STACK_OK)
2797         {
2798              OICFree(*devAddr);
2799              return result;
2800         }
2801
2802         da->port = port;
2803         da->adapter = adapter;
2804         da->flags = flags;
2805         if (!strncmp(fullUri, "coaps", 5))
2806         {
2807             da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2808         }
2809         *devAddr = da;
2810     }
2811
2812     // process resource uri, if any
2813     if (slash)
2814     {   // request uri and query
2815         size_t ulen = strlen(slash); // resource uri length
2816         size_t tlen = 0;      // resource type length
2817         char *type = NULL;
2818
2819         static const char strPresence[] = "/oic/ad?rt=";
2820         static const size_t lenPresence = sizeof(strPresence) - 1;
2821         if (!strncmp(slash, strPresence, lenPresence))
2822         {
2823             type = slash + lenPresence;
2824             tlen = ulen - lenPresence;
2825         }
2826         // resource uri
2827         if (resourceUri)
2828         {
2829             *resourceUri = (char *)OICMalloc(ulen + 1);
2830             if (!*resourceUri)
2831             {
2832                 result = OC_STACK_NO_MEMORY;
2833                 goto error;
2834             }
2835             OICStrcpy(*resourceUri, (ulen + 1), slash);
2836         }
2837         // resource type
2838         if (type && resourceType)
2839         {
2840             *resourceType = (char *)OICMalloc(tlen + 1);
2841             if (!*resourceType)
2842             {
2843                 result = OC_STACK_NO_MEMORY;
2844                 goto error;
2845             }
2846
2847             OICStrcpy(*resourceType, (tlen+1), type);
2848         }
2849     }
2850
2851     return OC_STACK_OK;
2852
2853 error:
2854     // free all returned values
2855     if (devAddr)
2856     {
2857         OICFree(*devAddr);
2858     }
2859     if (resourceUri)
2860     {
2861         OICFree(*resourceUri);
2862     }
2863     if (resourceType)
2864     {
2865         OICFree(*resourceType);
2866     }
2867     return result;
2868 }
2869
2870 #ifdef WITH_PRESENCE
2871 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2872                                        char **requestUri,
2873                                        bool isMulticast)
2874 {
2875     char uri[CA_MAX_URI_LENGTH];
2876
2877     FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2878
2879     *requestUri = OICStrdup(uri);
2880     if (!*requestUri)
2881     {
2882         return OC_STACK_NO_MEMORY;
2883     }
2884
2885     return OC_STACK_OK;
2886 }
2887 #endif // WITH_PRESENCE
2888
2889 /**
2890  * Discover or Perform requests on a specified resource
2891  */
2892 OCStackResult OCDoResource(OCDoHandle *handle,
2893                             OCMethod method,
2894                             const char *requestUri,
2895                             const OCDevAddr *destination,
2896                             OCPayload* payload,
2897                             OCConnectivityType connectivityType,
2898                             OCQualityOfService qos,
2899                             OCCallbackData *cbData,
2900                             OCHeaderOption *options,
2901                             uint8_t numOptions)
2902 {
2903     OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
2904                 connectivityType, qos, cbData, options, numOptions);
2905
2906     // This is the owner of the payload object, so we free it
2907     OCPayloadDestroy(payload);
2908     return ret;
2909 }
2910
2911 /**
2912  * Discover or Perform requests on a specified resource
2913  */
2914 OCStackResult OCDoRequest(OCDoHandle *handle,
2915                             OCMethod method,
2916                             const char *requestUri,
2917                             const OCDevAddr *destination,
2918                             OCPayload* payload,
2919                             OCConnectivityType connectivityType,
2920                             OCQualityOfService qos,
2921                             OCCallbackData *cbData,
2922                             OCHeaderOption *options,
2923                             uint8_t numOptions)
2924 {
2925     OIC_LOG(INFO, TAG, "Entering OCDoResource");
2926     OIC_TRACE_BEGIN(%s:OCDoRequest, TAG);
2927
2928     // Validate input parameters
2929     VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2930     VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2931
2932     OCStackResult result = OC_STACK_ERROR;
2933     CAResult_t caResult;
2934     CAToken_t token = NULL;
2935     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2936     ClientCB *clientCB = NULL;
2937     OCDoHandle resHandle = NULL;
2938     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2939     OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2940     uint32_t ttl = 0;
2941     OCTransportAdapter adapter;
2942     OCTransportFlags flags;
2943     // the request contents are put here
2944     CARequestInfo_t requestInfo = {.method = CA_GET};
2945     // requestUri  will be parsed into the following three variables
2946     OCDevAddr *devAddr = NULL;
2947     char *resourceUri = NULL;
2948     char *resourceType = NULL;
2949
2950     /*
2951      * Support original behavior with address on resourceUri argument.
2952      */
2953     adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2954     flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2955
2956     if (requestUri)
2957     {
2958         result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2959         if (result != OC_STACK_OK)
2960         {
2961             OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2962             goto exit;
2963         }
2964     }
2965     else if (!checkProxyUri(options, numOptions))
2966     {
2967         OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2968         goto exit;
2969     }
2970
2971     switch (method)
2972     {
2973     case OC_REST_GET:
2974     case OC_REST_OBSERVE:
2975     case OC_REST_OBSERVE_ALL:
2976         requestInfo.method = CA_GET;
2977         break;
2978     case OC_REST_PUT:
2979         requestInfo.method = CA_PUT;
2980         break;
2981     case OC_REST_POST:
2982         requestInfo.method = CA_POST;
2983         break;
2984     case OC_REST_DELETE:
2985         requestInfo.method = CA_DELETE;
2986         break;
2987     case OC_REST_DISCOVER:
2988 #ifdef WITH_PRESENCE
2989     case OC_REST_PRESENCE:
2990 #endif
2991         if (destination || devAddr)
2992         {
2993             requestInfo.isMulticast = false;
2994         }
2995         else
2996         {
2997             tmpDevAddr.adapter = adapter;
2998             tmpDevAddr.flags = flags;
2999             destination = &tmpDevAddr;
3000             requestInfo.isMulticast = true;
3001             qos = OC_LOW_QOS;
3002         }
3003         // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
3004         // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
3005         //                   replacing method type with GET.
3006         requestInfo.method = CA_GET;
3007         break;
3008     default:
3009         result = OC_STACK_INVALID_METHOD;
3010         goto exit;
3011     }
3012
3013     if (!devAddr && !destination)
3014     {
3015         OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
3016         result = OC_STACK_INVALID_PARAM;
3017         goto exit;
3018     }
3019
3020     /* If not original behavior, use destination argument */
3021     if (destination && !devAddr)
3022     {
3023         devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
3024         if (!devAddr)
3025         {
3026             result = OC_STACK_NO_MEMORY;
3027             goto exit;
3028         }
3029         OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
3030         *devAddr = *destination;
3031     }
3032
3033     if (devAddr)
3034     {
3035         OIC_LOG_V(INFO_PRIVATE, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
3036         if (!requestInfo.isMulticast)
3037         {
3038             OIC_LOG_V(DEBUG, TAG, "remoteAddr of devAddr : [%s]:[%d]",
3039                       devAddr->addr, devAddr->port);
3040         }
3041     }
3042
3043     resHandle = GenerateInvocationHandle();
3044     if (!resHandle)
3045     {
3046         result = OC_STACK_NO_MEMORY;
3047         goto exit;
3048     }
3049
3050     caResult = CAGenerateToken(&token, tokenLength);
3051     if (caResult != CA_STATUS_OK)
3052     {
3053         OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3054         result= OC_STACK_ERROR;
3055         goto exit;
3056     }
3057
3058     // fill in request data
3059     requestInfo.info.type = qualityOfServiceToMessageType(qos);
3060     requestInfo.info.token = token;
3061     requestInfo.info.tokenLength = tokenLength;
3062
3063     if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3064     {
3065         result = CreateObserveHeaderOption (&(requestInfo.info.options),
3066                                     options, numOptions, OC_OBSERVE_REGISTER);
3067         if (result != OC_STACK_OK)
3068         {
3069             goto exit;
3070         }
3071         requestInfo.info.numOptions = numOptions + 1;
3072     }
3073     else
3074     {
3075         requestInfo.info.numOptions = numOptions;
3076         requestInfo.info.options =
3077             (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3078         memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3079                numOptions * sizeof(CAHeaderOption_t));
3080     }
3081
3082     CopyDevAddrToEndpoint(devAddr, &endpoint);
3083
3084     if(payload)
3085     {
3086         if((result =
3087             OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3088                 != OC_STACK_OK)
3089         {
3090             OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3091             goto exit;
3092         }
3093         requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3094     }
3095     else
3096     {
3097         requestInfo.info.payload = NULL;
3098         requestInfo.info.payloadSize = 0;
3099         requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3100     }
3101
3102     // prepare for response
3103 #ifdef WITH_PRESENCE
3104     if (method == OC_REST_PRESENCE)
3105     {
3106         char *presenceUri = NULL;
3107         result = OCPreparePresence(&endpoint, &presenceUri,
3108                                    requestInfo.isMulticast);
3109         if (OC_STACK_OK != result)
3110         {
3111             goto exit;
3112         }
3113
3114         // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3115         // Presence notification will form a canonical uri to
3116         // look for callbacks into the application.
3117         if (resourceUri)
3118         {
3119             OICFree(resourceUri);
3120         }
3121         resourceUri = presenceUri;
3122     }
3123 #endif
3124
3125     // update resourceUri onto requestInfo after check presence uri
3126     requestInfo.info.resourceUri = resourceUri;
3127
3128     ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3129     result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3130                             method, devAddr, resourceUri, resourceType, ttl);
3131     if (OC_STACK_OK != result)
3132     {
3133         goto exit;
3134     }
3135
3136     cbData = NULL;        // Client CB list entry now owns it
3137     token = NULL;         // Client CB list entry now owns it
3138     devAddr = NULL;       // Client CB list entry now owns it
3139     resourceUri = NULL;   // Client CB list entry now owns it
3140     resourceType = NULL;  // Client CB list entry now owns it
3141
3142 #ifdef WITH_PRESENCE
3143     if (method == OC_REST_PRESENCE)
3144     {
3145         OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3146
3147         if (handle)
3148         {
3149             *handle = resHandle;
3150         }
3151
3152         goto exit;
3153     }
3154 #endif
3155
3156     // send request
3157     result = OCSendRequest(&endpoint, &requestInfo);
3158     if (OC_STACK_OK != result)
3159     {
3160         goto exit;
3161     }
3162
3163     if (handle)
3164     {
3165         *handle = resHandle;
3166     }
3167
3168 exit:
3169     if (result != OC_STACK_OK)
3170     {
3171         OIC_LOG(ERROR, TAG, "OCDoResource error");
3172         if (NULL != cbData && NULL != cbData->cd)
3173         {
3174             cbData->cd(cbData->context);
3175         }
3176         FindAndDeleteClientCB(clientCB);
3177         CADestroyToken(token);
3178         if (handle)
3179         {
3180             *handle = NULL;
3181         }
3182         OICFree(resHandle);
3183     }
3184
3185     OICFree(requestInfo.info.payload);
3186     OICFree(devAddr);
3187     OICFree(resourceUri);
3188     OICFree(resourceType);
3189     OICFree(requestInfo.info.options);
3190     OIC_TRACE_END();
3191     return result;
3192 }
3193
3194 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3195         uint8_t numOptions)
3196 {
3197     /*
3198      * This ftn is implemented one of two ways in the case of observation:
3199      *
3200      * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3201      *      Remove the callback associated on client side.
3202      *      When the next notification comes in from server,
3203      *      reply with RESET message to server.
3204      *      Keep in mind that the server will react to RESET only
3205      *      if the last notification was sent as CON
3206      *
3207      * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3208      *      and it is associated with an observe request
3209      *      (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3210      *      Send CON Observe request to server with
3211      *      observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3212      *      Remove the callback associated on client side.
3213      */
3214     OCStackResult ret = OC_STACK_OK;
3215     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3216     CARequestInfo_t requestInfo = {.method = CA_GET};
3217
3218     if(!handle)
3219     {
3220         return OC_STACK_INVALID_PARAM;
3221     }
3222
3223     ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3224     if (!clientCB)
3225     {
3226         OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3227         return OC_STACK_ERROR;
3228     }
3229
3230     switch (clientCB->method)
3231     {
3232         case OC_REST_OBSERVE:
3233         case OC_REST_OBSERVE_ALL:
3234
3235             OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3236
3237             CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3238
3239             if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
3240             {
3241                 FindAndDeleteClientCB(clientCB);
3242                 break;
3243             }
3244
3245             OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3246
3247             requestInfo.info.type = qualityOfServiceToMessageType(qos);
3248             requestInfo.info.token = clientCB->token;
3249             requestInfo.info.tokenLength = clientCB->tokenLength;
3250
3251             if (CreateObserveHeaderOption (&(requestInfo.info.options),
3252                     options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3253             {
3254                 return OC_STACK_ERROR;
3255             }
3256             requestInfo.info.numOptions = numOptions + 1;
3257             requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3258
3259
3260             ret = OCSendRequest(&endpoint, &requestInfo);
3261
3262             if (requestInfo.info.options)
3263             {
3264                 OICFree (requestInfo.info.options);
3265             }
3266             if (requestInfo.info.resourceUri)
3267             {
3268                 OICFree (requestInfo.info.resourceUri);
3269             }
3270
3271             break;
3272
3273         case OC_REST_DISCOVER:
3274             OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3275                                            clientCB->requestUri);
3276             FindAndDeleteClientCB(clientCB);
3277             break;
3278
3279 #ifdef WITH_PRESENCE
3280         case OC_REST_PRESENCE:
3281             FindAndDeleteClientCB(clientCB);
3282             break;
3283 #endif
3284         case OC_REST_GET:
3285         case OC_REST_PUT:
3286         case OC_REST_POST:
3287         case OC_REST_DELETE:
3288             OIC_LOG_V(INFO, TAG, "Cancelling request callback for resource %s",
3289                                            clientCB->requestUri);
3290             FindAndDeleteClientCB(clientCB);
3291             break;
3292
3293         default:
3294             ret = OC_STACK_INVALID_METHOD;
3295             break;
3296     }
3297
3298     return ret;
3299 }
3300
3301 /**
3302  * @brief   Register Persistent storage callback.
3303  * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3304  * @return
3305  *     OC_STACK_OK    - No errors; Success
3306  *     OC_STACK_INVALID_PARAM - Invalid parameter
3307  */
3308 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3309 {
3310     OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3311     if(!persistentStorageHandler)
3312     {
3313         OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3314         return OC_STACK_INVALID_PARAM;
3315     }
3316     else
3317     {
3318         if( !persistentStorageHandler->open ||
3319                 !persistentStorageHandler->close ||
3320                 !persistentStorageHandler->read ||
3321                 !persistentStorageHandler->unlink ||
3322                 !persistentStorageHandler->write)
3323         {
3324             OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3325             return OC_STACK_INVALID_PARAM;
3326         }
3327     }
3328     return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3329 }
3330
3331 #ifdef WITH_PRESENCE
3332
3333 OCStackResult OCProcessPresence()
3334 {
3335     OCStackResult result = OC_STACK_OK;
3336
3337     // the following line floods the log with messages that are irrelevant
3338     // to most purposes.  Uncomment as needed.
3339     //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3340     ClientCB* cbNode = NULL;
3341     ClientCB* tempcbNode = NULL;
3342     OCClientResponse clientResponse;
3343     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3344
3345     LL_FOREACH_SAFE(cbList, cbNode, tempcbNode)
3346     {
3347         if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3348         {
3349             continue;
3350         }
3351
3352         uint32_t now = GetTicks(0);
3353         OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3354                                                 cbNode->presence->TTLlevel);
3355         OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3356
3357         if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3358         {
3359             goto exit;
3360         }
3361
3362         if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3363         {
3364             OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3365                     cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3366         }
3367         if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3368         {
3369             OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3370
3371             clientResponse.sequenceNumber = 0;
3372             clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3373             clientResponse.devAddr = *cbNode->devAddr;
3374             FixUpClientResponse(&clientResponse);
3375             clientResponse.payload = NULL;
3376
3377             // Increment the TTLLevel (going to a next state), so we don't keep
3378             // sending presence notification to client.
3379             cbNode->presence->TTLlevel++;
3380             OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3381                                         cbNode->presence->TTLlevel);
3382
3383             OIC_LOG(INFO, TAG, "Before calling into application address space for presence timeout");
3384             cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3385             OIC_LOG(INFO, TAG, "After calling into application address space for presence timeout");
3386
3387             if (cbResult == OC_STACK_DELETE_TRANSACTION)
3388             {
3389                 FindAndDeleteClientCB(cbNode);
3390             }
3391             continue;
3392         }
3393
3394         if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3395         {
3396             continue;
3397         }
3398
3399         CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3400         CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3401         CARequestInfo_t requestInfo = {.method = CA_GET};
3402
3403         OIC_LOG(DEBUG, TAG, "time to test server presence");
3404
3405         CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3406
3407         requestData.type = CA_MSG_NONCONFIRM;
3408         requestData.token = cbNode->token;
3409         requestData.tokenLength = cbNode->tokenLength;
3410         requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3411         requestInfo.method = CA_GET;
3412         requestInfo.info = requestData;
3413
3414         result = OCSendRequest(&endpoint, &requestInfo);
3415         if (OC_STACK_OK != result)
3416         {
3417             goto exit;
3418         }
3419
3420         cbNode->presence->TTLlevel++;
3421         OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3422     }
3423 exit:
3424     if (result != OC_STACK_OK)
3425     {
3426         OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3427     }
3428
3429     return result;
3430 }
3431 #endif // WITH_PRESENCE
3432
3433 OCStackResult OCProcess()
3434 {
3435     if (stackState == OC_STACK_UNINITIALIZED)
3436     {
3437         OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3438         return OC_STACK_ERROR;
3439     }
3440 #ifdef WITH_PRESENCE
3441     OCProcessPresence();
3442 #endif
3443     CAHandleRequestResponse();
3444
3445 #ifdef ROUTING_GATEWAY
3446     RMProcess();
3447 #endif
3448
3449 #ifdef TCP_ADAPTER
3450     OCProcessKeepAlive();
3451 #endif
3452     return OC_STACK_OK;
3453 }
3454
3455 #ifdef WITH_PRESENCE
3456 OCStackResult OCStartPresence(const uint32_t ttl)
3457 {
3458     OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3459     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3460     OCChangeResourceProperty(
3461             &(((OCResource *)presenceResource.handle)->resourceProperties),
3462             OC_ACTIVE, 1);
3463
3464     if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3465     {
3466         presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3467         OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3468     }
3469     else if (0 == ttl)
3470     {
3471         presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3472         OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3473     }
3474     else
3475     {
3476         presenceResource.presenceTTL = ttl;
3477     }
3478 #ifndef __TIZENRT__
3479     OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3480 #endif
3481
3482     if (OC_PRESENCE_UNINITIALIZED == presenceState)
3483     {
3484         presenceState = OC_PRESENCE_INITIALIZED;
3485
3486         OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3487
3488         CAToken_t caToken = NULL;
3489         CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3490         if (caResult != CA_STATUS_OK)
3491         {
3492             OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3493             CADestroyToken(caToken);
3494             return OC_STACK_ERROR;
3495         }
3496
3497         AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3498                 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3499         CADestroyToken(caToken);
3500     }
3501
3502     // Each time OCStartPresence is called
3503     // a different random 32-bit integer number is used
3504     ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3505
3506     return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3507             OC_PRESENCE_TRIGGER_CREATE);
3508 }
3509
3510 OCStackResult OCStopPresence()
3511 {
3512     OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3513     OCStackResult result = OC_STACK_ERROR;
3514
3515     if(presenceResource.handle)
3516     {
3517         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3518
3519     // make resource inactive
3520     result = OCChangeResourceProperty(
3521             &(((OCResource *) presenceResource.handle)->resourceProperties),
3522             OC_ACTIVE, 0);
3523     }
3524
3525     if(result != OC_STACK_OK)
3526     {
3527         OIC_LOG(ERROR, TAG,
3528                       "Changing the presence resource properties to ACTIVE not successful");
3529         return result;
3530     }
3531
3532     return SendStopNotification();
3533 }
3534 #endif
3535
3536 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3537                                             void* callbackParameter)
3538 {
3539     defaultDeviceHandler = entityHandler;
3540     defaultDeviceHandlerCallbackParameter = callbackParameter;
3541
3542     return OC_STACK_OK;
3543 }
3544
3545 OCStackResult OCCreateResource(OCResourceHandle *handle,
3546         const char *resourceTypeName,
3547         const char *resourceInterfaceName,
3548         const char *uri, OCEntityHandler entityHandler,
3549         void* callbackParam,
3550         uint8_t resourceProperties)
3551 {
3552
3553     OCResource *pointer = NULL;
3554     OCStackResult result = OC_STACK_ERROR;
3555
3556     OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3557
3558     if(myStackMode == OC_CLIENT)
3559     {
3560         return OC_STACK_INVALID_PARAM;
3561     }
3562     // Validate parameters
3563     if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3564     {
3565         OIC_LOG(ERROR, TAG, "URI is empty or too long");
3566         return OC_STACK_INVALID_URI;
3567     }
3568     // Is it presented during resource discovery?
3569     if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3570     {
3571         OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3572         return OC_STACK_INVALID_PARAM;
3573     }
3574
3575     if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3576     {
3577         resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3578     }
3579
3580 #ifdef MQ_PUBLISHER
3581     resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3582 #endif
3583     // Make sure resourceProperties bitmask has allowed properties specified
3584     if (resourceProperties
3585             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3586                OC_EXPLICIT_DISCOVERABLE
3587 #ifdef MQ_PUBLISHER
3588                | OC_MQ_PUBLISHER
3589 #endif
3590 #ifdef MQ_BROKER
3591                | OC_MQ_BROKER
3592 #endif
3593                ))
3594     {
3595         OIC_LOG(ERROR, TAG, "Invalid property");
3596         return OC_STACK_INVALID_PARAM;
3597     }
3598
3599     // If the headResource is NULL, then no resources have been created...
3600     pointer = headResource;
3601     if (pointer)
3602     {
3603         // At least one resources is in the resource list, so we need to search for
3604         // repeated URLs, which are not allowed.  If a repeat is found, exit with an error
3605         while (pointer)
3606         {
3607             if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3608             {
3609                 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3610                 return OC_STACK_INVALID_PARAM;
3611             }
3612             pointer = pointer->next;
3613         }
3614     }
3615     // Create the pointer and insert it into the resource list
3616     pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3617     if (!pointer)
3618     {
3619         result = OC_STACK_NO_MEMORY;
3620         goto exit;
3621     }
3622     pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3623
3624     insertResource(pointer);
3625
3626     // Set the uri
3627     pointer->uri = OICStrdup(uri);
3628     if (!pointer->uri)
3629     {
3630         result = OC_STACK_NO_MEMORY;
3631         goto exit;
3632     }
3633
3634     // Set properties.  Set OC_ACTIVE
3635     pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3636             | OC_ACTIVE);
3637
3638     // Add the resourcetype to the resource
3639     result = BindResourceTypeToResource(pointer, resourceTypeName);
3640     if (result != OC_STACK_OK)
3641     {
3642         OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3643         goto exit;
3644     }
3645
3646     // Add the resourceinterface to the resource
3647     result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3648     if (result != OC_STACK_OK)
3649     {
3650         OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3651         goto exit;
3652     }
3653
3654     // If an entity handler has been passed, attach it to the newly created
3655     // resource.  Otherwise, set the default entity handler.
3656     if (entityHandler)
3657     {
3658         pointer->entityHandler = entityHandler;
3659         pointer->entityHandlerCallbackParam = callbackParam;
3660     }
3661     else
3662     {
3663         pointer->entityHandler = defaultResourceEHandler;
3664         pointer->entityHandlerCallbackParam = NULL;
3665     }
3666
3667     // Initialize a pointer indicating child resources in case of collection
3668     pointer->rsrcChildResourcesHead = NULL;
3669
3670     *handle = pointer;
3671     result = OC_STACK_OK;
3672
3673 #ifdef WITH_PRESENCE
3674     if (presenceResource.handle)
3675     {
3676         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3677         SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3678     }
3679 #endif
3680 exit:
3681     if (result != OC_STACK_OK)
3682     {
3683         // Deep delete of resource and other dynamic elements that it contains
3684         deleteResource(pointer);
3685     }
3686     return result;
3687 }
3688
3689 OCStackResult OCBindResource(
3690         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3691 {
3692     OCResource *resource = NULL;
3693     OCChildResource *tempChildResource = NULL;
3694     OCChildResource *newChildResource = NULL;
3695
3696     OIC_LOG(INFO, TAG, "Entering OCBindResource");
3697
3698     // Validate parameters
3699     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3700     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3701     // Container cannot contain itself
3702     if (collectionHandle == resourceHandle)
3703     {
3704         OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3705         return OC_STACK_INVALID_PARAM;
3706     }
3707
3708     // Use the handle to find the resource in the resource linked list
3709     resource = findResource((OCResource *) collectionHandle);
3710     if (!resource)
3711     {
3712         OIC_LOG(ERROR, TAG, "Collection handle not found");
3713         return OC_STACK_INVALID_PARAM;
3714     }
3715
3716     // Look for an open slot to add add the child resource.
3717     // If found, add it and return success
3718
3719     tempChildResource = resource->rsrcChildResourcesHead;
3720
3721     while(resource->rsrcChildResourcesHead && tempChildResource->next)
3722     {
3723         // TODO: what if one of child resource was deregistered without unbinding?
3724         tempChildResource = tempChildResource->next;
3725     }
3726
3727     // Do memory allocation for child resource
3728     newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3729     if(!newChildResource)
3730     {
3731         OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3732         return OC_STACK_ERROR;
3733     }
3734
3735     newChildResource->rsrcResource = (OCResource *) resourceHandle;
3736     newChildResource->next = NULL;
3737
3738     if(!resource->rsrcChildResourcesHead)
3739     {
3740         resource->rsrcChildResourcesHead = newChildResource;
3741     }
3742     else {
3743         tempChildResource->next = newChildResource;
3744     }
3745
3746     OIC_LOG(INFO, TAG, "resource bound");
3747
3748 #ifdef WITH_PRESENCE
3749     if (presenceResource.handle)
3750     {
3751         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3752         SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3753                 OC_PRESENCE_TRIGGER_CHANGE);
3754     }
3755 #endif
3756
3757     return OC_STACK_OK;
3758 }
3759
3760 OCStackResult OCUnBindResource(
3761         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3762 {
3763     OCResource *resource = NULL;
3764     OCChildResource *tempChildResource = NULL;
3765     OCChildResource *tempLastChildResource = NULL;
3766
3767     OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3768
3769     // Validate parameters
3770     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3771     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3772     // Container cannot contain itself
3773     if (collectionHandle == resourceHandle)
3774     {
3775         OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3776         return OC_STACK_INVALID_PARAM;
3777     }
3778
3779     // Use the handle to find the resource in the resource linked list
3780     resource = findResource((OCResource *) collectionHandle);
3781     if (!resource)
3782     {
3783         OIC_LOG(ERROR, TAG, "Collection handle not found");
3784         return OC_STACK_INVALID_PARAM;
3785     }
3786
3787     // Look for an open slot to add add the child resource.
3788     // If found, add it and return success
3789     if(!resource->rsrcChildResourcesHead)
3790     {
3791         OIC_LOG(INFO, TAG, "resource not found in collection");
3792
3793         // Unable to add resourceHandle, so return error
3794         return OC_STACK_ERROR;
3795
3796     }
3797
3798     tempChildResource = resource->rsrcChildResourcesHead;
3799
3800     while (tempChildResource)
3801     {
3802         if(tempChildResource->rsrcResource == resourceHandle)
3803         {
3804             // if resource going to be unbinded is the head one.
3805             if( tempChildResource == resource->rsrcChildResourcesHead )
3806             {
3807                 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3808                 OICFree(resource->rsrcChildResourcesHead);
3809                 resource->rsrcChildResourcesHead = temp;
3810                 temp = NULL;
3811             }
3812             else
3813             {
3814                 OCChildResource *temp = tempChildResource->next;
3815                 OICFree(tempChildResource);
3816                 if (tempLastChildResource)
3817                 {
3818                     tempLastChildResource->next = temp;
3819                     temp = NULL;
3820                 }
3821             }
3822
3823             OIC_LOG(INFO, TAG, "resource unbound");
3824
3825             // Send notification when resource is unbounded successfully.
3826 #ifdef WITH_PRESENCE
3827             if (presenceResource.handle)
3828             {
3829                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3830                 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3831                         OC_PRESENCE_TRIGGER_CHANGE);
3832             }
3833 #endif
3834             tempChildResource = NULL;
3835             tempLastChildResource = NULL;
3836
3837             return OC_STACK_OK;
3838
3839         }
3840
3841         tempLastChildResource = tempChildResource;
3842         tempChildResource = tempChildResource->next;
3843     }
3844
3845     OIC_LOG(INFO, TAG, "resource not found in collection");
3846
3847     tempChildResource = NULL;
3848     tempLastChildResource = NULL;
3849
3850     // Unable to add resourceHandle, so return error
3851     return OC_STACK_ERROR;
3852 }
3853
3854 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3855 {
3856     if (!resourceItemName)
3857     {
3858         return false;
3859     }
3860     // Per RFC 6690 only registered values must follow the first rule below.
3861     // At this point in time the only values registered begin with "core", and
3862     // all other values are specified as opaque strings where multiple values
3863     // are separated by a space.
3864     if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3865     {
3866         for(size_t index = sizeof(CORESPEC) - 1;  resourceItemName[index]; ++index)
3867         {
3868             if (resourceItemName[index] != '.'
3869                 && resourceItemName[index] != '-'
3870                 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3871                 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3872             {
3873                 return false;
3874             }
3875         }
3876     }
3877     else
3878     {
3879         for (size_t index = 0; resourceItemName[index]; ++index)
3880         {
3881             if (resourceItemName[index] == ' '
3882                 || resourceItemName[index] == '\t'
3883                 || resourceItemName[index] == '\r'
3884                 || resourceItemName[index] == '\n')
3885             {
3886                 return false;
3887             }
3888         }
3889     }
3890
3891     return true;
3892 }
3893
3894 OCStackResult BindResourceTypeToResource(OCResource* resource,
3895                                             const char *resourceTypeName)
3896 {
3897     OCResourceType *pointer = NULL;
3898     char *str = NULL;
3899     OCStackResult result = OC_STACK_ERROR;
3900
3901     VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3902
3903     if (!ValidateResourceTypeInterface(resourceTypeName))
3904     {
3905         OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3906         return OC_STACK_INVALID_PARAM;
3907     }
3908
3909     pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3910     if (!pointer)
3911     {
3912         result = OC_STACK_NO_MEMORY;
3913         goto exit;
3914     }
3915
3916     str = OICStrdup(resourceTypeName);
3917     if (!str)
3918     {
3919         result = OC_STACK_NO_MEMORY;
3920         goto exit;
3921     }
3922     pointer->resourcetypename = str;
3923     pointer->next = NULL;
3924
3925     insertResourceType(resource, pointer);
3926     result = OC_STACK_OK;
3927
3928 exit:
3929     if (result != OC_STACK_OK)
3930     {
3931         OICFree(pointer);
3932         OICFree(str);
3933     }
3934
3935     return result;
3936 }
3937
3938 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3939         const char *resourceInterfaceName)
3940 {
3941     OCResourceInterface *pointer = NULL;
3942     char *str = NULL;
3943     OCStackResult result = OC_STACK_ERROR;
3944
3945     VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3946
3947     if (!ValidateResourceTypeInterface(resourceInterfaceName))
3948     {
3949         OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3950         return OC_STACK_INVALID_PARAM;
3951     }
3952
3953     OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3954
3955     pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3956     if (!pointer)
3957     {
3958         result = OC_STACK_NO_MEMORY;
3959         goto exit;
3960     }
3961
3962     str = OICStrdup(resourceInterfaceName);
3963     if (!str)
3964     {
3965         result = OC_STACK_NO_MEMORY;
3966         goto exit;
3967     }
3968     pointer->name = str;
3969
3970     // Bind the resourceinterface to the resource
3971     insertResourceInterface(resource, pointer);
3972
3973     result = OC_STACK_OK;
3974
3975     exit:
3976     if (result != OC_STACK_OK)
3977     {
3978         OICFree(pointer);
3979         OICFree(str);
3980     }
3981
3982     return result;
3983 }
3984
3985 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3986         const char *resourceTypeName)
3987 {
3988
3989     OCStackResult result = OC_STACK_ERROR;
3990     OCResource *resource = NULL;
3991
3992     resource = findResource((OCResource *) handle);
3993     if (!resource)
3994     {
3995         OIC_LOG(ERROR, TAG, "Resource not found");
3996         return OC_STACK_ERROR;
3997     }
3998
3999     result = BindResourceTypeToResource(resource, resourceTypeName);
4000
4001 #ifdef WITH_PRESENCE
4002     if(presenceResource.handle)
4003     {
4004         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4005         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4006     }
4007 #endif
4008
4009     return result;
4010 }
4011
4012 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
4013         const char *resourceInterfaceName)
4014 {
4015
4016     OCStackResult result = OC_STACK_ERROR;
4017     OCResource *resource = NULL;
4018
4019     resource = findResource((OCResource *) handle);
4020     if (!resource)
4021     {
4022         OIC_LOG(ERROR, TAG, "Resource not found");
4023         return OC_STACK_ERROR;
4024     }
4025
4026     result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
4027
4028 #ifdef WITH_PRESENCE
4029     if (presenceResource.handle)
4030     {
4031         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4032         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4033     }
4034 #endif
4035
4036     return result;
4037 }
4038
4039 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
4040 {
4041     OCResource *pointer = headResource;
4042
4043     VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
4044     *numResources = 0;
4045     while (pointer)
4046     {
4047         *numResources = *numResources + 1;
4048         pointer = pointer->next;
4049     }
4050     return OC_STACK_OK;
4051 }
4052
4053 OCResourceHandle OCGetResourceHandle(uint8_t index)
4054 {
4055     OCResource *pointer = headResource;
4056
4057     for( uint8_t i = 0; i < index && pointer; ++i)
4058     {
4059         pointer = pointer->next;
4060     }
4061     return (OCResourceHandle) pointer;
4062 }
4063
4064 OCStackResult OCDeleteResource(OCResourceHandle handle)
4065 {
4066     if (!handle)
4067     {
4068         OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4069         return OC_STACK_INVALID_PARAM;
4070     }
4071
4072     OCResource *resource = findResource((OCResource *) handle);
4073     if (resource == NULL)
4074     {
4075         OIC_LOG(ERROR, TAG, "Resource not found");
4076         return OC_STACK_NO_RESOURCE;
4077     }
4078
4079     if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4080     {
4081         OIC_LOG(ERROR, TAG, "Error deleting resource");
4082         return OC_STACK_ERROR;
4083     }
4084
4085     return OC_STACK_OK;
4086 }
4087
4088 const char *OCGetResourceUri(OCResourceHandle handle)
4089 {
4090     OCResource *resource = NULL;
4091
4092     resource = findResource((OCResource *) handle);
4093     if (resource)
4094     {
4095         return resource->uri;
4096     }
4097     return (const char *) NULL;
4098 }
4099
4100 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4101 {
4102     OCResource *resource = NULL;
4103
4104     resource = findResource((OCResource *) handle);
4105     if (resource)
4106     {
4107         return resource->resourceProperties;
4108     }
4109     return (OCResourceProperty)-1;
4110 }
4111
4112 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4113         uint8_t *numResourceTypes)
4114 {
4115     OCResource *resource = NULL;
4116     OCResourceType *pointer = NULL;
4117
4118     VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4119     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4120
4121     *numResourceTypes = 0;
4122
4123     resource = findResource((OCResource *) handle);
4124     if (resource)
4125     {
4126         pointer = resource->rsrcType;
4127         while (pointer)
4128         {
4129             *numResourceTypes = *numResourceTypes + 1;
4130             pointer = pointer->next;
4131         }
4132     }
4133     return OC_STACK_OK;
4134 }
4135
4136 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4137 {
4138     OCResourceType *resourceType = NULL;
4139
4140     resourceType = findResourceTypeAtIndex(handle, index);
4141     if (resourceType)
4142     {
4143         return resourceType->resourcetypename;
4144     }
4145     return (const char *) NULL;
4146 }
4147
4148 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4149         uint8_t *numResourceInterfaces)
4150 {
4151     OCResourceInterface *pointer = NULL;
4152     OCResource *resource = NULL;
4153
4154     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4155     VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4156
4157     *numResourceInterfaces = 0;
4158     resource = findResource((OCResource *) handle);
4159     if (resource)
4160     {
4161         pointer = resource->rsrcInterface;
4162         while (pointer)
4163         {
4164             *numResourceInterfaces = *numResourceInterfaces + 1;
4165             pointer = pointer->next;
4166         }
4167     }
4168     return OC_STACK_OK;
4169 }
4170
4171 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4172 {
4173     OCResourceInterface *resourceInterface = NULL;
4174
4175     resourceInterface = findResourceInterfaceAtIndex(handle, index);
4176     if (resourceInterface)
4177     {
4178         return resourceInterface->name;
4179     }
4180     return (const char *) NULL;
4181 }
4182
4183 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4184         uint8_t index)
4185 {
4186     OCResource *resource = NULL;
4187     OCChildResource *tempChildResource = NULL;
4188     uint8_t num = 0;
4189
4190     resource = findResource((OCResource *) collectionHandle);
4191     if (!resource)
4192     {
4193         return NULL;
4194     }
4195
4196     tempChildResource = resource->rsrcChildResourcesHead;
4197
4198     while(tempChildResource)
4199     {
4200         if( num == index )
4201         {
4202             return tempChildResource->rsrcResource;
4203         }
4204         num++;
4205         tempChildResource = tempChildResource->next;
4206     }
4207
4208     // In this case, the number of resource handles in the collection exceeds the index
4209     tempChildResource = NULL;
4210     return NULL;
4211 }
4212
4213 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4214         OCEntityHandler entityHandler,
4215         void* callbackParam)
4216 {
4217     OCResource *resource = NULL;
4218
4219     // Validate parameters
4220     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4221
4222     // Use the handle to find the resource in the resource linked list
4223     resource = findResource((OCResource *)handle);
4224     if (!resource)
4225     {
4226         OIC_LOG(ERROR, TAG, "Resource not found");
4227         return OC_STACK_ERROR;
4228     }
4229
4230     // Bind the handler
4231     resource->entityHandler = entityHandler;
4232     resource->entityHandlerCallbackParam = callbackParam;
4233
4234 #ifdef WITH_PRESENCE
4235     if (presenceResource.handle)
4236     {
4237         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4238         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4239     }
4240 #endif
4241
4242     return OC_STACK_OK;
4243 }
4244
4245 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4246 {
4247     OCResource *resource = NULL;
4248
4249     resource = findResource((OCResource *)handle);
4250     if (!resource)
4251     {
4252         OIC_LOG(ERROR, TAG, "Resource not found");
4253         return NULL;
4254     }
4255
4256     // Bind the handler
4257     return resource->entityHandler;
4258 }
4259
4260 void incrementSequenceNumber(OCResource * resPtr)
4261 {
4262     // Increment the sequence number
4263     resPtr->sequenceNum += 1;
4264     if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4265     {
4266         resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4267     }
4268     return;
4269 }
4270
4271 #ifdef WITH_PRESENCE
4272 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4273         OCPresenceTrigger trigger)
4274 {
4275     OIC_LOG(INFO, TAG, "SendPresenceNotification");
4276     OCResource *resPtr = NULL;
4277     OCStackResult result = OC_STACK_ERROR;
4278     OCMethod method = OC_REST_PRESENCE;
4279     uint32_t maxAge = 0;
4280     resPtr = findResource((OCResource *) presenceResource.handle);
4281     if(NULL == resPtr)
4282     {
4283         return OC_STACK_NO_RESOURCE;
4284     }
4285
4286     if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4287     {
4288         maxAge = presenceResource.presenceTTL;
4289
4290         result = SendAllObserverNotification(method, resPtr, maxAge,
4291                 trigger, resourceType, OC_LOW_QOS);
4292     }
4293
4294     return result;
4295 }
4296
4297 OCStackResult SendStopNotification()
4298 {
4299     OIC_LOG(INFO, TAG, "SendStopNotification");
4300     OCResource *resPtr = NULL;
4301     OCStackResult result = OC_STACK_ERROR;
4302     OCMethod method = OC_REST_PRESENCE;
4303     resPtr = findResource((OCResource *) presenceResource.handle);
4304     if(NULL == resPtr)
4305     {
4306         return OC_STACK_NO_RESOURCE;
4307     }
4308
4309     // maxAge is 0. ResourceType is NULL.
4310     result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4311             NULL, OC_LOW_QOS);
4312
4313     return result;
4314 }
4315
4316 #endif // WITH_PRESENCE
4317 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4318 {
4319     OCResource *resPtr = NULL;
4320     OCStackResult result = OC_STACK_ERROR;
4321     OCMethod method = OC_REST_NOMETHOD;
4322     uint32_t maxAge = 0;
4323
4324     OIC_LOG(INFO, TAG, "Notifying all observers");
4325 #ifdef WITH_PRESENCE
4326     if(handle == presenceResource.handle)
4327     {
4328         return OC_STACK_OK;
4329     }
4330 #endif // WITH_PRESENCE
4331     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4332
4333     // Verify that the resource exists
4334     resPtr = findResource ((OCResource *) handle);
4335     if (NULL == resPtr)
4336     {
4337         return OC_STACK_NO_RESOURCE;
4338     }
4339     else
4340     {
4341         //only increment in the case of regular observing (not presence)
4342         incrementSequenceNumber(resPtr);
4343         method = OC_REST_OBSERVE;
4344         maxAge = MAX_OBSERVE_AGE;
4345 #ifdef WITH_PRESENCE
4346         result = SendAllObserverNotification (method, resPtr, maxAge,
4347                 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4348 #else
4349         result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4350 #endif
4351         return result;
4352     }
4353 }
4354
4355 OCStackResult
4356 OCNotifyListOfObservers (OCResourceHandle handle,
4357                          OCObservationId  *obsIdList,
4358                          uint8_t          numberOfIds,
4359                          const OCRepPayload       *payload,
4360                          OCQualityOfService qos)
4361 {
4362     OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4363
4364     OCResource *resPtr = NULL;
4365     //TODO: we should allow the server to define this
4366     uint32_t maxAge = MAX_OBSERVE_AGE;
4367
4368     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4369     VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4370     VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4371
4372     resPtr = findResource ((OCResource *) handle);
4373     if (NULL == resPtr || myStackMode == OC_CLIENT)
4374     {
4375         return OC_STACK_NO_RESOURCE;
4376     }
4377     else
4378     {
4379         incrementSequenceNumber(resPtr);
4380     }
4381     return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4382             payload, maxAge, qos));
4383 }
4384
4385 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4386 {
4387     OIC_TRACE_BEGIN(%s:OCDoResponse, TAG);
4388     OCStackResult result = OC_STACK_ERROR;
4389     OCServerRequest *serverRequest = NULL;
4390
4391     OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4392
4393     // Validate input parameters
4394     VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4395     VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4396
4397     // Normal response
4398     // Get pointer to request info
4399     serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
4400     if(serverRequest)
4401     {
4402         // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4403         result = serverRequest->ehResponseHandler(ehResponse);
4404     }
4405
4406     OIC_TRACE_END();
4407     return result;
4408 }
4409
4410 //#ifdef DIRECT_PAIRING
4411 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4412 {
4413     OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4414     if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4415     {
4416         OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4417         return NULL;
4418     }
4419
4420     return (const OCDPDev_t*)DPGetDiscoveredDevices();
4421 }
4422
4423 const OCDPDev_t* OCGetDirectPairedDevices()
4424 {
4425     return (const OCDPDev_t*)DPGetPairedDevices();
4426 }
4427
4428 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4429                                                      OCDirectPairingCB resultCallback)
4430 {
4431     OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4432     if(NULL ==  peer || NULL == pinNumber)
4433     {
4434         OIC_LOG(ERROR, TAG, "Invalid parameters");
4435         return OC_STACK_INVALID_PARAM;
4436     }
4437     if (NULL == resultCallback)
4438     {
4439         OIC_LOG(ERROR, TAG, "Invalid callback");
4440         return OC_STACK_INVALID_CALLBACK;
4441     }
4442
4443     return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4444                                            pinNumber, (OCDirectPairingResultCB)resultCallback);
4445 }
4446 //#endif // DIRECT_PAIRING
4447
4448 //-----------------------------------------------------------------------------
4449 // Private internal function definitions
4450 //-----------------------------------------------------------------------------
4451 static OCDoHandle GenerateInvocationHandle()
4452 {
4453     OCDoHandle handle = NULL;
4454     // Generate token here, it will be deleted when the transaction is deleted
4455     handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4456     if (handle)
4457     {
4458         OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4459     }
4460
4461     return handle;
4462 }
4463
4464 #ifdef WITH_PRESENCE
4465 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4466         OCResourceProperty resourceProperties, uint8_t enable)
4467 {
4468     if (!inputProperty)
4469     {
4470         return OC_STACK_INVALID_PARAM;
4471     }
4472     if (resourceProperties
4473             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4474     {
4475         OIC_LOG(ERROR, TAG, "Invalid property");
4476         return OC_STACK_INVALID_PARAM;
4477     }
4478     if(!enable)
4479     {
4480         *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4481     }
4482     else
4483     {
4484         *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4485     }
4486     return OC_STACK_OK;
4487 }
4488 #endif
4489
4490 OCStackResult initResources()
4491 {
4492     OCStackResult result = OC_STACK_OK;
4493
4494     headResource = NULL;
4495     tailResource = NULL;
4496     // Init Virtual Resources
4497 #ifdef WITH_PRESENCE
4498     presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4499
4500     result = OCCreateResource(&presenceResource.handle,
4501             OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4502             "core.r",
4503             OC_RSRVD_PRESENCE_URI,
4504             NULL,
4505             NULL,
4506             OC_OBSERVABLE);
4507     //make resource inactive
4508     result = OCChangeResourceProperty(
4509             &(((OCResource *) presenceResource.handle)->resourceProperties),
4510             OC_ACTIVE, 0);
4511 #endif
4512 #ifndef WITH_ARDUINO
4513     if (result == OC_STACK_OK)
4514     {
4515         result = SRMInitSecureResources();
4516     }
4517 #endif
4518
4519     if(result == OC_STACK_OK)
4520     {
4521         CreateResetProfile();
4522         result = OCCreateResource(&deviceResource,
4523                                   OC_RSRVD_RESOURCE_TYPE_DEVICE,
4524                                   OC_RSRVD_INTERFACE_DEFAULT,
4525                                   OC_RSRVD_DEVICE_URI,
4526                                   NULL,
4527                                   NULL,
4528                                   OC_DISCOVERABLE);
4529         if(result == OC_STACK_OK)
4530         {
4531             result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4532                                                      OC_RSRVD_INTERFACE_READ);
4533         }
4534     }
4535
4536     if(result == OC_STACK_OK)
4537     {
4538         result = OCCreateResource(&platformResource,
4539                                   OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4540                                   OC_RSRVD_INTERFACE_DEFAULT,
4541                                   OC_RSRVD_PLATFORM_URI,
4542                                   NULL,
4543                                   NULL,
4544                                   OC_DISCOVERABLE);
4545         if(result == OC_STACK_OK)
4546         {
4547             result = BindResourceInterfaceToResource((OCResource *)platformResource,
4548                                                      OC_RSRVD_INTERFACE_READ);
4549         }
4550     }
4551
4552     return result;
4553 }
4554
4555 void insertResource(OCResource *resource)
4556 {
4557     if (!headResource)
4558     {
4559         headResource = resource;
4560         tailResource = resource;
4561     }
4562     else
4563     {
4564         tailResource->next = resource;
4565         tailResource = resource;
4566     }
4567     resource->next = NULL;
4568 }
4569
4570 OCResource *findResource(OCResource *resource)
4571 {
4572     OCResource *pointer = headResource;
4573
4574     while (pointer)
4575     {
4576         if (pointer == resource)
4577         {
4578             return resource;
4579         }
4580         pointer = pointer->next;
4581     }
4582     return NULL;
4583 }
4584
4585 void deleteAllResources()
4586 {
4587     OCResource *pointer = headResource;
4588     OCResource *temp = NULL;
4589
4590     while (pointer)
4591     {
4592         temp = pointer->next;
4593 #ifdef WITH_PRESENCE
4594         if (pointer != (OCResource *) presenceResource.handle)
4595         {
4596 #endif // WITH_PRESENCE
4597             deleteResource(pointer);
4598 #ifdef WITH_PRESENCE
4599         }
4600 #endif // WITH_PRESENCE
4601         pointer = temp;
4602     }
4603     memset(&platformResource, 0, sizeof(platformResource));
4604     memset(&deviceResource, 0, sizeof(deviceResource));
4605 #ifdef MQ_BROKER
4606     memset(&brokerResource, 0, sizeof(brokerResource));
4607 #endif
4608
4609     SRMDeInitSecureResources();
4610
4611 #ifdef WITH_PRESENCE
4612     // Ensure that the last resource to be deleted is the presence resource. This allows for all
4613     // presence notification attributed to their deletion to be processed.
4614     deleteResource((OCResource *) presenceResource.handle);
4615     memset(&presenceResource, 0, sizeof(presenceResource));
4616 #endif // WITH_PRESENCE
4617 }
4618
4619 OCStackResult deleteResource(OCResource *resource)
4620 {
4621     OCResource *prev = NULL;
4622     OCResource *temp = NULL;
4623     if(!resource)
4624     {
4625         OIC_LOG(DEBUG,TAG,"resource is NULL");
4626         return OC_STACK_INVALID_PARAM;
4627     }
4628
4629     OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4630
4631     temp = headResource;
4632     while (temp)
4633     {
4634         if (temp == resource)
4635         {
4636             // Invalidate all Resource Properties.
4637             resource->resourceProperties = (OCResourceProperty) 0;
4638 #ifdef WITH_PRESENCE
4639             if(resource != (OCResource *) presenceResource.handle)
4640             {
4641 #endif // WITH_PRESENCE
4642                 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4643 #ifdef WITH_PRESENCE
4644             }
4645
4646             if(presenceResource.handle)
4647             {
4648                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4649                 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4650             }
4651 #endif
4652             // Delete resource's all observers
4653             DeleteObserverUsingResource(resource);
4654
4655             // Only resource in list.
4656             if (temp == headResource && temp == tailResource)
4657             {
4658                 headResource = NULL;
4659                 tailResource = NULL;
4660             }
4661             // Deleting head.
4662             else if (temp == headResource)
4663             {
4664                 headResource = temp->next;
4665             }
4666             // Deleting tail.
4667             else if (temp == tailResource && prev)
4668             {
4669                 tailResource = prev;
4670                 tailResource->next = NULL;
4671             }
4672             else if (prev)
4673             {
4674                 prev->next = temp->next;
4675             }
4676
4677             deleteResourceElements(temp);
4678             OICFree(temp);
4679             return OC_STACK_OK;
4680         }
4681         else
4682         {
4683             prev = temp;
4684             temp = temp->next;
4685         }
4686     }
4687
4688     return OC_STACK_ERROR;
4689 }
4690
4691 void deleteResourceElements(OCResource *resource)
4692 {
4693     if (!resource)
4694     {
4695         return;
4696     }
4697
4698     if (resource->uri)
4699     {
4700         OICFree(resource->uri);
4701         resource->uri = NULL;
4702     }
4703     if (resource->rsrcType)
4704     {
4705         deleteResourceType(resource->rsrcType);
4706         resource->rsrcType = NULL;
4707     }
4708     if (resource->rsrcInterface)
4709     {
4710         deleteResourceInterface(resource->rsrcInterface);
4711         resource->rsrcInterface = NULL;
4712     }
4713     if (resource->rsrcChildResourcesHead)
4714     {
4715         unbindChildResources(resource->rsrcChildResourcesHead);
4716         resource->rsrcChildResourcesHead = NULL;
4717     }
4718     if (resource->rsrcAttributes)
4719     {
4720         OCDeleteResourceAttributes(resource->rsrcAttributes);
4721         resource->rsrcAttributes = NULL;
4722     }
4723
4724     resource->entityHandler = NULL;
4725     resource = NULL;
4726 }
4727
4728 void deleteResourceType(OCResourceType *resourceType)
4729 {
4730     OCResourceType *next = NULL;
4731
4732     for (OCResourceType *pointer = resourceType; pointer; pointer = next)
4733     {
4734         next = pointer->next ? pointer->next : NULL;
4735         if (pointer->resourcetypename)
4736         {
4737             OICFree(pointer->resourcetypename);
4738             pointer->resourcetypename = NULL;
4739         }
4740         OICFree(pointer);
4741     }
4742 }
4743
4744 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4745 {
4746     OCResourceInterface *next = NULL;
4747     for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
4748     {
4749         next = pointer->next ? pointer->next : NULL;
4750         if (pointer->name)
4751         {
4752             OICFree(pointer->name);
4753             pointer->name = NULL;
4754         }
4755         OICFree(pointer);
4756     }
4757 }
4758
4759 void unbindChildResources(OCChildResource *head)
4760 {
4761     OCChildResource *next = NULL;
4762     for (OCChildResource *current = head; current; current = next)
4763     {
4764         next = current->next;
4765         OICFree(current);
4766     }
4767 }
4768
4769 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
4770 {
4771     OCAttribute *next = NULL;
4772     for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
4773     {
4774         next = pointer->next ? pointer->next : NULL;
4775         if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
4776         {
4777             OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
4778             pointer->attrValue = NULL;
4779         }
4780         else if (pointer->attrValue)
4781         {
4782             OICFree(pointer->attrValue);
4783             pointer->attrValue = NULL;
4784         }
4785         if (pointer->attrName)
4786         {
4787             OICFree(pointer->attrName);
4788             pointer->attrName = NULL;
4789         }
4790         OICFree(pointer);
4791     }
4792 }
4793
4794 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4795 {
4796     OCResourceType *pointer = NULL;
4797     OCResourceType *previous = NULL;
4798     if (!resource || !resourceType)
4799     {
4800         return;
4801     }
4802     // resource type list is empty.
4803     else if (!resource->rsrcType)
4804     {
4805         resource->rsrcType = resourceType;
4806     }
4807     else
4808     {
4809         pointer = resource->rsrcType;
4810
4811         while (pointer)
4812         {
4813             if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4814             {
4815                 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4816                 OICFree(resourceType->resourcetypename);
4817                 OICFree(resourceType);
4818                 return;
4819             }
4820             previous = pointer;
4821             pointer = pointer->next;
4822         }
4823
4824         if (previous)
4825         {
4826             previous->next = resourceType;
4827         }
4828     }
4829     resourceType->next = NULL;
4830
4831     OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4832 }
4833
4834 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4835 {
4836     OCResource *resource = NULL;
4837     OCResourceType *pointer = NULL;
4838
4839     // Find the specified resource
4840     resource = findResource((OCResource *) handle);
4841     if (!resource)
4842     {
4843         return NULL;
4844     }
4845
4846     // Make sure a resource has a resourcetype
4847     if (!resource->rsrcType)
4848     {
4849         return NULL;
4850     }
4851
4852     // Iterate through the list
4853     pointer = resource->rsrcType;
4854     for(uint8_t i = 0; i< index && pointer; ++i)
4855     {
4856         pointer = pointer->next;
4857     }
4858     return pointer;
4859 }
4860
4861 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4862 {
4863     if(resourceTypeList && resourceTypeName)
4864     {
4865         OCResourceType * rtPointer = resourceTypeList;
4866         while(resourceTypeName && rtPointer)
4867         {
4868             OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4869             if(rtPointer->resourcetypename &&
4870                     strcmp(resourceTypeName, (const char *)
4871                     (rtPointer->resourcetypename)) == 0)
4872             {
4873                 break;
4874             }
4875             rtPointer = rtPointer->next;
4876         }
4877         return rtPointer;
4878     }
4879     return NULL;
4880 }
4881
4882 /*
4883  * Insert a new interface into interface linked list only if not already present.
4884  * If alredy present, 2nd arg is free'd.
4885  * Default interface will always be first if present.
4886  */
4887 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4888 {
4889     OCResourceInterface *pointer = NULL;
4890     OCResourceInterface *previous = NULL;
4891
4892     newInterface->next = NULL;
4893
4894     OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4895
4896     if (!*firstInterface)
4897     {
4898         // If first interface is not oic.if.baseline, by default add it as first interface type.
4899         if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4900         {
4901             *firstInterface = newInterface;
4902         }
4903         else
4904         {
4905             OCStackResult result = BindResourceInterfaceToResource(resource,
4906                                                                     OC_RSRVD_INTERFACE_DEFAULT);
4907             if (result != OC_STACK_OK)
4908             {
4909                 OICFree(newInterface->name);
4910                 OICFree(newInterface);
4911                 return;
4912             }
4913             if (*firstInterface)
4914             {
4915                 (*firstInterface)->next = newInterface;
4916             }
4917         }
4918     }
4919     // If once add oic.if.baseline, later too below code take care of freeing memory.
4920     else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4921     {
4922         if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4923         {
4924             OICFree(newInterface->name);
4925             OICFree(newInterface);
4926             return;
4927         }
4928         // This code will not hit anymore, keeping
4929         else
4930         {
4931             newInterface->next = *firstInterface;
4932             *firstInterface = newInterface;
4933         }
4934     }
4935     else
4936     {
4937         pointer = *firstInterface;
4938         while (pointer)
4939         {
4940             if (strcmp(newInterface->name, pointer->name) == 0)
4941             {
4942                 OICFree(newInterface->name);
4943                 OICFree(newInterface);
4944                 return;
4945             }
4946             previous = pointer;
4947             pointer = pointer->next;
4948         }
4949
4950         if (previous)
4951         {
4952             previous->next = newInterface;
4953         }
4954     }
4955 }
4956
4957 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4958         uint8_t index)
4959 {
4960     OCResource *resource = NULL;
4961     OCResourceInterface *pointer = NULL;
4962
4963     // Find the specified resource
4964     resource = findResource((OCResource *) handle);
4965     if (!resource)
4966     {
4967         return NULL;
4968     }
4969
4970     // Make sure a resource has a resourceinterface
4971     if (!resource->rsrcInterface)
4972     {
4973         return NULL;
4974     }
4975
4976     // Iterate through the list
4977     pointer = resource->rsrcInterface;
4978
4979     for (uint8_t i = 0; i < index && pointer; ++i)
4980     {
4981         pointer = pointer->next;
4982     }
4983     return pointer;
4984 }
4985
4986 /*
4987  * This function splits the uri using the '?' delimiter.
4988  * "uriWithoutQuery" is the block of characters between the beginning
4989  * till the delimiter or '\0' which ever comes first.
4990  * "query" is whatever is to the right of the delimiter if present.
4991  * No delimiter sets the query to NULL.
4992  * If either are present, they will be malloc'ed into the params 2, 3.
4993  * The first param, *uri is left untouched.
4994
4995  * NOTE: This function does not account for whitespace at the end of the uri NOR
4996  *       malformed uri's with '??'. Whitespace at the end will be assumed to be
4997  *       part of the query.
4998  */
4999 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
5000 {
5001     if(!uri)
5002     {
5003         return OC_STACK_INVALID_URI;
5004     }
5005     if(!query || !uriWithoutQuery)
5006     {
5007         return OC_STACK_INVALID_PARAM;
5008     }
5009
5010     *query           = NULL;
5011     *uriWithoutQuery = NULL;
5012
5013     size_t uriWithoutQueryLen = 0;
5014     size_t queryLen = 0;
5015     size_t uriLen = strlen(uri);
5016
5017     char *pointerToDelimiter = strstr(uri, "?");
5018
5019     uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
5020     queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
5021
5022     if (uriWithoutQueryLen)
5023     {
5024         *uriWithoutQuery =  (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
5025         if (!*uriWithoutQuery)
5026         {
5027             goto exit;
5028         }
5029         OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
5030     }
5031     if (queryLen)
5032     {
5033         *query = (char *) OICCalloc(queryLen + 1, 1);
5034         if (!*query)
5035         {
5036             OICFree(*uriWithoutQuery);
5037             *uriWithoutQuery = NULL;
5038             goto exit;
5039         }
5040         OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5041     }
5042
5043     return OC_STACK_OK;
5044
5045     exit:
5046         return OC_STACK_NO_MEMORY;
5047 }
5048
5049 const char* OCGetServerInstanceIDString(void)
5050 {
5051     static char sidStr[UUID_STRING_SIZE];
5052     OicUuid_t sid;
5053     if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5054     {
5055         OIC_LOG(FATAL, TAG, "GetDoxmDeviceID failed!");
5056         return NULL;
5057     }
5058
5059     if (OCConvertUuidToString(sid.id, sidStr) != RAND_UUID_OK)
5060     {
5061         OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5062         return NULL;
5063     }
5064
5065     return sidStr;
5066 }
5067
5068 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5069 {
5070     OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5071     CAResult_t retResult = CA_STATUS_FAILED;
5072     CAResult_t caResult = CA_STATUS_OK;
5073
5074     CATransportAdapter_t connTypes[] = {
5075             CA_ADAPTER_IP,
5076             CA_ADAPTER_RFCOMM_BTEDR,
5077             CA_ADAPTER_GATT_BTLE,
5078             CA_ADAPTER_NFC
5079 #ifdef RA_ADAPTER
5080             ,CA_ADAPTER_REMOTE_ACCESS
5081 #endif
5082
5083 #ifdef TCP_ADAPTER
5084             ,CA_ADAPTER_TCP
5085 #endif
5086         };
5087     int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5088
5089     for(int i = 0; i < numConnTypes; i++)
5090     {
5091         // If CA status is not initialized, CASelectNetwork() will not be called.
5092         if (caResult != CA_STATUS_NOT_INITIALIZED)
5093         {
5094             if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5095             {
5096                 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5097                 caResult = CASelectNetwork(connTypes[i]);
5098                 if (caResult == CA_STATUS_OK)
5099                 {
5100                     retResult = CA_STATUS_OK;
5101                 }
5102             }
5103             else
5104             {
5105                 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5106             }
5107         }
5108     }
5109
5110     if (retResult != CA_STATUS_OK)
5111     {
5112         return caResult; // Returns error of appropriate transport that failed fatally.
5113     }
5114
5115     return retResult;
5116 }
5117
5118 OCStackResult CAResultToOCResult(CAResult_t caResult)
5119 {
5120     switch (caResult)
5121     {
5122         case CA_STATUS_OK:
5123             return OC_STACK_OK;
5124         case CA_STATUS_INVALID_PARAM:
5125             return OC_STACK_INVALID_PARAM;
5126         case CA_ADAPTER_NOT_ENABLED:
5127             return OC_STACK_ADAPTER_NOT_ENABLED;
5128         case CA_SERVER_STARTED_ALREADY:
5129             return OC_STACK_OK;
5130         case CA_SERVER_NOT_STARTED:
5131             return OC_STACK_ERROR;
5132         case CA_DESTINATION_NOT_REACHABLE:
5133             return OC_STACK_COMM_ERROR;
5134         case CA_SOCKET_OPERATION_FAILED:
5135             return OC_STACK_COMM_ERROR;
5136         case CA_SEND_FAILED:
5137             return OC_STACK_COMM_ERROR;
5138         case CA_RECEIVE_FAILED:
5139             return OC_STACK_COMM_ERROR;
5140         case CA_MEMORY_ALLOC_FAILED:
5141             return OC_STACK_NO_MEMORY;
5142         case CA_REQUEST_TIMEOUT:
5143             return OC_STACK_TIMEOUT;
5144         case CA_DESTINATION_DISCONNECTED:
5145             return OC_STACK_COMM_ERROR;
5146         case CA_STATUS_FAILED:
5147             return OC_STACK_ERROR;
5148         case CA_NOT_SUPPORTED:
5149             return OC_STACK_NOTIMPL;
5150         default:
5151             return OC_STACK_ERROR;
5152     }
5153 }
5154
5155 bool OCResultToSuccess(OCStackResult ocResult)
5156 {
5157     switch (ocResult)
5158     {
5159         case OC_STACK_OK:
5160         case OC_STACK_RESOURCE_CREATED:
5161         case OC_STACK_RESOURCE_DELETED:
5162         case OC_STACK_CONTINUE:
5163         case OC_STACK_RESOURCE_CHANGED:
5164         case OC_STACK_SLOW_RESOURCE:
5165             return true;
5166         default:
5167             return false;
5168     }
5169 }
5170
5171 #ifdef WITH_CHPROXY
5172 OCStackResult OCSetProxyURI(const char *uri)
5173 {
5174     return CAResultToOCResult(CASetProxyUri(uri));
5175 }
5176 #endif
5177
5178 #if defined(RD_CLIENT) || defined(RD_SERVER)
5179 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5180 {
5181     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5182
5183     OCResource *resource = NULL;
5184
5185     resource = findResource((OCResource *) handle);
5186     if (!resource)
5187     {
5188         OIC_LOG(ERROR, TAG, "Resource not found");
5189         return OC_STACK_ERROR;
5190     }
5191
5192     resource->ins = ins;
5193
5194     return OC_STACK_OK;
5195 }
5196
5197
5198 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5199                                               const OCClientResponse *response)
5200 {
5201     // Validate input parameters
5202     VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5203     VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5204
5205     char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5206     if (!targetUri)
5207     {
5208         return OC_STACK_NO_MEMORY;
5209     }
5210     strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5211
5212     if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5213     {
5214         OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5215
5216         char rdPubUri[MAX_URI_LENGTH] = { 0 };
5217         snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5218                  OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5219
5220         if (strcmp(rdPubUri, targetUri) == 0)
5221         {
5222             // Update resource unique id in stack.
5223             if (response)
5224             {
5225                 if (response->payload)
5226                 {
5227                     OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5228                     OCRepPayload **links = NULL;
5229                     size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5230                     if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5231                                                        &links, dimensions))
5232                     {
5233                         size_t i = 0;
5234                         for (; i < dimensions[0]; i++)
5235                         {
5236                             char *uri = NULL;
5237                             if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5238                             {
5239                                 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5240                                 int64_t ins = 0;
5241                                 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5242                                 {
5243                                     OCBindResourceInsToResource(handle, ins);
5244                                 }
5245
5246                                 OICFree(uri);
5247                                 uri = NULL;
5248                             }
5249                         }
5250
5251                         // Free links
5252                         size_t count = calcDimTotal(dimensions);
5253                         for (size_t k = 0; k < count; k++)
5254                         {
5255                             OCRepPayloadDestroy(links[k]);
5256                         }
5257                         OICFree(links);
5258                     }
5259                 }
5260             }
5261         }
5262     }
5263     else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5264     {
5265         OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5266
5267         uint8_t numResources = 0;
5268         OCGetNumberOfResources(&numResources);
5269
5270         char *ins = strstr(targetUri, OC_RSRVD_INS);
5271         if (!ins)
5272         {
5273             for (uint8_t i = 0; i < numResources; i++)
5274             {
5275                 OCResourceHandle resHandle = OCGetResourceHandle(i);
5276                 if (resHandle)
5277                 {
5278                     OCBindResourceInsToResource(resHandle, 0);
5279                 }
5280             }
5281         }
5282         else
5283         {
5284             const char *token = "&";
5285             char *iterTokenPtr = NULL;
5286             char *start = strtok_r(targetUri, token, &iterTokenPtr);
5287
5288              while (start != NULL)
5289              {
5290                  char *query = start;
5291                  query = strstr(query, OC_RSRVD_INS);
5292                  if (query)
5293                  {
5294                      int64_t queryIns = atoi(query + 4);
5295                      for (uint8_t i = 0; i < numResources; i++)
5296                      {
5297                          OCResourceHandle resHandle = OCGetResourceHandle(i);
5298                          if (resHandle)
5299                          {
5300                              int64_t resIns = 0;
5301                              OCGetResourceIns(resHandle, &resIns);
5302                              if (queryIns && queryIns == resIns)
5303                              {
5304                                  OCBindResourceInsToResource(resHandle, 0);
5305                                  break;
5306                              }
5307                          }
5308                      }
5309                  }
5310                  start = strtok_r(NULL, token, &iterTokenPtr);
5311              }
5312         }
5313     }
5314
5315     OICFree(targetUri);
5316     return OC_STACK_OK;
5317 }
5318
5319 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5320 {
5321     if (!uri)
5322     {
5323         OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5324         return NULL;
5325     }
5326
5327     OCResource *pointer = headResource;
5328
5329     while (pointer)
5330     {
5331         if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5332         {
5333             OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5334             return pointer;
5335         }
5336         pointer = pointer->next;
5337     }
5338     return NULL;
5339 }
5340
5341 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t *ins)
5342 {
5343     OCResource *resource = NULL;
5344
5345     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5346     VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5347
5348     resource = findResource((OCResource *) handle);
5349     if (resource)
5350     {
5351         *ins = resource->ins;
5352         return OC_STACK_OK;
5353     }
5354     return OC_STACK_ERROR;
5355 }
5356 #endif
5357
5358 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5359                                 const void* optionData, size_t optionDataLength)
5360 {
5361     if (!ocHdrOpt)
5362     {
5363         OIC_LOG (INFO, TAG, "Header options are NULL");
5364         return OC_STACK_INVALID_PARAM;
5365     }
5366
5367     if (!optionData)
5368     {
5369         OIC_LOG (INFO, TAG, "optionData are NULL");
5370         return OC_STACK_INVALID_PARAM;
5371     }
5372
5373     if (!numOptions)
5374     {
5375         OIC_LOG (INFO, TAG, "numOptions is NULL");
5376         return OC_STACK_INVALID_PARAM;
5377     }
5378
5379     if (*numOptions >= MAX_HEADER_OPTIONS)
5380     {
5381         OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5382         return OC_STACK_NO_MEMORY;
5383     }
5384
5385     ocHdrOpt += *numOptions;
5386     ocHdrOpt->protocolID = OC_COAP_ID;
5387     ocHdrOpt->optionID = optionID;
5388     ocHdrOpt->optionLength =
5389             optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
5390                     optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5391     memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5392     *numOptions += 1;
5393
5394     return OC_STACK_OK;
5395 }
5396
5397 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5398                                 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5399 {
5400     if (!ocHdrOpt || !numOptions)
5401     {
5402         OIC_LOG (INFO, TAG, "No options present");
5403         return OC_STACK_OK;
5404     }
5405
5406     if (!optionData)
5407     {
5408         OIC_LOG (INFO, TAG, "optionData are NULL");
5409         return OC_STACK_INVALID_PARAM;
5410     }
5411
5412     if (!receivedDataLength)
5413     {
5414         OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5415         return OC_STACK_INVALID_PARAM;
5416     }
5417
5418     for (uint8_t i = 0; i < numOptions; i++)
5419     {
5420         if (ocHdrOpt[i].optionID == optionID)
5421         {
5422             if (optionDataLength >= ocHdrOpt->optionLength)
5423             {
5424                 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5425                 *receivedDataLength = ocHdrOpt->optionLength;
5426                 return OC_STACK_OK;
5427             }
5428             else
5429             {
5430                 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5431                 return OC_STACK_ERROR;
5432             }
5433         }
5434     }
5435     return OC_STACK_OK;
5436 }
5437
5438 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5439 {
5440     OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5441     if (g_adapterHandler)
5442     {
5443         g_adapterHandler(adapter, enabled);
5444     }
5445 }
5446
5447 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5448 {
5449     OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5450     if (g_connectionHandler)
5451     {
5452        g_connectionHandler(info, isConnected);
5453     }
5454
5455     /*
5456      * If the client observes one or more resources over a reliable connection,
5457      * then the CoAP server (or intermediary in the role of the CoAP server)
5458      * MUST remove all entries associated with the client endpoint from the lists
5459      * of observers when the connection is either closed or times out.
5460      */
5461     if (!isConnected)
5462     {
5463         OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5464         CopyEndpointToDevAddr(info, &devAddr);
5465
5466         // remove observer list with remote device address.
5467         DeleteObserverUsingDevAddr(&devAddr);
5468     }
5469 }
5470
5471 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5472 {
5473     OicUuid_t oicUuid;
5474     OCStackResult ret = OC_STACK_ERROR;
5475
5476     ret = GetDoxmDeviceID(&oicUuid);
5477     if (OC_STACK_OK == ret)
5478     {
5479         memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5480     }
5481     else
5482     {
5483         OIC_LOG(ERROR, TAG, "Device ID Get error");
5484     }
5485     return ret;
5486 }
5487
5488 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5489 {
5490     OicUuid_t oicUuid;
5491     OCStackResult ret = OC_STACK_ERROR;
5492
5493     memcpy(&oicUuid, deviceId, UUID_LENGTH);
5494     for (int i = 0; i < UUID_LENGTH; i++)
5495     {
5496         OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5497     }
5498     ret = SetDoxmDeviceID(&oicUuid);
5499     return ret;
5500 }
5501
5502 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5503 {
5504     bool isDeviceOwned = true;
5505     OCStackResult ret = OC_STACK_ERROR;
5506
5507     ret = GetDoxmIsOwned(&isDeviceOwned);
5508     if (OC_STACK_OK == ret)
5509     {
5510         *isOwned = isDeviceOwned;
5511     }
5512     else
5513     {
5514         OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5515     }
5516     return ret;
5517 }
5518
5519 void OCClearCallBackList()
5520 {
5521     DeleteClientCBList();
5522 }
5523
5524 void OCClearObserverlist()
5525 {
5526     DeleteObserverList();
5527 }
5528
5529 int OCEncrypt(const unsigned char *pt, size_t pt_len,
5530         unsigned char **ct, size_t *ct_len)
5531 {
5532 #ifndef __SECURE_PSI__
5533     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5534     return 0;
5535 #else
5536     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5537
5538     return psiEncrypt(pt, pt_len, ct, ct_len);
5539 #endif // __SECURE_PSI__
5540 }
5541
5542 int OCDecrypt(const unsigned char *ct, size_t ct_len,
5543         unsigned char **pt, size_t *pt_len)
5544 {
5545 #ifndef __SECURE_PSI__
5546     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5547     return 0;
5548 #else
5549     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5550
5551     return psiDecrypt(ct, ct_len, pt, pt_len);
5552 #endif // __SECURE_PSI__
5553 }
5554
5555 OCStackResult OCSetKey(const unsigned char* key)
5556 {
5557 #ifndef __SECURE_PSI__
5558     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5559     return OC_STACK_OK;
5560 #else
5561     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5562
5563     return psiSetKey(key);
5564 #endif // __SECURE_PSI__
5565 }
5566
5567 OCStackResult OCGetKey(unsigned char* key)
5568 {
5569 #ifndef __SECURE_PSI__
5570     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5571     return OC_STACK_OK;
5572 #else
5573     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5574
5575     return psiGetKey(key);
5576 #endif // __SECURE_PSI__
5577 }
5578
5579 OCStackResult OCSetSecurePSI(const unsigned char *key, const OCPersistentStorage *psPlain,
5580         const OCPersistentStorage *psEnc, const OCPersistentStorage *psRescue)
5581 {
5582 #ifndef __SECURE_PSI__
5583     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5584     return OC_STACK_OK;
5585 #else
5586     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5587
5588     return setSecurePSI(key, psPlain, psEnc, psRescue);
5589 #endif // __SECURE_PSI__
5590 }
5591
5592 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5593 static void OtmEventHandler(const char *addr, uint16_t port, const char *uuid, int event)
5594 {
5595     if (g_otmEventHandler.cb)
5596     {
5597         g_otmEventHandler.cb(g_otmEventHandler.ctx, addr, port, uuid, event);
5598     }
5599 }
5600
5601 /* TODO Work-around
5602  * It is already declared in srmutility.h.
5603  * We can't include the header file, because of "redefined VERIFY_NON_NULL"
5604  */
5605 typedef void (*OicSecOtmEventHandler_t)(const char* addr, uint16_t port,
5606         const char* uuid, int event);
5607 void SetOtmEventHandler(OicSecOtmEventHandler_t otmEventHandler);
5608 #endif
5609
5610 OCStackResult OCSetOtmEventHandler(void *ctx, OCOtmEventHandler cb)
5611 {
5612 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5613     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5614
5615     g_otmEventHandler.cb = cb;
5616     g_otmEventHandler.ctx = ctx;
5617
5618     if (g_otmEventHandler.cb)
5619     {
5620         OIC_LOG(DEBUG, TAG, "SET OCOtmEventHandler");
5621         SetOtmEventHandler(OtmEventHandler);
5622     }
5623     else
5624     {
5625         OIC_LOG(DEBUG, TAG, "UNSET OCOtmEventHandler");
5626         SetOtmEventHandler(NULL);
5627     }
5628 #else
5629     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5630     OC_UNUSED(ctx);
5631     OC_UNUSED(cb);
5632 #endif
5633     return OC_STACK_OK;
5634 }