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