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