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