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