754756bac8a8a046ff32b557d54edd0dd4383eb7
[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         FindAndDeleteClientCB(cbNode);
1850     }
1851
1852     ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1853                                                        errorInfo->info.tokenLength);
1854     if (observer)
1855     {
1856         OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1857         OCStackResult result = CAResultToOCResult(errorInfo->result);
1858         if (OC_STACK_COMM_ERROR == result)
1859         {
1860             OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1861                             OC_OBSERVER_FAILED_COMM);
1862         }
1863     }
1864
1865     OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1866     OIC_TRACE_END();
1867     if(NULL != observer)
1868     {
1869         OICFree(observer);
1870         observer = NULL;
1871     }
1872 }
1873
1874 /*
1875  * This function sends out Direct Stack Responses. These are responses that are not coming
1876  * from the application entity handler. These responses have no payload and are usually ACKs,
1877  * RESETs or some error conditions that were caught by the stack.
1878  */
1879 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1880         const CAResponseResult_t responseResult, const CAMessageType_t type,
1881         const uint8_t numOptions, const CAHeaderOption_t *options,
1882         CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1883         CADataType_t dataType)
1884 {
1885     OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1886
1887     if (endPoint->flags & CA_MULTICAST)
1888     {
1889         OIC_LOG(ERROR, TAG, "It is unnecessary to respond to a multicast request");
1890         return OC_STACK_OK;
1891     }
1892
1893     CAResponseInfo_t respInfo = { .result = responseResult };
1894     respInfo.info.messageId = coapID;
1895     respInfo.info.numOptions = numOptions;
1896
1897     if (respInfo.info.numOptions)
1898     {
1899         respInfo.info.options =
1900             (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1901         memcpy (respInfo.info.options, options,
1902                 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1903
1904     }
1905
1906     respInfo.info.payload = NULL;
1907     respInfo.info.token = token;
1908     respInfo.info.tokenLength = tokenLength;
1909     respInfo.info.type = type;
1910     respInfo.info.resourceUri = OICStrdup (resourceUri);
1911     respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1912     respInfo.info.dataType = dataType;
1913
1914 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1915     // Add the destination to route option from the endpoint->routeData.
1916     bool doPost = false;
1917     OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1918     if(OC_STACK_OK != result)
1919     {
1920         OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1921         OICFree (respInfo.info.resourceUri);
1922         OICFree (respInfo.info.options);
1923         return result;
1924     }
1925     if (doPost)
1926     {
1927         OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1928         CARequestInfo_t reqInfo = {.method = CA_POST };
1929         /* The following initialization is not done in a single initializer block as in
1930          * arduino, .c file is compiled as .cpp and moves it from C99 to C++11.  The latter
1931          * does not have designated initalizers. This is a work-around for now.
1932          */
1933         reqInfo.info.type = CA_MSG_NONCONFIRM;
1934         reqInfo.info.messageId = coapID;
1935         reqInfo.info.tokenLength = tokenLength;
1936         reqInfo.info.token = token;
1937         reqInfo.info.numOptions = respInfo.info.numOptions;
1938         reqInfo.info.payload = NULL;
1939         reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1940         if (reqInfo.info.numOptions)
1941         {
1942             reqInfo.info.options =
1943                 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1944             if (NULL == reqInfo.info.options)
1945             {
1946                 OIC_LOG(ERROR, TAG, "Calloc failed");
1947                 OICFree (reqInfo.info.resourceUri);
1948                 OICFree (respInfo.info.resourceUri);
1949                 OICFree (respInfo.info.options);
1950                 return OC_STACK_NO_MEMORY;
1951             }
1952             memcpy (reqInfo.info.options, respInfo.info.options,
1953                     sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1954
1955         }
1956         CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1957         OICFree (reqInfo.info.resourceUri);
1958         OICFree (reqInfo.info.options);
1959         OICFree (respInfo.info.resourceUri);
1960         OICFree (respInfo.info.options);
1961         if (CA_STATUS_OK != caResult)
1962         {
1963             OIC_LOG(ERROR, TAG, "CASendRequest error");
1964             return CAResultToOCResult(caResult);
1965         }
1966     }
1967     else
1968 #endif
1969     {
1970         CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1971
1972         // resourceUri in the info field is cloned in the CA layer and
1973         // thus ownership is still here.
1974         OICFree (respInfo.info.resourceUri);
1975         OICFree (respInfo.info.options);
1976         if(CA_STATUS_OK != caResult)
1977         {
1978             OIC_LOG(ERROR, TAG, "CASendResponse error");
1979             return CAResultToOCResult(caResult);
1980         }
1981     }
1982     OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1983     return OC_STACK_OK;
1984 }
1985
1986 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1987 {
1988     OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1989     OCStackResult result = OC_STACK_ERROR;
1990     if(!protocolRequest)
1991     {
1992         OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1993         return OC_STACK_INVALID_PARAM;
1994     }
1995
1996     OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1997             protocolRequest->tokenLength);
1998     if(!request)
1999     {
2000         OIC_LOG(INFO, TAG, "This is a new Server Request");
2001         result = AddServerRequest(&request, protocolRequest->coapID,
2002                 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
2003                 protocolRequest->numRcvdVendorSpecificHeaderOptions,
2004                 protocolRequest->observationOption, protocolRequest->qos,
2005                 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
2006                 protocolRequest->payload, protocolRequest->requestToken,
2007                 protocolRequest->tokenLength, protocolRequest->resourceUrl,
2008                 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
2009                 &protocolRequest->devAddr);
2010         if (OC_STACK_OK != result)
2011         {
2012             OIC_LOG(ERROR, TAG, "Error adding server request");
2013             return result;
2014         }
2015
2016         if(!request)
2017         {
2018             OIC_LOG(ERROR, TAG, "Out of Memory");
2019             return OC_STACK_NO_MEMORY;
2020         }
2021
2022         if(!protocolRequest->reqMorePacket)
2023         {
2024             request->requestComplete = 1;
2025         }
2026
2027         OIC_LOG_V(WARNING, TAG, "Server request ID = [%u]", request->requestId);
2028     }
2029     else
2030     {
2031         OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
2032         return OC_STACK_DUPLICATE_REQUEST;
2033     }
2034
2035     if(request->requestComplete)
2036     {
2037         OIC_LOG(INFO, TAG, "This Server Request is complete");
2038         ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2039         OCResource *resource = NULL;
2040         result = DetermineResourceHandling (request, &resHandling, &resource);
2041         if (result == OC_STACK_OK)
2042         {
2043             result = ProcessRequest(resHandling, resource, request);
2044         }
2045     }
2046     else
2047     {
2048         OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2049         result = OC_STACK_CONTINUE;
2050     }
2051     return result;
2052 }
2053
2054 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2055 {
2056     OIC_TRACE_MARK(%s:OCHandleRequests:%s, TAG, requestInfo->info.resourceUri);
2057     OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2058
2059     OCStackResult requestResult = OC_STACK_ERROR;
2060
2061     if(myStackMode == OC_CLIENT)
2062     {
2063         //TODO: should the client be responding to requests?
2064         return;
2065     }
2066
2067     OCServerProtocolRequest serverRequest = {0};
2068
2069     OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2070
2071     char * uriWithoutQuery = NULL;
2072     char * query  = NULL;
2073
2074     requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2075
2076     if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2077     {
2078         OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2079         return;
2080     }
2081     OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2082     OIC_LOG_V(INFO, TAG, "Query : %s", query);
2083
2084     if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2085     {
2086         OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2087         OICFree(uriWithoutQuery);
2088     }
2089     else
2090     {
2091         OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2092         OICFree(uriWithoutQuery);
2093         OICFree(query);
2094         return;
2095     }
2096
2097     if(query)
2098     {
2099         if(strlen(query) < MAX_QUERY_LENGTH)
2100         {
2101             OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2102             OICFree(query);
2103         }
2104         else
2105         {
2106             OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2107             OICFree(query);
2108             return;
2109         }
2110     }
2111
2112     if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2113     {
2114         serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2115         serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2116         if (!serverRequest.payload)
2117         {
2118             OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2119             return;
2120         }
2121         memcpy (serverRequest.payload, requestInfo->info.payload,
2122                 requestInfo->info.payloadSize);
2123     }
2124     else
2125     {
2126         serverRequest.reqTotalSize = 0;
2127     }
2128
2129     switch (requestInfo->method)
2130     {
2131         case CA_GET:
2132             serverRequest.method = OC_REST_GET;
2133             break;
2134         case CA_PUT:
2135             serverRequest.method = OC_REST_PUT;
2136             break;
2137         case CA_POST:
2138             serverRequest.method = OC_REST_POST;
2139             break;
2140         case CA_DELETE:
2141             serverRequest.method = OC_REST_DELETE;
2142             break;
2143         default:
2144             OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2145             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2146                         requestInfo->info.type, requestInfo->info.numOptions,
2147                         requestInfo->info.options, requestInfo->info.token,
2148                         requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2149                         CA_RESPONSE_DATA);
2150             OICFree(serverRequest.payload);
2151             return;
2152     }
2153
2154     OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2155             requestInfo->info.tokenLength);
2156
2157     serverRequest.tokenLength = requestInfo->info.tokenLength;
2158     if (serverRequest.tokenLength) {
2159         // Non empty token
2160         serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2161
2162         if (!serverRequest.requestToken)
2163         {
2164             OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2165             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2166                     requestInfo->info.type, requestInfo->info.numOptions,
2167                     requestInfo->info.options, requestInfo->info.token,
2168                     requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2169                     CA_RESPONSE_DATA);
2170             OICFree(serverRequest.payload);
2171             return;
2172         }
2173         memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2174     }
2175
2176     switch (requestInfo->info.acceptFormat)
2177     {
2178         case CA_FORMAT_APPLICATION_CBOR:
2179             serverRequest.acceptFormat = OC_FORMAT_CBOR;
2180             break;
2181         case CA_FORMAT_UNDEFINED:
2182             serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2183             break;
2184         default:
2185             serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2186     }
2187
2188     if (requestInfo->info.type == CA_MSG_CONFIRM)
2189     {
2190         serverRequest.qos = OC_HIGH_QOS;
2191     }
2192     else
2193     {
2194         serverRequest.qos = OC_LOW_QOS;
2195     }
2196     // CA does not need the following field
2197     // Are we sure CA does not need them? how is it responding to multicast
2198     serverRequest.delayedResNeeded = 0;
2199
2200     serverRequest.coapID = requestInfo->info.messageId;
2201
2202     CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2203
2204     // copy vendor specific header options
2205     uint8_t tempNum = (requestInfo->info.numOptions);
2206
2207     // Assume no observation requested and it is a pure GET.
2208     // If obs registration/de-registration requested it'll be fetched from the
2209     // options in GetObserveHeaderOption()
2210     serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2211
2212     GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2213     if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2214     {
2215         OIC_LOG(ERROR, TAG,
2216                 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2217         SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2218                 requestInfo->info.type, requestInfo->info.numOptions,
2219                 requestInfo->info.options, requestInfo->info.token,
2220                 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2221                 CA_RESPONSE_DATA);
2222         OICFree(serverRequest.payload);
2223         OICFree(serverRequest.requestToken);
2224         return;
2225     }
2226
2227     serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2228     if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2229     {
2230         serverRequest.rcvdVendorSpecificHeaderOptions = (OCHeaderOption*) OICCalloc(tempNum, sizeof(OCHeaderOption));
2231         if (NULL == serverRequest.rcvdVendorSpecificHeaderOptions)
2232         {
2233             OIC_LOG(ERROR, TAG, "Failed to allocated memory to vnd header options!");
2234             OICFree(serverRequest.payload);
2235             OICFree(serverRequest.requestToken);
2236             return;
2237         }
2238
2239         memcpy (serverRequest.rcvdVendorSpecificHeaderOptions, requestInfo->info.options,
2240             sizeof(CAHeaderOption_t)*tempNum);
2241     }
2242
2243     requestResult = HandleStackRequests (&serverRequest);
2244
2245     // Send ACK to client as precursor to slow response
2246     if (requestResult == OC_STACK_SLOW_RESOURCE)
2247     {
2248         if (requestInfo->info.type == CA_MSG_CONFIRM)
2249         {
2250             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2251                                     CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2252                                     CA_RESPONSE_DATA);
2253         }
2254     }
2255 #ifndef __TIZENRT__
2256     if (requestResult == OC_STACK_RESOURCE_ERROR
2257             && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2258     {
2259         OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2260     }
2261 #else
2262     if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2263     {
2264         if (requestResult == OC_STACK_RESOURCE_ERROR)
2265         {
2266             OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2267         }
2268         else if (!OCResultToSuccess(requestResult))
2269         {
2270             DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2271         }
2272     }
2273 #endif
2274     else if(!OCResultToSuccess(requestResult))
2275     {
2276         OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2277
2278         // Delete observer node if it is OBSERVE failure from app
2279         if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2280         {
2281             DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2282         }
2283
2284         CAResponseResult_t stackResponse =
2285             OCToCAStackResult(requestResult, serverRequest.method);
2286
2287         SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2288                 requestInfo->info.type, requestInfo->info.numOptions,
2289                 requestInfo->info.options, requestInfo->info.token,
2290                 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2291                 CA_RESPONSE_DATA);
2292     }
2293     // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2294     // The token is copied in there, and is thus still owned by this function.
2295     OICFree(serverRequest.payload);
2296     OICFree(serverRequest.requestToken);
2297     OICFree(serverRequest.rcvdVendorSpecificHeaderOptions);
2298     OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2299 }
2300
2301 //This function will be called back by CA layer when a request is received
2302 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2303 {
2304     OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2305     OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2306     if(!endPoint)
2307     {
2308         OIC_LOG(ERROR, TAG, "endPoint is NULL");
2309         OIC_TRACE_END();
2310         return;
2311     }
2312
2313     if(!requestInfo)
2314     {
2315         OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2316         OIC_TRACE_END();
2317         return;
2318     }
2319
2320 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2321 #ifdef ROUTING_GATEWAY
2322     bool needRIHandling = false;
2323     bool isEmptyMsg = false;
2324     /*
2325      * Routing manager is going to update either of endpoint or request or both.
2326      * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2327      * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2328      * destination. It can also remove "RM" coap header option before passing request / response to
2329      * RI as this option will make no sense to either RI or application.
2330      */
2331     OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2332                                         &needRIHandling, &isEmptyMsg);
2333     if(OC_STACK_OK != ret || !needRIHandling)
2334     {
2335         OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2336         OIC_TRACE_END();
2337         return;
2338     }
2339 #endif
2340
2341     /*
2342      * Put source in sender endpoint so that the next packet from application can be routed to
2343      * proper destination and remove RM header option.
2344      */
2345     RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2346                  (uint8_t *) &(requestInfo->info.numOptions),
2347                  (CAEndpoint_t *) endPoint);
2348
2349 #ifdef ROUTING_GATEWAY
2350     if (isEmptyMsg)
2351     {
2352         /*
2353          * In Gateways, the MSGType in route option is used to check if the actual
2354          * response is EMPTY message(4 bytes CoAP Header).  In case of Client, the
2355          * EMPTY response is sent in the form of POST request which need to be changed
2356          * to a EMPTY response by RM.  This translation is done in this part of the code.
2357          */
2358         OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2359         CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2360                                      .info.messageId = requestInfo->info.messageId,
2361                                      .info.type = CA_MSG_ACKNOWLEDGE};
2362         OCHandleResponse(endPoint, &respInfo);
2363     }
2364     else
2365 #endif
2366 #endif
2367     {
2368         // Normal handling of the packet
2369         OCHandleRequests(endPoint, requestInfo);
2370     }
2371     OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2372     OIC_TRACE_END();
2373 }
2374
2375 //-----------------------------------------------------------------------------
2376 // Public APIs
2377 //-----------------------------------------------------------------------------
2378 #ifdef RA_ADAPTER
2379 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2380 {
2381     if (!raInfo           ||
2382         !raInfo->username ||
2383         !raInfo->hostname ||
2384         !raInfo->xmpp_domain)
2385     {
2386
2387         return OC_STACK_INVALID_PARAM;
2388     }
2389     OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2390     gRASetInfo = (result == OC_STACK_OK)? true : false;
2391
2392     return result;
2393 }
2394 #endif
2395
2396 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2397 {
2398     (void) ipAddr;
2399     (void) port;
2400     return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2401 }
2402
2403 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2404 {
2405     OC_UNUSED(serverFlags);
2406     OC_UNUSED(clientFlags);
2407
2408     OIC_LOG(DEBUG, TAG, "call OCInit1");
2409     return OCInit2(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS, OC_DEFAULT_ADAPTER);
2410 }
2411
2412 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2413                       OCTransportAdapter transportType)
2414 {
2415     if(stackState == OC_STACK_INITIALIZED)
2416     {
2417         OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2418                 OCStop() between them are ignored.");
2419         return OC_STACK_OK;
2420     }
2421
2422 #ifndef ROUTING_GATEWAY
2423     if (OC_GATEWAY == mode)
2424     {
2425         OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2426         return OC_STACK_INVALID_PARAM;
2427     }
2428 #endif
2429
2430 #ifdef RA_ADAPTER
2431     if(!gRASetInfo)
2432     {
2433         OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2434         return OC_STACK_ERROR;
2435     }
2436 #endif
2437
2438     OCStackResult result = OC_STACK_ERROR;
2439     OIC_LOG(INFO, TAG, "Entering OCInit");
2440
2441     // Validate mode
2442     if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2443         || (mode == OC_GATEWAY)))
2444     {
2445         OIC_LOG(ERROR, TAG, "Invalid mode");
2446         return OC_STACK_ERROR;
2447     }
2448     myStackMode = mode;
2449
2450     if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2451     {
2452         caglobals.client = true;
2453     }
2454     if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2455     {
2456         caglobals.server = true;
2457     }
2458
2459     caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2460     if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2461     {
2462         caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2463     }
2464     caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2465     if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2466     {
2467         caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2468     }
2469
2470     defaultDeviceHandler = NULL;
2471     defaultDeviceHandlerCallbackParameter = NULL;
2472
2473     result = InitializeScheduleResourceList();
2474     VERIFY_SUCCESS(result, OC_STACK_OK);
2475
2476     result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2477     VERIFY_SUCCESS(result, OC_STACK_OK);
2478
2479     result = CAResultToOCResult(OCSelectNetwork(transportType));
2480     VERIFY_SUCCESS(result, OC_STACK_OK);
2481
2482     result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2483       OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2484     VERIFY_SUCCESS(result, OC_STACK_OK);
2485
2486     switch (myStackMode)
2487     {
2488         case OC_CLIENT:
2489             CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2490             result = CAResultToOCResult(CAStartDiscoveryServer());
2491             OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2492             break;
2493         case OC_SERVER:
2494             SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2495             result = CAResultToOCResult(CAStartListeningServer());
2496             OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2497             break;
2498         case OC_CLIENT_SERVER:
2499         case OC_GATEWAY:
2500             SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2501             result = CAResultToOCResult(CAStartListeningServer());
2502             if(result == OC_STACK_OK)
2503             {
2504                 result = CAResultToOCResult(CAStartDiscoveryServer());
2505             }
2506             break;
2507     }
2508     VERIFY_SUCCESS(result, OC_STACK_OK);
2509
2510 #ifdef TCP_ADAPTER
2511     CARegisterKeepAliveHandler(OCHandleKeepAliveConnCB);
2512 #endif
2513
2514 #ifdef WITH_PRESENCE
2515     PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2516 #endif // WITH_PRESENCE
2517
2518     //Update Stack state to initialized
2519     stackState = OC_STACK_INITIALIZED;
2520
2521     // Initialize resource
2522     if(myStackMode != OC_CLIENT)
2523     {
2524         result = initResources();
2525     }
2526
2527     // Initialize the SRM Policy Engine
2528     if(result == OC_STACK_OK)
2529     {
2530         result = SRMInitPolicyEngine();
2531         // TODO after BeachHead delivery: consolidate into single SRMInit()
2532     }
2533 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2534     RMSetStackMode(mode);
2535 #ifdef ROUTING_GATEWAY
2536     if (OC_GATEWAY == myStackMode)
2537     {
2538         result = RMInitialize();
2539     }
2540 #endif
2541 #endif
2542
2543 #ifdef TCP_ADAPTER
2544     if (result == OC_STACK_OK)
2545     {
2546         result = OCInitializeKeepAlive(myStackMode);
2547     }
2548 #endif
2549
2550     InitializeObserverList();
2551
2552 exit:
2553     if(result != OC_STACK_OK)
2554     {
2555         OIC_LOG(ERROR, TAG, "Stack initialization error");
2556         TerminateScheduleResourceList();
2557         deleteAllResources();
2558         CATerminate();
2559         stackState = OC_STACK_UNINITIALIZED;
2560     }
2561     return result;
2562 }
2563
2564 OCStackResult OCStop()
2565 {
2566     OIC_LOG(INFO, TAG, "Entering OCStop");
2567
2568     if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2569     {
2570         OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2571         return OC_STACK_OK;
2572     }
2573     else if (stackState != OC_STACK_INITIALIZED)
2574     {
2575         OIC_LOG(INFO, TAG, "Stack not initialized");
2576         return OC_STACK_ERROR;
2577     }
2578
2579     // unset cautil config
2580     CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2581     CAUtilSetBTConfigure(configs);
2582
2583     stackState = OC_STACK_UNINIT_IN_PROGRESS;
2584
2585     CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2586                                       OCDefaultConnectionStateChangedHandler);
2587
2588 #ifdef WITH_PRESENCE
2589     // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2590     // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2591     presenceResource.presenceTTL = 0;
2592     presenceState = OC_PRESENCE_UNINITIALIZED;
2593 #endif // WITH_PRESENCE
2594
2595 #ifdef ROUTING_GATEWAY
2596     if (OC_GATEWAY == myStackMode)
2597     {
2598         RMTerminate();
2599     }
2600 #endif
2601
2602 #ifdef TCP_ADAPTER
2603     OCTerminateKeepAlive(myStackMode);
2604 #endif
2605
2606     TerminateScheduleResourceList();
2607     // Remove all observers
2608     DeleteObserverList();
2609     // Free memory dynamically allocated for resources
2610     deleteAllResources();
2611     // Remove all the client callbacks
2612     DeleteClientCBList();
2613     // Terminate connectivity-abstraction layer.
2614     CATerminate();
2615
2616     // De-init the SRM Policy Engine
2617     // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2618     SRMDeInitPolicyEngine();
2619
2620     // Destroy Observer List Mutex
2621     TerminateObserverList();
2622
2623     stackState = OC_STACK_UNINITIALIZED;
2624     return OC_STACK_OK;
2625 }
2626
2627 OCStackResult OCStartMulticastServer()
2628 {
2629     if(stackState != OC_STACK_INITIALIZED)
2630     {
2631         OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2632         return OC_STACK_ERROR;
2633     }
2634     CAResult_t ret = CAStartListeningServer();
2635     if (CA_STATUS_OK != ret)
2636     {
2637         OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2638         return OC_STACK_ERROR;
2639     }
2640     return OC_STACK_OK;
2641 }
2642
2643 OCStackResult OCStopMulticastServer()
2644 {
2645     CAResult_t ret = CAStopListeningServer();
2646     if (CA_STATUS_OK != ret)
2647     {
2648         OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2649         return OC_STACK_ERROR;
2650     }
2651     return OC_STACK_OK;
2652 }
2653
2654 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2655 {
2656     switch (qos)
2657     {
2658         case OC_HIGH_QOS:
2659             return CA_MSG_CONFIRM;
2660         case OC_LOW_QOS:
2661         case OC_MEDIUM_QOS:
2662         case OC_NA_QOS:
2663         default:
2664             return CA_MSG_NONCONFIRM;
2665     }
2666 }
2667
2668 OCStackResult ParseRequestUri(const char *fullUri,
2669                               OCTransportAdapter adapter,
2670                               OCTransportFlags flags,
2671                               OCDevAddr **devAddr,
2672                               char **resourceUri,
2673                               char **resourceType)
2674 {
2675     VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2676
2677     OCStackResult result = OC_STACK_OK;
2678     OCDevAddr *da = NULL;
2679     char *colon = NULL;
2680     char *end;
2681
2682     // provide defaults for all returned values
2683     if (devAddr)
2684     {
2685         *devAddr = NULL;
2686     }
2687     if (resourceUri)
2688     {
2689         *resourceUri = NULL;
2690     }
2691     if (resourceType)
2692     {
2693         *resourceType = NULL;
2694     }
2695
2696     // delimit url prefix, if any
2697     const char *start = fullUri;
2698     char *slash2 = strstr(start, "//");
2699     if (slash2)
2700     {
2701         start = slash2 + 2;
2702     }
2703     char *slash = strchr(start, '/');
2704     if (!slash)
2705     {
2706         return OC_STACK_INVALID_URI;
2707     }
2708
2709     // process url scheme
2710     size_t prefixLen = slash2 - fullUri;
2711     bool istcp = false;
2712     if (prefixLen)
2713     {
2714         if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2715         || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2716         {
2717             istcp = true;
2718         }
2719     }
2720
2721     // TODO: this logic should come in with unit tests exercising the various strings
2722     // processs url prefix, if any
2723     size_t urlLen = slash - start;
2724     // port
2725     uint16_t port = 0;
2726     size_t len = 0;
2727     if (urlLen && devAddr)
2728     {   // construct OCDevAddr
2729         if (start[0] == '[')
2730         {   // ipv6 address
2731             char *close = strchr(++start, ']');
2732             if (!close || close > slash)
2733             {
2734                 return OC_STACK_INVALID_URI;
2735             }
2736             end = close;
2737             if (close[1] == ':')
2738             {
2739                 colon = close + 1;
2740             }
2741
2742             if (istcp)
2743             {
2744                 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2745             }
2746             else
2747             {
2748                 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2749             }
2750             flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2751         }
2752         else
2753         {
2754             char *dot = strchr(start, '.');
2755             if (dot && dot < slash)
2756             {   // ipv4 address
2757                 colon = strchr(start, ':');
2758                 end = (colon && colon < slash) ? colon : slash;
2759
2760                 if (istcp)
2761                 {
2762                     // coap over tcp
2763                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2764                 }
2765                 else
2766                 {
2767                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2768                 }
2769                 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2770             }
2771             else
2772             {   // MAC address
2773                 end = slash;
2774             }
2775         }
2776         len = end - start;
2777         if (len >= sizeof(da->addr))
2778         {
2779             return OC_STACK_INVALID_URI;
2780         }
2781         // collect port, if any
2782         if (colon && colon < slash)
2783         {
2784             for (colon++; colon < slash; colon++)
2785             {
2786                 char c = colon[0];
2787                 if (c < '0' || c > '9')
2788                 {
2789                     return OC_STACK_INVALID_URI;
2790                 }
2791                 port = 10 * port + c - '0';
2792             }
2793         }
2794
2795         len = end - start;
2796         if (len >= sizeof(da->addr))
2797         {
2798             return OC_STACK_INVALID_URI;
2799         }
2800
2801         da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2802         if (!da)
2803         {
2804             return OC_STACK_NO_MEMORY;
2805         }
2806
2807         // Decode address per RFC 6874.
2808         result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2809         if (result != OC_STACK_OK)
2810         {
2811              OICFree(*devAddr);
2812              return result;
2813         }
2814
2815         da->port = port;
2816         da->adapter = adapter;
2817         da->flags = flags;
2818         if (!strncmp(fullUri, "coaps", 5))
2819         {
2820             da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2821         }
2822         *devAddr = da;
2823     }
2824
2825     // process resource uri, if any
2826     if (slash)
2827     {   // request uri and query
2828         size_t ulen = strlen(slash); // resource uri length
2829         size_t tlen = 0;      // resource type length
2830         char *type = NULL;
2831
2832         static const char strPresence[] = "/oic/ad?rt=";
2833         static const size_t lenPresence = sizeof(strPresence) - 1;
2834         if (!strncmp(slash, strPresence, lenPresence))
2835         {
2836             type = slash + lenPresence;
2837             tlen = ulen - lenPresence;
2838         }
2839         // resource uri
2840         if (resourceUri)
2841         {
2842             *resourceUri = (char *)OICMalloc(ulen + 1);
2843             if (!*resourceUri)
2844             {
2845                 result = OC_STACK_NO_MEMORY;
2846                 goto error;
2847             }
2848             OICStrcpy(*resourceUri, (ulen + 1), slash);
2849         }
2850         // resource type
2851         if (type && resourceType)
2852         {
2853             *resourceType = (char *)OICMalloc(tlen + 1);
2854             if (!*resourceType)
2855             {
2856                 result = OC_STACK_NO_MEMORY;
2857                 goto error;
2858             }
2859
2860             OICStrcpy(*resourceType, (tlen+1), type);
2861         }
2862     }
2863
2864     return OC_STACK_OK;
2865
2866 error:
2867     // free all returned values
2868     if (devAddr)
2869     {
2870         OICFree(*devAddr);
2871     }
2872     if (resourceUri)
2873     {
2874         OICFree(*resourceUri);
2875     }
2876     if (resourceType)
2877     {
2878         OICFree(*resourceType);
2879     }
2880     return result;
2881 }
2882
2883 #ifdef WITH_PRESENCE
2884 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2885                                        char **requestUri,
2886                                        bool isMulticast)
2887 {
2888     char uri[CA_MAX_URI_LENGTH];
2889
2890     FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2891
2892     *requestUri = OICStrdup(uri);
2893     if (!*requestUri)
2894     {
2895         return OC_STACK_NO_MEMORY;
2896     }
2897
2898     return OC_STACK_OK;
2899 }
2900 #endif // WITH_PRESENCE
2901
2902 /**
2903  * Discover or Perform requests on a specified resource
2904  */
2905 OCStackResult OCDoResource(OCDoHandle *handle,
2906                             OCMethod method,
2907                             const char *requestUri,
2908                             const OCDevAddr *destination,
2909                             OCPayload* payload,
2910                             OCConnectivityType connectivityType,
2911                             OCQualityOfService qos,
2912                             OCCallbackData *cbData,
2913                             OCHeaderOption *options,
2914                             uint8_t numOptions)
2915 {
2916     OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
2917                 connectivityType, qos, cbData, options, numOptions);
2918
2919     // This is the owner of the payload object, so we free it
2920     OCPayloadDestroy(payload);
2921     return ret;
2922 }
2923
2924 /**
2925  * Discover or Perform requests on a specified resource
2926  */
2927 OCStackResult OCDoRequest(OCDoHandle *handle,
2928                             OCMethod method,
2929                             const char *requestUri,
2930                             const OCDevAddr *destination,
2931                             OCPayload* payload,
2932                             OCConnectivityType connectivityType,
2933                             OCQualityOfService qos,
2934                             OCCallbackData *cbData,
2935                             OCHeaderOption *options,
2936                             uint8_t numOptions)
2937 {
2938     OIC_LOG(INFO, TAG, "Entering OCDoResource");
2939     OIC_TRACE_BEGIN(%s:OCDoRequest, TAG);
2940
2941     // Validate input parameters
2942     VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2943     VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2944
2945     OCStackResult result = OC_STACK_ERROR;
2946     CAResult_t caResult;
2947     CAToken_t token = NULL;
2948     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2949     ClientCB *clientCB = NULL;
2950     OCDoHandle resHandle = NULL;
2951     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2952     OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2953     uint32_t ttl = 0;
2954     OCTransportAdapter adapter;
2955     OCTransportFlags flags;
2956     // the request contents are put here
2957     CARequestInfo_t requestInfo = {.method = CA_GET};
2958     // requestUri  will be parsed into the following three variables
2959     OCDevAddr *devAddr = NULL;
2960     char *resourceUri = NULL;
2961     char *resourceType = NULL;
2962
2963     /*
2964      * Support original behavior with address on resourceUri argument.
2965      */
2966     adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2967     flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2968
2969     if (requestUri)
2970     {
2971         result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2972         if (result != OC_STACK_OK)
2973         {
2974             OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2975             goto exit;
2976         }
2977     }
2978     else if (!checkProxyUri(options, numOptions))
2979     {
2980         result = OC_STACK_INVALID_URI;
2981         OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2982         goto exit;
2983     }
2984
2985     switch (method)
2986     {
2987     case OC_REST_GET:
2988     case OC_REST_OBSERVE:
2989     case OC_REST_OBSERVE_ALL:
2990         requestInfo.method = CA_GET;
2991         break;
2992     case OC_REST_PUT:
2993         requestInfo.method = CA_PUT;
2994         break;
2995     case OC_REST_POST:
2996         requestInfo.method = CA_POST;
2997         break;
2998     case OC_REST_DELETE:
2999         requestInfo.method = CA_DELETE;
3000         break;
3001     case OC_REST_DISCOVER:
3002 #ifdef WITH_PRESENCE
3003     case OC_REST_PRESENCE:
3004 #endif
3005         if (destination || devAddr)
3006         {
3007             requestInfo.isMulticast = false;
3008         }
3009         else
3010         {
3011             tmpDevAddr.adapter = adapter;
3012             tmpDevAddr.flags = flags;
3013             destination = &tmpDevAddr;
3014             requestInfo.isMulticast = true;
3015             qos = OC_LOW_QOS;
3016         }
3017         // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
3018         // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
3019         //                   replacing method type with GET.
3020         requestInfo.method = CA_GET;
3021         break;
3022     default:
3023         result = OC_STACK_INVALID_METHOD;
3024         goto exit;
3025     }
3026
3027     if (!devAddr && !destination)
3028     {
3029         OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
3030         result = OC_STACK_INVALID_PARAM;
3031         goto exit;
3032     }
3033
3034     /* If not original behavior, use destination argument */
3035     if (destination && !devAddr)
3036     {
3037         devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
3038         if (!devAddr)
3039         {
3040             result = OC_STACK_NO_MEMORY;
3041             goto exit;
3042         }
3043         OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
3044         *devAddr = *destination;
3045     }
3046
3047     if (devAddr)
3048     {
3049         OIC_LOG_V(INFO_PRIVATE, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
3050         if (!requestInfo.isMulticast)
3051         {
3052             OIC_LOG_V(DEBUG, TAG, "remoteAddr of devAddr : [%s]:[%d]",
3053                       devAddr->addr, devAddr->port);
3054         }
3055     }
3056
3057     resHandle = GenerateInvocationHandle();
3058     if (!resHandle)
3059     {
3060         result = OC_STACK_NO_MEMORY;
3061         goto exit;
3062     }
3063
3064     caResult = CAGenerateToken(&token, tokenLength);
3065     if (caResult != CA_STATUS_OK)
3066     {
3067         OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3068         result = CAResultToOCResult(caResult);
3069         goto exit;
3070     }
3071
3072     // fill in request data
3073     requestInfo.info.type = qualityOfServiceToMessageType(qos);
3074     requestInfo.info.token = token;
3075     requestInfo.info.tokenLength = tokenLength;
3076
3077     if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3078     {
3079         result = CreateObserveHeaderOption (&(requestInfo.info.options),
3080                                     options, numOptions, OC_OBSERVE_REGISTER);
3081         if (result != OC_STACK_OK)
3082         {
3083             goto exit;
3084         }
3085         requestInfo.info.numOptions = numOptions + 1;
3086     }
3087     else
3088     {
3089         requestInfo.info.numOptions = numOptions;
3090         requestInfo.info.options =
3091             (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3092         memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3093                numOptions * sizeof(CAHeaderOption_t));
3094     }
3095
3096     CopyDevAddrToEndpoint(devAddr, &endpoint);
3097
3098     if(payload)
3099     {
3100         if((result =
3101             OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3102                 != OC_STACK_OK)
3103         {
3104             OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3105             goto exit;
3106         }
3107         requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3108     }
3109     else
3110     {
3111         requestInfo.info.payload = NULL;
3112         requestInfo.info.payloadSize = 0;
3113         requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3114     }
3115
3116     // prepare for response
3117 #ifdef WITH_PRESENCE
3118     if (method == OC_REST_PRESENCE)
3119     {
3120         char *presenceUri = NULL;
3121         result = OCPreparePresence(&endpoint, &presenceUri,
3122                                    requestInfo.isMulticast);
3123         if (OC_STACK_OK != result)
3124         {
3125             goto exit;
3126         }
3127
3128         // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3129         // Presence notification will form a canonical uri to
3130         // look for callbacks into the application.
3131         if (resourceUri)
3132         {
3133             OICFree(resourceUri);
3134         }
3135         resourceUri = presenceUri;
3136     }
3137 #endif
3138
3139     // update resourceUri onto requestInfo after check presence uri
3140     requestInfo.info.resourceUri = resourceUri;
3141
3142     ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3143     result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3144                             method, devAddr, resourceUri, resourceType, ttl);
3145     if (OC_STACK_OK != result)
3146     {
3147         goto exit;
3148     }
3149
3150     cbData = NULL;        // Client CB list entry now owns it
3151     token = NULL;         // Client CB list entry now owns it
3152     devAddr = NULL;       // Client CB list entry now owns it
3153     resourceUri = NULL;   // Client CB list entry now owns it
3154     resourceType = NULL;  // Client CB list entry now owns it
3155
3156 #ifdef WITH_PRESENCE
3157     if (method == OC_REST_PRESENCE)
3158     {
3159         OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3160
3161         if (handle)
3162         {
3163             *handle = resHandle;
3164         }
3165 #ifdef WITH_PROCESS_EVENT
3166         OCSendProcessEventSignal();
3167 #endif // WITH_PROCESS_EVENT
3168
3169         goto exit;
3170     }
3171 #endif
3172
3173     // send request
3174     result = OCSendRequest(&endpoint, &requestInfo);
3175     if (OC_STACK_OK != result)
3176     {
3177         goto exit;
3178     }
3179
3180     if (handle)
3181     {
3182         *handle = resHandle;
3183     }
3184
3185 exit:
3186     if (result != OC_STACK_OK)
3187     {
3188         OIC_LOG(ERROR, TAG, "OCDoResource error");
3189         if (NULL != cbData && NULL != cbData->cd)
3190         {
3191             cbData->cd(cbData->context);
3192         }
3193         if (!clientCB)                 // token and resHandle associated with clientCB
3194         {
3195             CADestroyToken(token);
3196             OICFree(resHandle);
3197         }
3198         else
3199         {
3200             FindAndDeleteClientCB(clientCB);
3201         }
3202         if (handle)
3203         {
3204             *handle = NULL;
3205         }
3206     }
3207
3208     OICFree(requestInfo.info.payload);
3209     OICFree(devAddr);
3210     OICFree(resourceUri);
3211     OICFree(resourceType);
3212     OICFree(requestInfo.info.options);
3213     OIC_TRACE_END();
3214     return result;
3215 }
3216
3217 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3218         uint8_t numOptions)
3219 {
3220     /*
3221      * This ftn is implemented one of two ways in the case of observation:
3222      *
3223      * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3224      *      Remove the callback associated on client side.
3225      *      When the next notification comes in from server,
3226      *      reply with RESET message to server.
3227      *      Keep in mind that the server will react to RESET only
3228      *      if the last notification was sent as CON
3229      *
3230      * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3231      *      and it is associated with an observe request
3232      *      (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3233      *      Send CON Observe request to server with
3234      *      observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3235      *      Remove the callback associated on client side.
3236      */
3237     OCStackResult ret = OC_STACK_OK;
3238     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3239     CARequestInfo_t requestInfo = {.method = CA_GET};
3240
3241     if(!handle)
3242     {
3243         return OC_STACK_INVALID_PARAM;
3244     }
3245
3246     ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3247     if (!clientCB)
3248     {
3249         OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3250         return OC_STACK_ERROR;
3251     }
3252
3253     switch (clientCB->method)
3254     {
3255         case OC_REST_OBSERVE:
3256         case OC_REST_OBSERVE_ALL:
3257
3258             OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3259
3260             CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3261
3262             if (((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS) ||
3263                     ((endpoint.adapter & CA_ADAPTER_TCP) && OC_LOW_QOS_WITH_TCP == qos))
3264             {
3265                 OIC_LOG_V(INFO, TAG, "the %s observe callback is removed", clientCB->requestUri);
3266                 FindAndDeleteClientCB(clientCB);
3267                 break;
3268             }
3269
3270             OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3271
3272             requestInfo.info.type = qualityOfServiceToMessageType(qos);
3273             requestInfo.info.token = clientCB->token;
3274             requestInfo.info.tokenLength = clientCB->tokenLength;
3275
3276             if (CreateObserveHeaderOption (&(requestInfo.info.options),
3277                     options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3278             {
3279                 return OC_STACK_ERROR;
3280             }
3281             requestInfo.info.numOptions = numOptions + 1;
3282             requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3283
3284
3285             ret = OCSendRequest(&endpoint, &requestInfo);
3286
3287             if (requestInfo.info.options)
3288             {
3289                 OICFree (requestInfo.info.options);
3290             }
3291             if (requestInfo.info.resourceUri)
3292             {
3293                 OICFree (requestInfo.info.resourceUri);
3294             }
3295
3296             break;
3297
3298         case OC_REST_DISCOVER:
3299             OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3300                                            clientCB->requestUri);
3301             FindAndDeleteClientCB(clientCB);
3302             break;
3303
3304 #ifdef WITH_PRESENCE
3305         case OC_REST_PRESENCE:
3306             FindAndDeleteClientCB(clientCB);
3307             break;
3308 #endif
3309         case OC_REST_GET:
3310         case OC_REST_PUT:
3311         case OC_REST_POST:
3312         case OC_REST_DELETE:
3313             OIC_LOG_V(INFO, TAG, "Cancelling request callback for resource %s",
3314                                            clientCB->requestUri);
3315             FindAndDeleteClientCB(clientCB);
3316             break;
3317
3318         default:
3319             ret = OC_STACK_INVALID_METHOD;
3320             break;
3321     }
3322
3323     return ret;
3324 }
3325
3326 /**
3327  * @brief   Register Persistent storage callback.
3328  * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3329  * @return
3330  *     OC_STACK_OK    - No errors; Success
3331  *     OC_STACK_INVALID_PARAM - Invalid parameter
3332  */
3333 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3334 {
3335     OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3336     if(!persistentStorageHandler)
3337     {
3338         OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3339         return OC_STACK_INVALID_PARAM;
3340     }
3341     else
3342     {
3343         if( !persistentStorageHandler->open ||
3344                 !persistentStorageHandler->close ||
3345                 !persistentStorageHandler->read ||
3346                 !persistentStorageHandler->unlink ||
3347                 !persistentStorageHandler->write)
3348         {
3349             OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3350             return OC_STACK_INVALID_PARAM;
3351         }
3352     }
3353     return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3354 }
3355
3356 #ifdef WITH_PRESENCE
3357
3358 #ifdef WITH_PROCESS_EVENT
3359 OCStackResult OCProcessPresence(uint32_t *nextEventTime)
3360 #else   // WITH_PROCESS_EVENT
3361 OCStackResult OCProcessPresence(void)
3362 #endif  // !WITH_PROCESS_EVENT
3363 {
3364     OCStackResult result = OC_STACK_OK;
3365
3366     // the following line floods the log with messages that are irrelevant
3367     // to most purposes.  Uncomment as needed.
3368     //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3369     ClientCB* cbNode = NULL;
3370     ClientCB* tempcbNode = NULL;
3371     OCClientResponse clientResponse;
3372     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3373
3374     LL_FOREACH_SAFE(cbList, cbNode, tempcbNode)
3375     {
3376         if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3377         {
3378             continue;
3379         }
3380
3381         uint32_t now = GetTicks(0);
3382         OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3383                                                 cbNode->presence->TTLlevel);
3384         OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3385
3386         if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3387         {
3388             goto exit;
3389         }
3390
3391         if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3392         {
3393             OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3394                     cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3395         }
3396         if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3397         {
3398             OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3399
3400             clientResponse.sequenceNumber = 0;
3401             clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3402             clientResponse.devAddr = *cbNode->devAddr;
3403             FixUpClientResponse(&clientResponse);
3404             clientResponse.payload = NULL;
3405
3406             // Increment the TTLLevel (going to a next state), so we don't keep
3407             // sending presence notification to client.
3408             cbNode->presence->TTLlevel++;
3409             OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3410                                         cbNode->presence->TTLlevel);
3411
3412             OIC_LOG(INFO, TAG, "Before calling into application address space for presence timeout");
3413             cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3414             OIC_LOG(INFO, TAG, "After calling into application address space for presence timeout");
3415
3416             if (cbResult == OC_STACK_DELETE_TRANSACTION)
3417             {
3418                 FindAndDeleteClientCB(cbNode);
3419             }
3420             continue;
3421         }
3422
3423         uint32_t timeout = cbNode->presence->timeOut[cbNode->presence->TTLlevel];
3424         if (now < timeout)
3425         {
3426 #ifdef WITH_PROCESS_EVENT
3427             if (nextEventTime && (timeout - now) < *nextEventTime)
3428             {
3429                 *nextEventTime = timeout - now;
3430             }
3431 #endif // WITH_PROCESS_EVENT
3432             continue;
3433         }
3434
3435         CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3436         CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3437         CARequestInfo_t requestInfo = {.method = CA_GET};
3438
3439         OIC_LOG(DEBUG, TAG, "time to test server presence");
3440
3441         CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3442
3443         requestData.type = CA_MSG_NONCONFIRM;
3444         requestData.token = cbNode->token;
3445         requestData.tokenLength = cbNode->tokenLength;
3446         requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3447         requestInfo.method = CA_GET;
3448         requestInfo.info = requestData;
3449
3450         result = OCSendRequest(&endpoint, &requestInfo);
3451         if (OC_STACK_OK != result)
3452         {
3453             goto exit;
3454         }
3455
3456         cbNode->presence->TTLlevel++;
3457         OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3458     }
3459 exit:
3460     if (result != OC_STACK_OK)
3461     {
3462         OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3463     }
3464
3465     return result;
3466 }
3467 #endif // WITH_PRESENCE
3468
3469 #ifdef WITH_PROCESS_EVENT
3470 OCStackResult OCProcess(void)
3471 {
3472     uint32_t nextEventTime;
3473     return OCProcessEvent(&nextEventTime);
3474 }
3475
3476 OCStackResult OCProcessEvent(uint32_t *nextEventTime)
3477 {
3478     if (stackState == OC_STACK_UNINITIALIZED)
3479     {
3480         OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3481         return OC_STACK_ERROR;
3482     }
3483
3484     *nextEventTime = UINT32_MAX;
3485
3486 #ifdef WITH_PRESENCE
3487     OCProcessPresence(nextEventTime);
3488     OIC_LOG_V(INFO, TAG, "OCProcessPresence next event time : %u", *nextEventTime);
3489 #endif
3490     CAHandleRequestResponse();
3491
3492 // TODO
3493 #ifdef ROUTING_GATEWAY
3494     RMProcess(nextEventTime);
3495 #endif
3496
3497 #ifdef TCP_ADAPTER
3498     OCProcessKeepAlive(nextEventTime);
3499     OIC_LOG_V(INFO, TAG, "OCProcessKeepAlive next event time : %u", *nextEventTime);
3500 #endif
3501     return OC_STACK_OK;
3502 }
3503
3504 void OCRegisterProcessEvent(oc_event event)
3505 {
3506     g_ocProcessEvent = event;
3507     CARegisterProcessEvent(event);
3508 }
3509
3510 void OCSendProcessEventSignal(void)
3511 {
3512     if (g_ocProcessEvent)
3513     {
3514         oc_event_signal(g_ocProcessEvent);
3515     }
3516 }
3517 #else // WITH_PROCESS_EVENT
3518
3519 OCStackResult OCProcess()
3520 {
3521     if (stackState == OC_STACK_UNINITIALIZED)
3522     {
3523         OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3524         return OC_STACK_ERROR;
3525     }
3526 #ifdef WITH_PRESENCE
3527     OCProcessPresence();
3528 #endif
3529     CAHandleRequestResponse();
3530
3531 #ifdef ROUTING_GATEWAY
3532     RMProcess();
3533 #endif
3534
3535 #ifdef TCP_ADAPTER
3536     OCProcessKeepAlive();
3537 #endif
3538     return OC_STACK_OK;
3539 }
3540 #endif // !WITH_PROCESS_EVENT
3541
3542 #ifdef WITH_PRESENCE
3543 OCStackResult OCStartPresence(const uint32_t ttl)
3544 {
3545     OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3546     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3547     OCChangeResourceProperty(
3548             &(((OCResource *)presenceResource.handle)->resourceProperties),
3549             OC_ACTIVE, 1);
3550
3551     if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3552     {
3553         presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3554         OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3555     }
3556     else if (0 == ttl)
3557     {
3558         presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3559         OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3560     }
3561     else
3562     {
3563         presenceResource.presenceTTL = ttl;
3564     }
3565 #ifndef __TIZENRT__
3566     OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3567 #endif
3568
3569     if (OC_PRESENCE_UNINITIALIZED == presenceState)
3570     {
3571         presenceState = OC_PRESENCE_INITIALIZED;
3572
3573         OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3574
3575         CAToken_t caToken = NULL;
3576         CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3577         if (caResult != CA_STATUS_OK)
3578         {
3579             OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3580             CADestroyToken(caToken);
3581             return OC_STACK_ERROR;
3582         }
3583
3584         AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3585                 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3586         CADestroyToken(caToken);
3587     }
3588
3589     // Each time OCStartPresence is called
3590     // a different random 32-bit integer number is used
3591     ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3592
3593     return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3594             OC_PRESENCE_TRIGGER_CREATE);
3595 }
3596
3597 OCStackResult OCStopPresence()
3598 {
3599     OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3600     OCStackResult result = OC_STACK_ERROR;
3601
3602     if(presenceResource.handle)
3603     {
3604         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3605
3606     // make resource inactive
3607     result = OCChangeResourceProperty(
3608             &(((OCResource *) presenceResource.handle)->resourceProperties),
3609             OC_ACTIVE, 0);
3610     }
3611
3612     if(result != OC_STACK_OK)
3613     {
3614         OIC_LOG(ERROR, TAG,
3615                       "Changing the presence resource properties to ACTIVE not successful");
3616         return result;
3617     }
3618
3619     return SendStopNotification();
3620 }
3621 #endif
3622
3623 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3624                                             void* callbackParameter)
3625 {
3626     defaultDeviceHandler = entityHandler;
3627     defaultDeviceHandlerCallbackParameter = callbackParameter;
3628
3629     return OC_STACK_OK;
3630 }
3631
3632 OCStackResult OCCreateResource(OCResourceHandle *handle,
3633         const char *resourceTypeName,
3634         const char *resourceInterfaceName,
3635         const char *uri, OCEntityHandler entityHandler,
3636         void* callbackParam,
3637         uint8_t resourceProperties)
3638 {
3639
3640     OCResource *pointer = NULL;
3641     OCStackResult result = OC_STACK_ERROR;
3642
3643     OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3644
3645     if(myStackMode == OC_CLIENT)
3646     {
3647         return OC_STACK_INVALID_PARAM;
3648     }
3649     // Validate parameters
3650     if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3651     {
3652         OIC_LOG(ERROR, TAG, "URI is empty or too long");
3653         return OC_STACK_INVALID_URI;
3654     }
3655     // Is it presented during resource discovery?
3656     if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3657     {
3658         OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3659         return OC_STACK_INVALID_PARAM;
3660     }
3661
3662     if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3663     {
3664         resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3665     }
3666
3667 #ifdef MQ_PUBLISHER
3668     resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3669 #endif
3670     // Make sure resourceProperties bitmask has allowed properties specified
3671     if (resourceProperties
3672             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3673                OC_EXPLICIT_DISCOVERABLE
3674 #ifdef MQ_PUBLISHER
3675                | OC_MQ_PUBLISHER
3676 #endif
3677 #ifdef MQ_BROKER
3678                | OC_MQ_BROKER
3679 #endif
3680                ))
3681     {
3682         OIC_LOG(ERROR, TAG, "Invalid property");
3683         return OC_STACK_INVALID_PARAM;
3684     }
3685
3686     // If the headResource is NULL, then no resources have been created...
3687     pointer = headResource;
3688     if (pointer)
3689     {
3690         // At least one resources is in the resource list, so we need to search for
3691         // repeated URLs, which are not allowed.  If a repeat is found, exit with an error
3692         while (pointer)
3693         {
3694             if (pointer->uri && strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3695             {
3696                 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3697                 return OC_STACK_INVALID_PARAM;
3698             }
3699             pointer = pointer->next;
3700         }
3701     }
3702     // Create the pointer and insert it into the resource list
3703     pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3704     if (!pointer)
3705     {
3706         result = OC_STACK_NO_MEMORY;
3707         goto exit;
3708     }
3709     pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3710
3711     insertResource(pointer);
3712
3713     // Set the uri
3714     pointer->uri = OICStrdup(uri);
3715     if (!pointer->uri)
3716     {
3717         result = OC_STACK_NO_MEMORY;
3718         goto exit;
3719     }
3720
3721     // Set properties.  Set OC_ACTIVE
3722     pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3723             | OC_ACTIVE);
3724
3725     // Add the resourcetype to the resource
3726     result = BindResourceTypeToResource(pointer, resourceTypeName);
3727     if (result != OC_STACK_OK)
3728     {
3729         OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3730         goto exit;
3731     }
3732
3733     // Add the resourceinterface to the resource
3734     result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3735     if (result != OC_STACK_OK)
3736     {
3737         OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3738         goto exit;
3739     }
3740
3741     // If an entity handler has been passed, attach it to the newly created
3742     // resource.  Otherwise, set the default entity handler.
3743     if (entityHandler)
3744     {
3745         pointer->entityHandler = entityHandler;
3746         pointer->entityHandlerCallbackParam = callbackParam;
3747     }
3748     else
3749     {
3750         pointer->entityHandler = defaultResourceEHandler;
3751         pointer->entityHandlerCallbackParam = NULL;
3752     }
3753
3754     // Initialize a pointer indicating child resources in case of collection
3755     pointer->rsrcChildResourcesHead = NULL;
3756
3757     *handle = pointer;
3758     result = OC_STACK_OK;
3759
3760 #ifdef WITH_PRESENCE
3761     if (presenceResource.handle)
3762     {
3763         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3764         SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3765     }
3766 #endif
3767 exit:
3768     if (result != OC_STACK_OK)
3769     {
3770         // Deep delete of resource and other dynamic elements that it contains
3771         deleteResource(pointer);
3772     }
3773     return result;
3774 }
3775
3776 OCStackResult OCBindResource(
3777         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3778 {
3779     OCResource *resource = NULL;
3780     OCChildResource *tempChildResource = NULL;
3781     OCChildResource *newChildResource = NULL;
3782
3783     OIC_LOG(INFO, TAG, "Entering OCBindResource");
3784
3785     // Validate parameters
3786     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3787     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3788     // Container cannot contain itself
3789     if (collectionHandle == resourceHandle)
3790     {
3791         OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3792         return OC_STACK_INVALID_PARAM;
3793     }
3794
3795     // Use the handle to find the resource in the resource linked list
3796     resource = findResource((OCResource *) collectionHandle);
3797     if (!resource)
3798     {
3799         OIC_LOG(ERROR, TAG, "Collection handle not found");
3800         return OC_STACK_INVALID_PARAM;
3801     }
3802
3803     // Look for an open slot to add add the child resource.
3804     // If found, add it and return success
3805
3806     tempChildResource = resource->rsrcChildResourcesHead;
3807
3808     while(resource->rsrcChildResourcesHead && tempChildResource->next)
3809     {
3810         // TODO: what if one of child resource was deregistered without unbinding?
3811         tempChildResource = tempChildResource->next;
3812     }
3813
3814     // Do memory allocation for child resource
3815     newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3816     if(!newChildResource)
3817     {
3818         OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3819         return OC_STACK_ERROR;
3820     }
3821
3822     newChildResource->rsrcResource = (OCResource *) resourceHandle;
3823     newChildResource->next = NULL;
3824
3825     if(!resource->rsrcChildResourcesHead)
3826     {
3827         resource->rsrcChildResourcesHead = newChildResource;
3828     }
3829     else {
3830         tempChildResource->next = newChildResource;
3831     }
3832
3833     OIC_LOG(INFO, TAG, "resource bound");
3834
3835 #ifdef WITH_PRESENCE
3836     if (presenceResource.handle)
3837     {
3838         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3839         SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3840                 OC_PRESENCE_TRIGGER_CHANGE);
3841     }
3842 #endif
3843
3844     return OC_STACK_OK;
3845 }
3846
3847 OCStackResult OCUnBindResource(
3848         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3849 {
3850     OCResource *resource = NULL;
3851     OCChildResource *tempChildResource = NULL;
3852     OCChildResource *tempLastChildResource = NULL;
3853
3854     OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3855
3856     // Validate parameters
3857     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3858     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3859     // Container cannot contain itself
3860     if (collectionHandle == resourceHandle)
3861     {
3862         OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3863         return OC_STACK_INVALID_PARAM;
3864     }
3865
3866     // Use the handle to find the resource in the resource linked list
3867     resource = findResource((OCResource *) collectionHandle);
3868     if (!resource)
3869     {
3870         OIC_LOG(ERROR, TAG, "Collection handle not found");
3871         return OC_STACK_INVALID_PARAM;
3872     }
3873
3874     // Look for an open slot to add add the child resource.
3875     // If found, add it and return success
3876     if(!resource->rsrcChildResourcesHead)
3877     {
3878         OIC_LOG(INFO, TAG, "resource not found in collection");
3879
3880         // Unable to add resourceHandle, so return error
3881         return OC_STACK_ERROR;
3882
3883     }
3884
3885     tempChildResource = resource->rsrcChildResourcesHead;
3886
3887     while (tempChildResource)
3888     {
3889         if(tempChildResource->rsrcResource == resourceHandle)
3890         {
3891             // if resource going to be unbinded is the head one.
3892             if( tempChildResource == resource->rsrcChildResourcesHead )
3893             {
3894                 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3895                 OICFree(resource->rsrcChildResourcesHead);
3896                 resource->rsrcChildResourcesHead = temp;
3897                 temp = NULL;
3898             }
3899             else
3900             {
3901                 OCChildResource *temp = tempChildResource->next;
3902                 OICFree(tempChildResource);
3903                 if (tempLastChildResource)
3904                 {
3905                     tempLastChildResource->next = temp;
3906                     temp = NULL;
3907                 }
3908             }
3909
3910             OIC_LOG(INFO, TAG, "resource unbound");
3911
3912             // Send notification when resource is unbounded successfully.
3913 #ifdef WITH_PRESENCE
3914             if (presenceResource.handle)
3915             {
3916                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3917                 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3918                         OC_PRESENCE_TRIGGER_CHANGE);
3919             }
3920 #endif
3921             tempChildResource = NULL;
3922             tempLastChildResource = NULL;
3923
3924             return OC_STACK_OK;
3925
3926         }
3927
3928         tempLastChildResource = tempChildResource;
3929         tempChildResource = tempChildResource->next;
3930     }
3931
3932     OIC_LOG(INFO, TAG, "resource not found in collection");
3933
3934     tempChildResource = NULL;
3935     tempLastChildResource = NULL;
3936
3937     // Unable to add resourceHandle, so return error
3938     return OC_STACK_ERROR;
3939 }
3940
3941 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3942 {
3943     if (!resourceItemName)
3944     {
3945         return false;
3946     }
3947     // Per RFC 6690 only registered values must follow the first rule below.
3948     // At this point in time the only values registered begin with "core", and
3949     // all other values are specified as opaque strings where multiple values
3950     // are separated by a space.
3951     if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3952     {
3953         for(size_t index = sizeof(CORESPEC) - 1;  resourceItemName[index]; ++index)
3954         {
3955             if (resourceItemName[index] != '.'
3956                 && resourceItemName[index] != '-'
3957                 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3958                 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3959             {
3960                 return false;
3961             }
3962         }
3963     }
3964     else
3965     {
3966         for (size_t index = 0; resourceItemName[index]; ++index)
3967         {
3968             if (resourceItemName[index] == ' '
3969                 || resourceItemName[index] == '\t'
3970                 || resourceItemName[index] == '\r'
3971                 || resourceItemName[index] == '\n')
3972             {
3973                 return false;
3974             }
3975         }
3976     }
3977
3978     return true;
3979 }
3980
3981 OCStackResult BindResourceTypeToResource(OCResource* resource,
3982                                             const char *resourceTypeName)
3983 {
3984     OCResourceType *pointer = NULL;
3985     char *str = NULL;
3986     OCStackResult result = OC_STACK_ERROR;
3987
3988     VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3989
3990     if (!ValidateResourceTypeInterface(resourceTypeName))
3991     {
3992         OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3993         return OC_STACK_INVALID_PARAM;
3994     }
3995
3996     pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3997     if (!pointer)
3998     {
3999         result = OC_STACK_NO_MEMORY;
4000         goto exit;
4001     }
4002
4003     str = OICStrdup(resourceTypeName);
4004     if (!str)
4005     {
4006         result = OC_STACK_NO_MEMORY;
4007         goto exit;
4008     }
4009     pointer->resourcetypename = str;
4010     pointer->next = NULL;
4011
4012     insertResourceType(resource, pointer);
4013     result = OC_STACK_OK;
4014
4015 exit:
4016     if (result != OC_STACK_OK)
4017     {
4018         OICFree(pointer);
4019         OICFree(str);
4020     }
4021
4022     return result;
4023 }
4024
4025 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
4026         const char *resourceInterfaceName)
4027 {
4028     OCResourceInterface *pointer = NULL;
4029     char *str = NULL;
4030     OCStackResult result = OC_STACK_ERROR;
4031
4032     VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
4033
4034     if (!ValidateResourceTypeInterface(resourceInterfaceName))
4035     {
4036         OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
4037         return OC_STACK_INVALID_PARAM;
4038     }
4039
4040     OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
4041
4042     pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
4043     if (!pointer)
4044     {
4045         result = OC_STACK_NO_MEMORY;
4046         goto exit;
4047     }
4048
4049     str = OICStrdup(resourceInterfaceName);
4050     if (!str)
4051     {
4052         result = OC_STACK_NO_MEMORY;
4053         goto exit;
4054     }
4055     pointer->name = str;
4056
4057     // Bind the resourceinterface to the resource
4058     insertResourceInterface(resource, pointer);
4059
4060     result = OC_STACK_OK;
4061
4062     exit:
4063     if (result != OC_STACK_OK)
4064     {
4065         OICFree(pointer);
4066         OICFree(str);
4067     }
4068
4069     return result;
4070 }
4071
4072 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
4073         const char *resourceTypeName)
4074 {
4075
4076     OCStackResult result = OC_STACK_ERROR;
4077     OCResource *resource = NULL;
4078
4079     resource = findResource((OCResource *) handle);
4080     if (!resource)
4081     {
4082         OIC_LOG(ERROR, TAG, "Resource not found");
4083         return OC_STACK_ERROR;
4084     }
4085
4086     result = BindResourceTypeToResource(resource, resourceTypeName);
4087
4088 #ifdef WITH_PRESENCE
4089     if(presenceResource.handle)
4090     {
4091         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4092         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4093     }
4094 #endif
4095
4096     return result;
4097 }
4098
4099 OCStackResult OCResetResourceTypes(OCResourceHandle handle,
4100                                    const char *newResourceType)
4101 {
4102     OCStackResult result = OC_STACK_ERROR;
4103     OCResource *resource = NULL;
4104
4105     resource = findResource((OCResource *) handle);
4106     if (!resource)
4107     {
4108         OIC_LOG(ERROR, TAG, "Resource not found");
4109         return OC_STACK_ERROR;
4110     }
4111
4112     // Clear all bound resource types
4113     deleteResourceType(resource->rsrcType);
4114     resource->rsrcType = NULL;
4115
4116     // Bind new resource type to resource
4117     result = BindResourceTypeToResource(resource, newResourceType);
4118
4119 #ifdef WITH_PRESENCE
4120     if(presenceResource.handle)
4121     {
4122         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4123         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4124     }
4125 #endif
4126
4127     return result;
4128 }
4129
4130 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
4131         const char *resourceInterfaceName)
4132 {
4133
4134     OCStackResult result = OC_STACK_ERROR;
4135     OCResource *resource = NULL;
4136
4137     resource = findResource((OCResource *) handle);
4138     if (!resource)
4139     {
4140         OIC_LOG(ERROR, TAG, "Resource not found");
4141         return OC_STACK_ERROR;
4142     }
4143
4144     result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
4145
4146 #ifdef WITH_PRESENCE
4147     if (presenceResource.handle)
4148     {
4149         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4150         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4151     }
4152 #endif
4153
4154     return result;
4155 }
4156
4157 OCStackResult OCResetResourceInterfaces(OCResourceHandle handle,
4158                                         const char *newResourceInterface)
4159 {
4160     OCStackResult result = OC_STACK_ERROR;
4161     OCResource *resource = NULL;
4162
4163     resource = findResource((OCResource *) handle);
4164     if (!resource)
4165     {
4166         OIC_LOG(ERROR, TAG, "Resource not found");
4167         return OC_STACK_ERROR;
4168     }
4169
4170     // Clear all bound interface
4171     deleteResourceInterface(resource->rsrcInterface);
4172     resource->rsrcInterface = NULL;
4173
4174     // Bind new interface to resource
4175     result = BindResourceInterfaceToResource(resource, newResourceInterface);
4176
4177 #ifdef WITH_PRESENCE
4178     if (presenceResource.handle)
4179     {
4180         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4181         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4182     }
4183 #endif
4184
4185     return result;
4186 }
4187
4188 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
4189 {
4190     OCResource *pointer = headResource;
4191
4192     VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
4193     *numResources = 0;
4194     while (pointer)
4195     {
4196         *numResources = *numResources + 1;
4197         pointer = pointer->next;
4198     }
4199     return OC_STACK_OK;
4200 }
4201
4202 OCResourceHandle OCGetResourceHandle(uint8_t index)
4203 {
4204     OCResource *pointer = headResource;
4205
4206     for( uint8_t i = 0; i < index && pointer; ++i)
4207     {
4208         pointer = pointer->next;
4209     }
4210     return (OCResourceHandle) pointer;
4211 }
4212
4213 OCStackResult OCDeleteResource(OCResourceHandle handle)
4214 {
4215     if (!handle)
4216     {
4217         OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4218         return OC_STACK_INVALID_PARAM;
4219     }
4220
4221     OCResource *resource = findResource((OCResource *) handle);
4222     if (resource == NULL)
4223     {
4224         OIC_LOG(ERROR, TAG, "Resource not found");
4225         return OC_STACK_NO_RESOURCE;
4226     }
4227
4228     if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4229     {
4230         OIC_LOG(ERROR, TAG, "Error deleting resource");
4231         return OC_STACK_ERROR;
4232     }
4233
4234     return OC_STACK_OK;
4235 }
4236
4237 const char *OCGetResourceUri(OCResourceHandle handle)
4238 {
4239     OCResource *resource = NULL;
4240
4241     resource = findResource((OCResource *) handle);
4242     if (resource)
4243     {
4244         return resource->uri;
4245     }
4246     return (const char *) NULL;
4247 }
4248
4249 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4250 {
4251     OCResource *resource = NULL;
4252
4253     resource = findResource((OCResource *) handle);
4254     if (resource)
4255     {
4256         return resource->resourceProperties;
4257     }
4258     return (OCResourceProperty)-1;
4259 }
4260
4261 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4262         uint8_t *numResourceTypes)
4263 {
4264     OCResource *resource = NULL;
4265     OCResourceType *pointer = NULL;
4266
4267     VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4268     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4269
4270     *numResourceTypes = 0;
4271
4272     resource = findResource((OCResource *) handle);
4273     if (resource)
4274     {
4275         pointer = resource->rsrcType;
4276         while (pointer)
4277         {
4278             *numResourceTypes = *numResourceTypes + 1;
4279             pointer = pointer->next;
4280         }
4281     }
4282     return OC_STACK_OK;
4283 }
4284
4285 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4286 {
4287     OCResourceType *resourceType = NULL;
4288
4289     resourceType = findResourceTypeAtIndex(handle, index);
4290     if (resourceType)
4291     {
4292         return resourceType->resourcetypename;
4293     }
4294     return (const char *) NULL;
4295 }
4296
4297 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4298         uint8_t *numResourceInterfaces)
4299 {
4300     OCResourceInterface *pointer = NULL;
4301     OCResource *resource = NULL;
4302
4303     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4304     VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4305
4306     *numResourceInterfaces = 0;
4307     resource = findResource((OCResource *) handle);
4308     if (resource)
4309     {
4310         pointer = resource->rsrcInterface;
4311         while (pointer)
4312         {
4313             *numResourceInterfaces = *numResourceInterfaces + 1;
4314             pointer = pointer->next;
4315         }
4316     }
4317     return OC_STACK_OK;
4318 }
4319
4320 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4321 {
4322     OCResourceInterface *resourceInterface = NULL;
4323
4324     resourceInterface = findResourceInterfaceAtIndex(handle, index);
4325     if (resourceInterface)
4326     {
4327         return resourceInterface->name;
4328     }
4329     return (const char *) NULL;
4330 }
4331
4332 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4333         uint8_t index)
4334 {
4335     OCResource *resource = NULL;
4336     OCChildResource *tempChildResource = NULL;
4337     uint8_t num = 0;
4338
4339     resource = findResource((OCResource *) collectionHandle);
4340     if (!resource)
4341     {
4342         return NULL;
4343     }
4344
4345     tempChildResource = resource->rsrcChildResourcesHead;
4346
4347     while(tempChildResource)
4348     {
4349         if( num == index )
4350         {
4351             return tempChildResource->rsrcResource;
4352         }
4353         num++;
4354         tempChildResource = tempChildResource->next;
4355     }
4356
4357     // In this case, the number of resource handles in the collection exceeds the index
4358     tempChildResource = NULL;
4359     return NULL;
4360 }
4361
4362 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4363         OCEntityHandler entityHandler,
4364         void* callbackParam)
4365 {
4366     OCResource *resource = NULL;
4367
4368     // Validate parameters
4369     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4370
4371     // Use the handle to find the resource in the resource linked list
4372     resource = findResource((OCResource *)handle);
4373     if (!resource)
4374     {
4375         OIC_LOG(ERROR, TAG, "Resource not found");
4376         return OC_STACK_ERROR;
4377     }
4378
4379     // Bind the handler
4380     resource->entityHandler = entityHandler;
4381     resource->entityHandlerCallbackParam = callbackParam;
4382
4383 #ifdef WITH_PRESENCE
4384     if (presenceResource.handle)
4385     {
4386         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4387         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4388     }
4389 #endif
4390
4391     return OC_STACK_OK;
4392 }
4393
4394 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4395 {
4396     OCResource *resource = NULL;
4397
4398     resource = findResource((OCResource *)handle);
4399     if (!resource)
4400     {
4401         OIC_LOG(ERROR, TAG, "Resource not found");
4402         return NULL;
4403     }
4404
4405     // Bind the handler
4406     return resource->entityHandler;
4407 }
4408
4409 void incrementSequenceNumber(OCResource * resPtr)
4410 {
4411     // Increment the sequence number
4412     resPtr->sequenceNum += 1;
4413     if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4414     {
4415         resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4416     }
4417     return;
4418 }
4419
4420 #ifdef WITH_PRESENCE
4421 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4422         OCPresenceTrigger trigger)
4423 {
4424     OIC_LOG(INFO, TAG, "SendPresenceNotification");
4425     OCResource *resPtr = NULL;
4426     OCStackResult result = OC_STACK_ERROR;
4427     OCMethod method = OC_REST_PRESENCE;
4428     uint32_t maxAge = 0;
4429     resPtr = findResource((OCResource *) presenceResource.handle);
4430     if(NULL == resPtr)
4431     {
4432         return OC_STACK_NO_RESOURCE;
4433     }
4434
4435     if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4436     {
4437         maxAge = presenceResource.presenceTTL;
4438
4439         result = SendAllObserverNotification(method, resPtr, maxAge,
4440                 trigger, resourceType, OC_LOW_QOS);
4441     }
4442
4443     return result;
4444 }
4445
4446 OCStackResult SendStopNotification()
4447 {
4448     OIC_LOG(INFO, TAG, "SendStopNotification");
4449     OCResource *resPtr = NULL;
4450     OCStackResult result = OC_STACK_ERROR;
4451     OCMethod method = OC_REST_PRESENCE;
4452     resPtr = findResource((OCResource *) presenceResource.handle);
4453     if(NULL == resPtr)
4454     {
4455         return OC_STACK_NO_RESOURCE;
4456     }
4457
4458     // maxAge is 0. ResourceType is NULL.
4459     result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4460             NULL, OC_LOW_QOS);
4461
4462     return result;
4463 }
4464
4465 #endif // WITH_PRESENCE
4466 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4467 {
4468     OCResource *resPtr = NULL;
4469     OCStackResult result = OC_STACK_ERROR;
4470     OCMethod method = OC_REST_NOMETHOD;
4471     uint32_t maxAge = 0;
4472
4473     OIC_LOG(INFO, TAG, "Notifying all observers");
4474 #ifdef WITH_PRESENCE
4475     if(handle == presenceResource.handle)
4476     {
4477         return OC_STACK_OK;
4478     }
4479 #endif // WITH_PRESENCE
4480     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4481
4482     // Verify that the resource exists
4483     resPtr = findResource ((OCResource *) handle);
4484     if (NULL == resPtr)
4485     {
4486         return OC_STACK_NO_RESOURCE;
4487     }
4488     else
4489     {
4490         //only increment in the case of regular observing (not presence)
4491         incrementSequenceNumber(resPtr);
4492         method = OC_REST_OBSERVE;
4493         maxAge = MAX_OBSERVE_AGE;
4494 #ifdef WITH_PRESENCE
4495         result = SendAllObserverNotification (method, resPtr, maxAge,
4496                 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4497 #else
4498         result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4499 #endif
4500         return result;
4501     }
4502 }
4503
4504 OCStackResult
4505 OCNotifyListOfObservers (OCResourceHandle handle,
4506                          OCObservationId  *obsIdList,
4507                          uint8_t          numberOfIds,
4508                          const OCRepPayload       *payload,
4509                          OCQualityOfService qos)
4510 {
4511     OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4512
4513     OCResource *resPtr = NULL;
4514     //TODO: we should allow the server to define this
4515     uint32_t maxAge = MAX_OBSERVE_AGE;
4516
4517     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4518     VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4519     VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4520
4521     resPtr = findResource ((OCResource *) handle);
4522     if (NULL == resPtr || myStackMode == OC_CLIENT)
4523     {
4524         return OC_STACK_NO_RESOURCE;
4525     }
4526     else
4527     {
4528         incrementSequenceNumber(resPtr);
4529     }
4530     return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4531             payload, maxAge, qos));
4532 }
4533
4534 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4535 {
4536     OIC_TRACE_BEGIN(%s:OCDoResponse, TAG);
4537     OCStackResult result = OC_STACK_ERROR;
4538     OCServerRequest *serverRequest = NULL;
4539
4540     OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4541
4542     // Validate input parameters
4543     VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4544     VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4545
4546     // Normal response
4547     // Get pointer to request info
4548     serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
4549     if(serverRequest)
4550     {
4551         // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4552         result = serverRequest->ehResponseHandler(ehResponse);
4553     }
4554
4555     OIC_TRACE_END();
4556     return result;
4557 }
4558
4559 //#ifdef DIRECT_PAIRING
4560 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4561 {
4562     OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4563     if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4564     {
4565         OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4566         return NULL;
4567     }
4568
4569     return (const OCDPDev_t*)DPGetDiscoveredDevices();
4570 }
4571
4572 const OCDPDev_t* OCGetDirectPairedDevices()
4573 {
4574     return (const OCDPDev_t*)DPGetPairedDevices();
4575 }
4576
4577 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4578                                                      OCDirectPairingCB resultCallback)
4579 {
4580     OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4581     if(NULL ==  peer || NULL == pinNumber)
4582     {
4583         OIC_LOG(ERROR, TAG, "Invalid parameters");
4584         return OC_STACK_INVALID_PARAM;
4585     }
4586     if (NULL == resultCallback)
4587     {
4588         OIC_LOG(ERROR, TAG, "Invalid callback");
4589         return OC_STACK_INVALID_CALLBACK;
4590     }
4591
4592     return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4593                                            pinNumber, (OCDirectPairingResultCB)resultCallback);
4594 }
4595 //#endif // DIRECT_PAIRING
4596
4597 //-----------------------------------------------------------------------------
4598 // Private internal function definitions
4599 //-----------------------------------------------------------------------------
4600 static OCDoHandle GenerateInvocationHandle()
4601 {
4602     OCDoHandle handle = NULL;
4603     // Generate token here, it will be deleted when the transaction is deleted
4604     handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4605     if (handle)
4606     {
4607         OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4608     }
4609
4610     return handle;
4611 }
4612
4613 #ifdef WITH_PRESENCE
4614 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4615         OCResourceProperty resourceProperties, uint8_t enable)
4616 {
4617     if (!inputProperty)
4618     {
4619         return OC_STACK_INVALID_PARAM;
4620     }
4621     if (resourceProperties
4622             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4623     {
4624         OIC_LOG(ERROR, TAG, "Invalid property");
4625         return OC_STACK_INVALID_PARAM;
4626     }
4627     if(!enable)
4628     {
4629         *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4630     }
4631     else
4632     {
4633         *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4634     }
4635     return OC_STACK_OK;
4636 }
4637 #endif
4638
4639 OCStackResult initResources()
4640 {
4641     OCStackResult result = OC_STACK_OK;
4642
4643     headResource = NULL;
4644     tailResource = NULL;
4645     // Init Virtual Resources
4646 #ifdef WITH_PRESENCE
4647     presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4648
4649     result = OCCreateResource(&presenceResource.handle,
4650             OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4651             "core.r",
4652             OC_RSRVD_PRESENCE_URI,
4653             NULL,
4654             NULL,
4655             OC_OBSERVABLE);
4656     //make resource inactive
4657     result = OCChangeResourceProperty(
4658             &(((OCResource *) presenceResource.handle)->resourceProperties),
4659             OC_ACTIVE, 0);
4660 #endif
4661 #ifndef WITH_ARDUINO
4662     if (result == OC_STACK_OK)
4663     {
4664         result = SRMInitSecureResources();
4665     }
4666 #endif
4667
4668     if(result == OC_STACK_OK)
4669     {
4670         CreateResetProfile();
4671         result = OCCreateResource(&deviceResource,
4672                                   OC_RSRVD_RESOURCE_TYPE_DEVICE,
4673                                   OC_RSRVD_INTERFACE_DEFAULT,
4674                                   OC_RSRVD_DEVICE_URI,
4675                                   NULL,
4676                                   NULL,
4677                                   OC_DISCOVERABLE);
4678         if(result == OC_STACK_OK)
4679         {
4680             result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4681                                                      OC_RSRVD_INTERFACE_READ);
4682         }
4683     }
4684
4685     if(result == OC_STACK_OK)
4686     {
4687         result = OCCreateResource(&platformResource,
4688                                   OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4689                                   OC_RSRVD_INTERFACE_DEFAULT,
4690                                   OC_RSRVD_PLATFORM_URI,
4691                                   NULL,
4692                                   NULL,
4693                                   OC_DISCOVERABLE);
4694         if(result == OC_STACK_OK)
4695         {
4696             result = BindResourceInterfaceToResource((OCResource *)platformResource,
4697                                                      OC_RSRVD_INTERFACE_READ);
4698         }
4699     }
4700
4701     return result;
4702 }
4703
4704 void insertResource(OCResource *resource)
4705 {
4706     if (!headResource)
4707     {
4708         headResource = resource;
4709         tailResource = resource;
4710     }
4711     else
4712     {
4713         tailResource->next = resource;
4714         tailResource = resource;
4715     }
4716     resource->next = NULL;
4717 }
4718
4719 OCResource *findResource(OCResource *resource)
4720 {
4721     OCResource *pointer = headResource;
4722
4723     while (pointer)
4724     {
4725         if (pointer == resource)
4726         {
4727             return resource;
4728         }
4729         pointer = pointer->next;
4730     }
4731     return NULL;
4732 }
4733
4734 void deleteAllResources()
4735 {
4736     OCResource *pointer = headResource;
4737     OCResource *temp = NULL;
4738
4739     while (pointer)
4740     {
4741         temp = pointer->next;
4742 #ifdef WITH_PRESENCE
4743         if (pointer != (OCResource *) presenceResource.handle)
4744         {
4745 #endif // WITH_PRESENCE
4746             deleteResource(pointer);
4747 #ifdef WITH_PRESENCE
4748         }
4749 #endif // WITH_PRESENCE
4750         pointer = temp;
4751     }
4752     memset(&platformResource, 0, sizeof(platformResource));
4753     memset(&deviceResource, 0, sizeof(deviceResource));
4754 #ifdef MQ_BROKER
4755     memset(&brokerResource, 0, sizeof(brokerResource));
4756 #endif
4757
4758     SRMDeInitSecureResources();
4759
4760 #ifdef WITH_PRESENCE
4761     // Ensure that the last resource to be deleted is the presence resource. This allows for all
4762     // presence notification attributed to their deletion to be processed.
4763     deleteResource((OCResource *) presenceResource.handle);
4764     memset(&presenceResource, 0, sizeof(presenceResource));
4765 #endif // WITH_PRESENCE
4766 }
4767
4768 OCStackResult deleteResource(OCResource *resource)
4769 {
4770     OCResource *prev = NULL;
4771     OCResource *temp = NULL;
4772     if(!resource)
4773     {
4774         OIC_LOG(DEBUG,TAG,"resource is NULL");
4775         return OC_STACK_INVALID_PARAM;
4776     }
4777
4778     OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4779
4780     temp = headResource;
4781     while (temp)
4782     {
4783         if (temp == resource)
4784         {
4785             // Invalidate all Resource Properties.
4786             resource->resourceProperties = (OCResourceProperty) 0;
4787 #ifdef WITH_PRESENCE
4788             if(resource != (OCResource *) presenceResource.handle)
4789             {
4790 #endif // WITH_PRESENCE
4791                 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4792 #ifdef WITH_PRESENCE
4793             }
4794
4795             if(presenceResource.handle)
4796             {
4797                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4798                 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4799             }
4800 #endif
4801             // Delete resource's all observers
4802             DeleteObserverUsingResource(resource);
4803
4804             // Only resource in list.
4805             if (temp == headResource && temp == tailResource)
4806             {
4807                 headResource = NULL;
4808                 tailResource = NULL;
4809             }
4810             // Deleting head.
4811             else if (temp == headResource)
4812             {
4813                 headResource = temp->next;
4814             }
4815             // Deleting tail.
4816             else if (temp == tailResource && prev)
4817             {
4818                 tailResource = prev;
4819                 tailResource->next = NULL;
4820             }
4821             else if (prev)
4822             {
4823                 prev->next = temp->next;
4824             }
4825
4826             deleteResourceElements(temp);
4827             OICFree(temp);
4828             return OC_STACK_OK;
4829         }
4830         else
4831         {
4832             prev = temp;
4833             temp = temp->next;
4834         }
4835     }
4836
4837     return OC_STACK_ERROR;
4838 }
4839
4840 void deleteResourceElements(OCResource *resource)
4841 {
4842     if (!resource)
4843     {
4844         return;
4845     }
4846
4847     if (resource->uri)
4848     {
4849         OICFree(resource->uri);
4850         resource->uri = NULL;
4851     }
4852     if (resource->rsrcType)
4853     {
4854         deleteResourceType(resource->rsrcType);
4855         resource->rsrcType = NULL;
4856     }
4857     if (resource->rsrcInterface)
4858     {
4859         deleteResourceInterface(resource->rsrcInterface);
4860         resource->rsrcInterface = NULL;
4861     }
4862     if (resource->rsrcChildResourcesHead)
4863     {
4864         unbindChildResources(resource->rsrcChildResourcesHead);
4865         resource->rsrcChildResourcesHead = NULL;
4866     }
4867     if (resource->rsrcAttributes)
4868     {
4869         OCDeleteResourceAttributes(resource->rsrcAttributes);
4870         resource->rsrcAttributes = NULL;
4871     }
4872
4873     resource->entityHandler = NULL;
4874     resource = NULL;
4875 }
4876
4877 void deleteResourceType(OCResourceType *resourceType)
4878 {
4879     OCResourceType *next = NULL;
4880
4881     for (OCResourceType *pointer = resourceType; pointer; pointer = next)
4882     {
4883         next = pointer->next ? pointer->next : NULL;
4884         if (pointer->resourcetypename)
4885         {
4886             OICFree(pointer->resourcetypename);
4887             pointer->resourcetypename = NULL;
4888         }
4889         OICFree(pointer);
4890     }
4891 }
4892
4893 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4894 {
4895     OCResourceInterface *next = NULL;
4896     for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
4897     {
4898         next = pointer->next ? pointer->next : NULL;
4899         if (pointer->name)
4900         {
4901             OICFree(pointer->name);
4902             pointer->name = NULL;
4903         }
4904         OICFree(pointer);
4905     }
4906 }
4907
4908 void unbindChildResources(OCChildResource *head)
4909 {
4910     OCChildResource *next = NULL;
4911     for (OCChildResource *current = head; current; current = next)
4912     {
4913         next = current->next;
4914         OICFree(current);
4915     }
4916 }
4917
4918 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
4919 {
4920     OCAttribute *next = NULL;
4921     for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
4922     {
4923         next = pointer->next ? pointer->next : NULL;
4924         if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
4925         {
4926             OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
4927             pointer->attrValue = NULL;
4928         }
4929         else if (pointer->attrValue)
4930         {
4931             OICFree(pointer->attrValue);
4932             pointer->attrValue = NULL;
4933         }
4934         if (pointer->attrName)
4935         {
4936             OICFree(pointer->attrName);
4937             pointer->attrName = NULL;
4938         }
4939         OICFree(pointer);
4940     }
4941 }
4942
4943 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4944 {
4945     OCResourceType *pointer = NULL;
4946     OCResourceType *previous = NULL;
4947     if (!resource || !resourceType)
4948     {
4949         return;
4950     }
4951     // resource type list is empty.
4952     else if (!resource->rsrcType)
4953     {
4954         resource->rsrcType = resourceType;
4955     }
4956     else
4957     {
4958         pointer = resource->rsrcType;
4959
4960         while (pointer)
4961         {
4962             if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4963             {
4964                 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4965                 OICFree(resourceType->resourcetypename);
4966                 OICFree(resourceType);
4967                 return;
4968             }
4969             previous = pointer;
4970             pointer = pointer->next;
4971         }
4972
4973         if (previous)
4974         {
4975             previous->next = resourceType;
4976         }
4977     }
4978     resourceType->next = NULL;
4979
4980     OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4981 }
4982
4983 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4984 {
4985     OCResource *resource = NULL;
4986     OCResourceType *pointer = NULL;
4987
4988     // Find the specified resource
4989     resource = findResource((OCResource *) handle);
4990     if (!resource)
4991     {
4992         return NULL;
4993     }
4994
4995     // Make sure a resource has a resourcetype
4996     if (!resource->rsrcType)
4997     {
4998         return NULL;
4999     }
5000
5001     // Iterate through the list
5002     pointer = resource->rsrcType;
5003     for(uint8_t i = 0; i< index && pointer; ++i)
5004     {
5005         pointer = pointer->next;
5006     }
5007     return pointer;
5008 }
5009
5010 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
5011 {
5012     if(resourceTypeList && resourceTypeName)
5013     {
5014         OCResourceType * rtPointer = resourceTypeList;
5015         while(resourceTypeName && rtPointer)
5016         {
5017             OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
5018             if(rtPointer->resourcetypename &&
5019                     strcmp(resourceTypeName, (const char *)
5020                     (rtPointer->resourcetypename)) == 0)
5021             {
5022                 break;
5023             }
5024             rtPointer = rtPointer->next;
5025         }
5026         return rtPointer;
5027     }
5028     return NULL;
5029 }
5030
5031 /*
5032  * Insert a new interface into interface linked list only if not already present.
5033  * If alredy present, 2nd arg is free'd.
5034  * Default interface will always be first if present.
5035  */
5036 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
5037 {
5038     OCResourceInterface *pointer = NULL;
5039     OCResourceInterface *previous = NULL;
5040
5041     newInterface->next = NULL;
5042
5043     OCResourceInterface **firstInterface = &(resource->rsrcInterface);
5044
5045     if (!*firstInterface)
5046     {
5047         // If first interface is not oic.if.baseline, by default add it as first interface type.
5048         if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
5049         {
5050             *firstInterface = newInterface;
5051         }
5052         else
5053         {
5054             OCStackResult result = BindResourceInterfaceToResource(resource,
5055                                                                     OC_RSRVD_INTERFACE_DEFAULT);
5056             if (result != OC_STACK_OK)
5057             {
5058                 OICFree(newInterface->name);
5059                 OICFree(newInterface);
5060                 return;
5061             }
5062             if (*firstInterface)
5063             {
5064                 (*firstInterface)->next = newInterface;
5065             }
5066         }
5067     }
5068     // If once add oic.if.baseline, later too below code take care of freeing memory.
5069     else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5070     {
5071         if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5072         {
5073             OICFree(newInterface->name);
5074             OICFree(newInterface);
5075             return;
5076         }
5077         // This code will not hit anymore, keeping
5078         else
5079         {
5080             newInterface->next = *firstInterface;
5081             *firstInterface = newInterface;
5082         }
5083     }
5084     else
5085     {
5086         pointer = *firstInterface;
5087         while (pointer)
5088         {
5089             if (strcmp(newInterface->name, pointer->name) == 0)
5090             {
5091                 OICFree(newInterface->name);
5092                 OICFree(newInterface);
5093                 return;
5094             }
5095             previous = pointer;
5096             pointer = pointer->next;
5097         }
5098
5099         if (previous)
5100         {
5101             previous->next = newInterface;
5102         }
5103     }
5104 }
5105
5106 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
5107         uint8_t index)
5108 {
5109     OCResource *resource = NULL;
5110     OCResourceInterface *pointer = NULL;
5111
5112     // Find the specified resource
5113     resource = findResource((OCResource *) handle);
5114     if (!resource)
5115     {
5116         return NULL;
5117     }
5118
5119     // Make sure a resource has a resourceinterface
5120     if (!resource->rsrcInterface)
5121     {
5122         return NULL;
5123     }
5124
5125     // Iterate through the list
5126     pointer = resource->rsrcInterface;
5127
5128     for (uint8_t i = 0; i < index && pointer; ++i)
5129     {
5130         pointer = pointer->next;
5131     }
5132     return pointer;
5133 }
5134
5135 /*
5136  * This function splits the uri using the '?' delimiter.
5137  * "uriWithoutQuery" is the block of characters between the beginning
5138  * till the delimiter or '\0' which ever comes first.
5139  * "query" is whatever is to the right of the delimiter if present.
5140  * No delimiter sets the query to NULL.
5141  * If either are present, they will be malloc'ed into the params 2, 3.
5142  * The first param, *uri is left untouched.
5143
5144  * NOTE: This function does not account for whitespace at the end of the uri NOR
5145  *       malformed uri's with '??'. Whitespace at the end will be assumed to be
5146  *       part of the query.
5147  */
5148 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
5149 {
5150     if(!uri)
5151     {
5152         return OC_STACK_INVALID_URI;
5153     }
5154     if(!query || !uriWithoutQuery)
5155     {
5156         return OC_STACK_INVALID_PARAM;
5157     }
5158
5159     *query           = NULL;
5160     *uriWithoutQuery = NULL;
5161
5162     size_t uriWithoutQueryLen = 0;
5163     size_t queryLen = 0;
5164     size_t uriLen = strlen(uri);
5165
5166     char *pointerToDelimiter = strstr(uri, "?");
5167
5168     uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
5169     queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
5170
5171     if (uriWithoutQueryLen)
5172     {
5173         *uriWithoutQuery =  (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
5174         if (!*uriWithoutQuery)
5175         {
5176             goto exit;
5177         }
5178         OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
5179     }
5180     if (queryLen)
5181     {
5182         *query = (char *) OICCalloc(queryLen + 1, 1);
5183         if (!*query)
5184         {
5185             OICFree(*uriWithoutQuery);
5186             *uriWithoutQuery = NULL;
5187             goto exit;
5188         }
5189         OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5190     }
5191
5192     return OC_STACK_OK;
5193
5194     exit:
5195         return OC_STACK_NO_MEMORY;
5196 }
5197
5198 const char* OCGetServerInstanceIDString(void)
5199 {
5200     static char sidStr[UUID_STRING_SIZE];
5201     OicUuid_t sid;
5202     if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5203     {
5204         OIC_LOG(FATAL, TAG, "GetDoxmDeviceID failed!");
5205         return NULL;
5206     }
5207
5208     if (OCConvertUuidToString(sid.id, sidStr) != RAND_UUID_OK)
5209     {
5210         OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5211         return NULL;
5212     }
5213
5214     return sidStr;
5215 }
5216
5217 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5218 {
5219     OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5220     CAResult_t retResult = CA_STATUS_FAILED;
5221     CAResult_t caResult = CA_STATUS_OK;
5222
5223     CATransportAdapter_t connTypes[] = {
5224             CA_ADAPTER_IP,
5225             CA_ADAPTER_RFCOMM_BTEDR,
5226             CA_ADAPTER_GATT_BTLE,
5227             CA_ADAPTER_NFC
5228 #ifdef RA_ADAPTER
5229             ,CA_ADAPTER_REMOTE_ACCESS
5230 #endif
5231
5232 #ifdef TCP_ADAPTER
5233             ,CA_ADAPTER_TCP
5234 #endif
5235         };
5236     int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5237
5238     for(int i = 0; i < numConnTypes; i++)
5239     {
5240         // If CA status is not initialized, CASelectNetwork() will not be called.
5241         if (caResult != CA_STATUS_NOT_INITIALIZED)
5242         {
5243             if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5244             {
5245                 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5246                 caResult = CASelectNetwork(connTypes[i]);
5247                 if (caResult == CA_STATUS_OK)
5248                 {
5249                     retResult = CA_STATUS_OK;
5250                 }
5251             }
5252             else
5253             {
5254                 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5255             }
5256         }
5257     }
5258
5259     if (retResult != CA_STATUS_OK)
5260     {
5261         return caResult; // Returns error of appropriate transport that failed fatally.
5262     }
5263
5264     return retResult;
5265 }
5266
5267 OCStackResult CAResultToOCResult(CAResult_t caResult)
5268 {
5269     switch (caResult)
5270     {
5271         case CA_STATUS_OK:
5272             return OC_STACK_OK;
5273         case CA_STATUS_INVALID_PARAM:
5274             return OC_STACK_INVALID_PARAM;
5275         case CA_ADAPTER_NOT_ENABLED:
5276             return OC_STACK_ADAPTER_NOT_ENABLED;
5277         case CA_SERVER_STARTED_ALREADY:
5278             return OC_STACK_OK;
5279         case CA_SERVER_NOT_STARTED:
5280             return OC_STACK_ERROR;
5281         case CA_DESTINATION_NOT_REACHABLE:
5282             return OC_STACK_COMM_ERROR;
5283         case CA_SOCKET_OPERATION_FAILED:
5284             return OC_STACK_COMM_ERROR;
5285         case CA_SEND_FAILED:
5286             return OC_STACK_COMM_ERROR;
5287         case CA_RECEIVE_FAILED:
5288             return OC_STACK_COMM_ERROR;
5289         case CA_MEMORY_ALLOC_FAILED:
5290             return OC_STACK_NO_MEMORY;
5291         case CA_REQUEST_TIMEOUT:
5292             return OC_STACK_TIMEOUT;
5293         case CA_DESTINATION_DISCONNECTED:
5294             return OC_STACK_COMM_ERROR;
5295         case CA_STATUS_FAILED:
5296             return OC_STACK_ERROR;
5297         case CA_NOT_SUPPORTED:
5298             return OC_STACK_NOTIMPL;
5299         default:
5300             return OC_STACK_ERROR;
5301     }
5302 }
5303
5304 bool OCResultToSuccess(OCStackResult ocResult)
5305 {
5306     switch (ocResult)
5307     {
5308         case OC_STACK_OK:
5309         case OC_STACK_RESOURCE_CREATED:
5310         case OC_STACK_RESOURCE_DELETED:
5311         case OC_STACK_CONTINUE:
5312         case OC_STACK_RESOURCE_CHANGED:
5313         case OC_STACK_SLOW_RESOURCE:
5314             return true;
5315         default:
5316             return false;
5317     }
5318 }
5319
5320 #ifdef WITH_CHPROXY
5321 OCStackResult OCSetProxyURI(const char *uri)
5322 {
5323     return CAResultToOCResult(CASetProxyUri(uri));
5324 }
5325 #endif
5326
5327 #if defined(RD_CLIENT) || defined(RD_SERVER)
5328 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5329 {
5330     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5331
5332     OCResource *resource = NULL;
5333
5334     resource = findResource((OCResource *) handle);
5335     if (!resource)
5336     {
5337         OIC_LOG(ERROR, TAG, "Resource not found");
5338         return OC_STACK_ERROR;
5339     }
5340
5341     resource->ins = ins;
5342
5343     return OC_STACK_OK;
5344 }
5345
5346
5347 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5348                                               const OCClientResponse *response)
5349 {
5350     // Validate input parameters
5351     VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5352     VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5353
5354     char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5355     if (!targetUri)
5356     {
5357         return OC_STACK_NO_MEMORY;
5358     }
5359     strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5360
5361     if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5362     {
5363         OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5364
5365         char rdPubUri[MAX_URI_LENGTH] = { 0 };
5366         snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5367                  OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5368
5369         if (strcmp(rdPubUri, targetUri) == 0)
5370         {
5371             // Update resource unique id in stack.
5372             if (response)
5373             {
5374                 if (response->payload)
5375                 {
5376                     OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5377                     OCRepPayload **links = NULL;
5378                     size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5379                     if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5380                                                        &links, dimensions))
5381                     {
5382                         size_t i = 0;
5383                         for (; i < dimensions[0]; i++)
5384                         {
5385                             char *uri = NULL;
5386                             if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5387                             {
5388                                 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5389                                 int64_t ins = 0;
5390                                 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5391                                 {
5392                                     OCBindResourceInsToResource(handle, ins);
5393                                 }
5394
5395                                 OICFree(uri);
5396                                 uri = NULL;
5397                             }
5398                         }
5399
5400                         // Free links
5401                         size_t count = calcDimTotal(dimensions);
5402                         for (size_t k = 0; k < count; k++)
5403                         {
5404                             OCRepPayloadDestroy(links[k]);
5405                         }
5406                         OICFree(links);
5407                     }
5408                 }
5409             }
5410         }
5411     }
5412     else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5413     {
5414         OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5415
5416         uint8_t numResources = 0;
5417         OCGetNumberOfResources(&numResources);
5418
5419         char *ins = strstr(targetUri, OC_RSRVD_INS);
5420         if (!ins)
5421         {
5422             for (uint8_t i = 0; i < numResources; i++)
5423             {
5424                 OCResourceHandle resHandle = OCGetResourceHandle(i);
5425                 if (resHandle)
5426                 {
5427                     OCBindResourceInsToResource(resHandle, 0);
5428                 }
5429             }
5430         }
5431         else
5432         {
5433             const char *token = "&";
5434             char *iterTokenPtr = NULL;
5435             char *start = strtok_r(targetUri, token, &iterTokenPtr);
5436
5437              while (start != NULL)
5438              {
5439                  char *query = start;
5440                  query = strstr(query, OC_RSRVD_INS);
5441                  if (query)
5442                  {
5443                      int64_t queryIns = atoi(query + 4);
5444                      for (uint8_t i = 0; i < numResources; i++)
5445                      {
5446                          OCResourceHandle resHandle = OCGetResourceHandle(i);
5447                          if (resHandle)
5448                          {
5449                              int64_t resIns = 0;
5450                              OCGetResourceIns(resHandle, &resIns);
5451                              if (queryIns && queryIns == resIns)
5452                              {
5453                                  OCBindResourceInsToResource(resHandle, 0);
5454                                  break;
5455                              }
5456                          }
5457                      }
5458                  }
5459                  start = strtok_r(NULL, token, &iterTokenPtr);
5460              }
5461         }
5462     }
5463
5464     OICFree(targetUri);
5465     return OC_STACK_OK;
5466 }
5467
5468 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5469 {
5470     if (!uri)
5471     {
5472         OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5473         return NULL;
5474     }
5475
5476     OCResource *pointer = headResource;
5477
5478     while (pointer)
5479     {
5480         if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5481         {
5482             OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5483             return pointer;
5484         }
5485         pointer = pointer->next;
5486     }
5487     return NULL;
5488 }
5489
5490 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t *ins)
5491 {
5492     OCResource *resource = NULL;
5493
5494     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5495     VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5496
5497     resource = findResource((OCResource *) handle);
5498     if (resource)
5499     {
5500         *ins = resource->ins;
5501         return OC_STACK_OK;
5502     }
5503     return OC_STACK_ERROR;
5504 }
5505 #endif
5506
5507 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5508                                 const void* optionData, size_t optionDataLength)
5509 {
5510     if (!ocHdrOpt)
5511     {
5512         OIC_LOG (INFO, TAG, "Header options are NULL");
5513         return OC_STACK_INVALID_PARAM;
5514     }
5515
5516     if (!optionData)
5517     {
5518         OIC_LOG (INFO, TAG, "optionData are NULL");
5519         return OC_STACK_INVALID_PARAM;
5520     }
5521
5522     if (!numOptions)
5523     {
5524         OIC_LOG (INFO, TAG, "numOptions is NULL");
5525         return OC_STACK_INVALID_PARAM;
5526     }
5527
5528     if (*numOptions >= MAX_HEADER_OPTIONS)
5529     {
5530         OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5531         return OC_STACK_NO_MEMORY;
5532     }
5533
5534     ocHdrOpt += *numOptions;
5535     ocHdrOpt->protocolID = OC_COAP_ID;
5536     ocHdrOpt->optionID = optionID;
5537     ocHdrOpt->optionLength =
5538             optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
5539                     optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5540     memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5541     *numOptions += 1;
5542
5543     return OC_STACK_OK;
5544 }
5545
5546 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5547                                 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5548 {
5549     if (!ocHdrOpt || !numOptions)
5550     {
5551         OIC_LOG (INFO, TAG, "No options present");
5552         return OC_STACK_OK;
5553     }
5554
5555     if (!optionData)
5556     {
5557         OIC_LOG (INFO, TAG, "optionData are NULL");
5558         return OC_STACK_INVALID_PARAM;
5559     }
5560
5561     if (!receivedDataLength)
5562     {
5563         OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5564         return OC_STACK_INVALID_PARAM;
5565     }
5566
5567     for (uint8_t i = 0; i < numOptions; i++)
5568     {
5569         if (ocHdrOpt[i].optionID == optionID)
5570         {
5571             if (optionDataLength >= ocHdrOpt->optionLength)
5572             {
5573                 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5574                 *receivedDataLength = ocHdrOpt->optionLength;
5575                 return OC_STACK_OK;
5576             }
5577             else
5578             {
5579                 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5580                 return OC_STACK_ERROR;
5581             }
5582         }
5583     }
5584     return OC_STACK_OK;
5585 }
5586
5587 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5588 {
5589     OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5590
5591     OC_UNUSED(adapter);
5592     OC_UNUSED(enabled);
5593 }
5594
5595 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5596 {
5597     OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5598
5599     /*
5600      * If the client observes one or more resources over a reliable connection,
5601      * then the CoAP server (or intermediary in the role of the CoAP server)
5602      * MUST remove all entries associated with the client endpoint from the lists
5603      * of observers when the connection is either closed or times out.
5604      */
5605     if (!isConnected)
5606     {
5607         OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5608         CopyEndpointToDevAddr(info, &devAddr);
5609
5610         // remove observer list with remote device address.
5611         DeleteObserverUsingDevAddr(&devAddr);
5612     }
5613 }
5614
5615 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5616 {
5617     OicUuid_t oicUuid;
5618     OCStackResult ret = OC_STACK_ERROR;
5619
5620     ret = GetDoxmDeviceID(&oicUuid);
5621     if (OC_STACK_OK == ret)
5622     {
5623         memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5624     }
5625     else
5626     {
5627         OIC_LOG(ERROR, TAG, "Device ID Get error");
5628     }
5629     return ret;
5630 }
5631
5632 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5633 {
5634     OicUuid_t oicUuid;
5635     OCStackResult ret = OC_STACK_ERROR;
5636
5637     memcpy(&oicUuid, deviceId, UUID_LENGTH);
5638     for (int i = 0; i < UUID_LENGTH; i++)
5639     {
5640         OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5641     }
5642     ret = SetDoxmDeviceID(&oicUuid);
5643     return ret;
5644 }
5645
5646 OCStackResult OCSetDeviceIdResetPF(const OCUUIdentity *deviceId)
5647 {
5648     OicUuid_t oicUuid;
5649     OCStackResult ret = OC_STACK_ERROR;
5650
5651     memcpy(&oicUuid, deviceId, UUID_LENGTH);
5652     char *strUuid = NULL;
5653     if (OC_STACK_OK == ConvertUuidToStr(&oicUuid, &strUuid))
5654     {
5655         OIC_LOG_V(INFO, TAG, "%s: deviceId : %s" ,__func__, strUuid);
5656         OICFree(strUuid);
5657     }
5658     else
5659     {
5660         OIC_LOG(DEBUG, TAG, "Can't convert  deviceId to string");
5661     }
5662     ret = SetDoxmDeviceIDResetPF(&oicUuid);
5663     return ret;
5664 }
5665
5666 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5667 {
5668     bool isDeviceOwned = true;
5669     OCStackResult ret = OC_STACK_ERROR;
5670
5671     ret = GetDoxmIsOwned(&isDeviceOwned);
5672     if (OC_STACK_OK == ret)
5673     {
5674         *isOwned = isDeviceOwned;
5675     }
5676     else
5677     {
5678         OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5679     }
5680     return ret;
5681 }
5682
5683 OCStackResult OCGetDeviceOperationalState(bool* isOp)
5684 {
5685     if(NULL != isOp)
5686     {
5687         *isOp = GetPstatIsop();
5688         return OC_STACK_OK;
5689     }
5690
5691     return OC_STACK_ERROR;
5692 }
5693
5694 void OCClearCallBackList()
5695 {
5696     DeleteClientCBList();
5697 }
5698
5699 void OCClearObserverlist()
5700 {
5701     DeleteObserverList();
5702 }
5703
5704 int OCEncrypt(const unsigned char *pt, size_t pt_len,
5705         unsigned char **ct, size_t *ct_len)
5706 {
5707 #ifndef __SECURE_PSI__
5708     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5709     return 0;
5710 #else
5711     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5712
5713     return psiEncrypt(pt, pt_len, ct, ct_len);
5714 #endif // __SECURE_PSI__
5715 }
5716
5717 int OCDecrypt(const unsigned char *ct, size_t ct_len,
5718         unsigned char **pt, size_t *pt_len)
5719 {
5720 #ifndef __SECURE_PSI__
5721     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5722     return 0;
5723 #else
5724     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5725
5726     return psiDecrypt(ct, ct_len, pt, pt_len);
5727 #endif // __SECURE_PSI__
5728 }
5729
5730 OCStackResult OCSetKey(const unsigned char* key)
5731 {
5732 #ifndef __SECURE_PSI__
5733     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5734     return OC_STACK_OK;
5735 #else
5736     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5737
5738     return psiSetKey(key);
5739 #endif // __SECURE_PSI__
5740 }
5741
5742 OCStackResult OCGetKey(unsigned char* key)
5743 {
5744 #ifndef __SECURE_PSI__
5745     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5746     return OC_STACK_OK;
5747 #else
5748     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5749
5750     return psiGetKey(key);
5751 #endif // __SECURE_PSI__
5752 }
5753
5754 OCStackResult OCSetSecurePSI(const unsigned char *key, const OCPersistentStorage *psPlain,
5755         const OCPersistentStorage *psEnc, const OCPersistentStorage *psRescue)
5756 {
5757 #ifndef __SECURE_PSI__
5758     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5759     return OC_STACK_OK;
5760 #else
5761     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5762
5763     return setSecurePSI(key, psPlain, psEnc, psRescue);
5764 #endif // __SECURE_PSI__
5765 }
5766
5767 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5768 static void OtmEventHandler(const char *addr, uint16_t port, const char *uuid, int event)
5769 {
5770     if (g_otmEventHandler.cb)
5771     {
5772         g_otmEventHandler.cb(g_otmEventHandler.ctx, addr, port, uuid, event);
5773     }
5774 }
5775
5776 /* TODO Work-around
5777  * It is already declared in srmutility.h.
5778  * We can't include the header file, because of "redefined VERIFY_NON_NULL"
5779  */
5780 typedef void (*OicSecOtmEventHandler_t)(const char* addr, uint16_t port,
5781         const char* uuid, int event);
5782 void SetOtmEventHandler(OicSecOtmEventHandler_t otmEventHandler);
5783 #endif
5784
5785 OCStackResult OCSetOtmEventHandler(void *ctx, OCOtmEventHandler cb)
5786 {
5787 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5788     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5789
5790     g_otmEventHandler.cb = cb;
5791     g_otmEventHandler.ctx = ctx;
5792
5793     if (g_otmEventHandler.cb)
5794     {
5795         OIC_LOG(DEBUG, TAG, "SET OCOtmEventHandler");
5796         SetOtmEventHandler(OtmEventHandler);
5797     }
5798     else
5799     {
5800         OIC_LOG(DEBUG, TAG, "UNSET OCOtmEventHandler");
5801         SetOtmEventHandler(NULL);
5802     }
5803 #else
5804     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5805     OC_UNUSED(ctx);
5806     OC_UNUSED(cb);
5807 #endif
5808     return OC_STACK_OK;
5809 }