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