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