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