Update snapshot(2018-02-14)
[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     token = NULL;         // Client CB list entry now owns it
3136     devAddr = NULL;       // Client CB list entry now owns it
3137     resourceUri = NULL;   // Client CB list entry now owns it
3138     resourceType = NULL;  // Client CB list entry now owns it
3139
3140 #ifdef WITH_PRESENCE
3141     if (method == OC_REST_PRESENCE)
3142     {
3143         OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3144
3145         if (handle)
3146         {
3147             *handle = resHandle;
3148         }
3149
3150         goto exit;
3151     }
3152 #endif
3153
3154     // send request
3155     result = OCSendRequest(&endpoint, &requestInfo);
3156     if (OC_STACK_OK != result)
3157     {
3158         goto exit;
3159     }
3160
3161     if (handle)
3162     {
3163         *handle = resHandle;
3164     }
3165
3166 exit:
3167     if (result != OC_STACK_OK)
3168     {
3169         OIC_LOG(ERROR, TAG, "OCDoResource error");
3170         FindAndDeleteClientCB(clientCB);
3171         CADestroyToken(token);
3172         if (handle)
3173         {
3174             *handle = NULL;
3175         }
3176         OICFree(resHandle);
3177     }
3178
3179     OICFree(requestInfo.info.payload);
3180     OICFree(devAddr);
3181     OICFree(resourceUri);
3182     OICFree(resourceType);
3183     OICFree(requestInfo.info.options);
3184     OIC_TRACE_END();
3185     return result;
3186 }
3187
3188 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3189         uint8_t numOptions)
3190 {
3191     /*
3192      * This ftn is implemented one of two ways in the case of observation:
3193      *
3194      * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3195      *      Remove the callback associated on client side.
3196      *      When the next notification comes in from server,
3197      *      reply with RESET message to server.
3198      *      Keep in mind that the server will react to RESET only
3199      *      if the last notification was sent as CON
3200      *
3201      * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3202      *      and it is associated with an observe request
3203      *      (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3204      *      Send CON Observe request to server with
3205      *      observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3206      *      Remove the callback associated on client side.
3207      */
3208     OCStackResult ret = OC_STACK_OK;
3209     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3210     CARequestInfo_t requestInfo = {.method = CA_GET};
3211
3212     if(!handle)
3213     {
3214         return OC_STACK_INVALID_PARAM;
3215     }
3216
3217     ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3218     if (!clientCB)
3219     {
3220         OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3221         return OC_STACK_ERROR;
3222     }
3223
3224     switch (clientCB->method)
3225     {
3226         case OC_REST_OBSERVE:
3227         case OC_REST_OBSERVE_ALL:
3228
3229             OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3230
3231             CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3232
3233             if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
3234             {
3235                 FindAndDeleteClientCB(clientCB);
3236                 break;
3237             }
3238
3239             OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3240
3241             requestInfo.info.type = qualityOfServiceToMessageType(qos);
3242             requestInfo.info.token = clientCB->token;
3243             requestInfo.info.tokenLength = clientCB->tokenLength;
3244
3245             if (CreateObserveHeaderOption (&(requestInfo.info.options),
3246                     options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3247             {
3248                 return OC_STACK_ERROR;
3249             }
3250             requestInfo.info.numOptions = numOptions + 1;
3251             requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3252
3253
3254             ret = OCSendRequest(&endpoint, &requestInfo);
3255
3256             if (requestInfo.info.options)
3257             {
3258                 OICFree (requestInfo.info.options);
3259             }
3260             if (requestInfo.info.resourceUri)
3261             {
3262                 OICFree (requestInfo.info.resourceUri);
3263             }
3264
3265             break;
3266
3267         case OC_REST_DISCOVER:
3268             OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3269                                            clientCB->requestUri);
3270             FindAndDeleteClientCB(clientCB);
3271             break;
3272
3273 #ifdef WITH_PRESENCE
3274         case OC_REST_PRESENCE:
3275             FindAndDeleteClientCB(clientCB);
3276             break;
3277 #endif
3278         case OC_REST_GET:
3279         case OC_REST_PUT:
3280         case OC_REST_POST:
3281         case OC_REST_DELETE:
3282             OIC_LOG_V(INFO, TAG, "Cancelling request callback for resource %s",
3283                                            clientCB->requestUri);
3284             FindAndDeleteClientCB(clientCB);
3285             break;
3286
3287         default:
3288             ret = OC_STACK_INVALID_METHOD;
3289             break;
3290     }
3291
3292     return ret;
3293 }
3294
3295 /**
3296  * @brief   Register Persistent storage callback.
3297  * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3298  * @return
3299  *     OC_STACK_OK    - No errors; Success
3300  *     OC_STACK_INVALID_PARAM - Invalid parameter
3301  */
3302 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3303 {
3304     OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3305     if(!persistentStorageHandler)
3306     {
3307         OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3308         return OC_STACK_INVALID_PARAM;
3309     }
3310     else
3311     {
3312         if( !persistentStorageHandler->open ||
3313                 !persistentStorageHandler->close ||
3314                 !persistentStorageHandler->read ||
3315                 !persistentStorageHandler->unlink ||
3316                 !persistentStorageHandler->write)
3317         {
3318             OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3319             return OC_STACK_INVALID_PARAM;
3320         }
3321     }
3322     return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3323 }
3324
3325 #ifdef WITH_PRESENCE
3326
3327 OCStackResult OCProcessPresence()
3328 {
3329     OCStackResult result = OC_STACK_OK;
3330
3331     // the following line floods the log with messages that are irrelevant
3332     // to most purposes.  Uncomment as needed.
3333     //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3334     ClientCB* cbNode = NULL;
3335     OCClientResponse clientResponse;
3336     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3337
3338     LL_FOREACH(cbList, cbNode)
3339     {
3340         if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3341         {
3342             continue;
3343         }
3344
3345         uint32_t now = GetTicks(0);
3346         OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3347                                                 cbNode->presence->TTLlevel);
3348         OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3349
3350         if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3351         {
3352             goto exit;
3353         }
3354
3355         if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3356         {
3357             OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3358                     cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3359         }
3360         if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3361         {
3362             OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3363
3364             clientResponse.sequenceNumber = 0;
3365             clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3366             clientResponse.devAddr = *cbNode->devAddr;
3367             FixUpClientResponse(&clientResponse);
3368             clientResponse.payload = NULL;
3369
3370             // Increment the TTLLevel (going to a next state), so we don't keep
3371             // sending presence notification to client.
3372             cbNode->presence->TTLlevel++;
3373             OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3374                                         cbNode->presence->TTLlevel);
3375
3376             OIC_LOG(INFO, TAG, "Before calling into application address space for presence timeout");
3377             cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3378             OIC_LOG(INFO, TAG, "After calling into application address space for presence timeout");
3379
3380             if (cbResult == OC_STACK_DELETE_TRANSACTION)
3381             {
3382                 FindAndDeleteClientCB(cbNode);
3383             }
3384         }
3385
3386         if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3387         {
3388             continue;
3389         }
3390
3391         CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3392         CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3393         CARequestInfo_t requestInfo = {.method = CA_GET};
3394
3395         OIC_LOG(DEBUG, TAG, "time to test server presence");
3396
3397         CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3398
3399         requestData.type = CA_MSG_NONCONFIRM;
3400         requestData.token = cbNode->token;
3401         requestData.tokenLength = cbNode->tokenLength;
3402         requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3403         requestInfo.method = CA_GET;
3404         requestInfo.info = requestData;
3405
3406         result = OCSendRequest(&endpoint, &requestInfo);
3407         if (OC_STACK_OK != result)
3408         {
3409             goto exit;
3410         }
3411
3412         cbNode->presence->TTLlevel++;
3413         OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3414     }
3415 exit:
3416     if (result != OC_STACK_OK)
3417     {
3418         OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3419     }
3420
3421     return result;
3422 }
3423 #endif // WITH_PRESENCE
3424
3425 OCStackResult OCProcess()
3426 {
3427     if (stackState == OC_STACK_UNINITIALIZED)
3428     {
3429         OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3430         return OC_STACK_ERROR;
3431     }
3432 #ifdef WITH_PRESENCE
3433     OCProcessPresence();
3434 #endif
3435     CAHandleRequestResponse();
3436
3437 #ifdef ROUTING_GATEWAY
3438     RMProcess();
3439 #endif
3440
3441 #ifdef TCP_ADAPTER
3442     OCProcessKeepAlive();
3443 #endif
3444     return OC_STACK_OK;
3445 }
3446
3447 #ifdef WITH_PRESENCE
3448 OCStackResult OCStartPresence(const uint32_t ttl)
3449 {
3450     OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3451     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3452     OCChangeResourceProperty(
3453             &(((OCResource *)presenceResource.handle)->resourceProperties),
3454             OC_ACTIVE, 1);
3455
3456     if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3457     {
3458         presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3459         OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3460     }
3461     else if (0 == ttl)
3462     {
3463         presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3464         OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3465     }
3466     else
3467     {
3468         presenceResource.presenceTTL = ttl;
3469     }
3470 #ifndef __TIZENRT__
3471     OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3472 #endif
3473
3474     if (OC_PRESENCE_UNINITIALIZED == presenceState)
3475     {
3476         presenceState = OC_PRESENCE_INITIALIZED;
3477
3478         OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3479
3480         CAToken_t caToken = NULL;
3481         CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3482         if (caResult != CA_STATUS_OK)
3483         {
3484             OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3485             CADestroyToken(caToken);
3486             return OC_STACK_ERROR;
3487         }
3488
3489         AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3490                 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3491         CADestroyToken(caToken);
3492     }
3493
3494     // Each time OCStartPresence is called
3495     // a different random 32-bit integer number is used
3496     ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3497
3498     return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3499             OC_PRESENCE_TRIGGER_CREATE);
3500 }
3501
3502 OCStackResult OCStopPresence()
3503 {
3504     OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3505     OCStackResult result = OC_STACK_ERROR;
3506
3507     if(presenceResource.handle)
3508     {
3509         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3510
3511     // make resource inactive
3512     result = OCChangeResourceProperty(
3513             &(((OCResource *) presenceResource.handle)->resourceProperties),
3514             OC_ACTIVE, 0);
3515     }
3516
3517     if(result != OC_STACK_OK)
3518     {
3519         OIC_LOG(ERROR, TAG,
3520                       "Changing the presence resource properties to ACTIVE not successful");
3521         return result;
3522     }
3523
3524     return SendStopNotification();
3525 }
3526 #endif
3527
3528 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3529                                             void* callbackParameter)
3530 {
3531     defaultDeviceHandler = entityHandler;
3532     defaultDeviceHandlerCallbackParameter = callbackParameter;
3533
3534     return OC_STACK_OK;
3535 }
3536
3537 OCStackResult OCCreateResource(OCResourceHandle *handle,
3538         const char *resourceTypeName,
3539         const char *resourceInterfaceName,
3540         const char *uri, OCEntityHandler entityHandler,
3541         void* callbackParam,
3542         uint8_t resourceProperties)
3543 {
3544
3545     OCResource *pointer = NULL;
3546     OCStackResult result = OC_STACK_ERROR;
3547
3548     OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3549
3550     if(myStackMode == OC_CLIENT)
3551     {
3552         return OC_STACK_INVALID_PARAM;
3553     }
3554     // Validate parameters
3555     if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3556     {
3557         OIC_LOG(ERROR, TAG, "URI is empty or too long");
3558         return OC_STACK_INVALID_URI;
3559     }
3560     // Is it presented during resource discovery?
3561     if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3562     {
3563         OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3564         return OC_STACK_INVALID_PARAM;
3565     }
3566
3567     if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3568     {
3569         resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3570     }
3571
3572 #ifdef MQ_PUBLISHER
3573     resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3574 #endif
3575     // Make sure resourceProperties bitmask has allowed properties specified
3576     if (resourceProperties
3577             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3578                OC_EXPLICIT_DISCOVERABLE
3579 #ifdef MQ_PUBLISHER
3580                | OC_MQ_PUBLISHER
3581 #endif
3582 #ifdef MQ_BROKER
3583                | OC_MQ_BROKER
3584 #endif
3585                ))
3586     {
3587         OIC_LOG(ERROR, TAG, "Invalid property");
3588         return OC_STACK_INVALID_PARAM;
3589     }
3590
3591     // If the headResource is NULL, then no resources have been created...
3592     pointer = headResource;
3593     if (pointer)
3594     {
3595         // At least one resources is in the resource list, so we need to search for
3596         // repeated URLs, which are not allowed.  If a repeat is found, exit with an error
3597         while (pointer)
3598         {
3599             if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3600             {
3601                 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3602                 return OC_STACK_INVALID_PARAM;
3603             }
3604             pointer = pointer->next;
3605         }
3606     }
3607     // Create the pointer and insert it into the resource list
3608     pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3609     if (!pointer)
3610     {
3611         result = OC_STACK_NO_MEMORY;
3612         goto exit;
3613     }
3614     pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3615
3616     insertResource(pointer);
3617
3618     // Set the uri
3619     pointer->uri = OICStrdup(uri);
3620     if (!pointer->uri)
3621     {
3622         result = OC_STACK_NO_MEMORY;
3623         goto exit;
3624     }
3625
3626     // Set properties.  Set OC_ACTIVE
3627     pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3628             | OC_ACTIVE);
3629
3630     // Add the resourcetype to the resource
3631     result = BindResourceTypeToResource(pointer, resourceTypeName);
3632     if (result != OC_STACK_OK)
3633     {
3634         OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3635         goto exit;
3636     }
3637
3638     // Add the resourceinterface to the resource
3639     result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3640     if (result != OC_STACK_OK)
3641     {
3642         OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3643         goto exit;
3644     }
3645
3646     // If an entity handler has been passed, attach it to the newly created
3647     // resource.  Otherwise, set the default entity handler.
3648     if (entityHandler)
3649     {
3650         pointer->entityHandler = entityHandler;
3651         pointer->entityHandlerCallbackParam = callbackParam;
3652     }
3653     else
3654     {
3655         pointer->entityHandler = defaultResourceEHandler;
3656         pointer->entityHandlerCallbackParam = NULL;
3657     }
3658
3659     // Initialize a pointer indicating child resources in case of collection
3660     pointer->rsrcChildResourcesHead = NULL;
3661
3662     *handle = pointer;
3663     result = OC_STACK_OK;
3664
3665 #ifdef WITH_PRESENCE
3666     if (presenceResource.handle)
3667     {
3668         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3669         SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3670     }
3671 #endif
3672 exit:
3673     if (result != OC_STACK_OK)
3674     {
3675         // Deep delete of resource and other dynamic elements that it contains
3676         deleteResource(pointer);
3677     }
3678     return result;
3679 }
3680
3681 OCStackResult OCBindResource(
3682         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3683 {
3684     OCResource *resource = NULL;
3685     OCChildResource *tempChildResource = NULL;
3686     OCChildResource *newChildResource = NULL;
3687
3688     OIC_LOG(INFO, TAG, "Entering OCBindResource");
3689
3690     // Validate parameters
3691     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3692     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3693     // Container cannot contain itself
3694     if (collectionHandle == resourceHandle)
3695     {
3696         OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3697         return OC_STACK_INVALID_PARAM;
3698     }
3699
3700     // Use the handle to find the resource in the resource linked list
3701     resource = findResource((OCResource *) collectionHandle);
3702     if (!resource)
3703     {
3704         OIC_LOG(ERROR, TAG, "Collection handle not found");
3705         return OC_STACK_INVALID_PARAM;
3706     }
3707
3708     // Look for an open slot to add add the child resource.
3709     // If found, add it and return success
3710
3711     tempChildResource = resource->rsrcChildResourcesHead;
3712
3713     while(resource->rsrcChildResourcesHead && tempChildResource->next)
3714     {
3715         // TODO: what if one of child resource was deregistered without unbinding?
3716         tempChildResource = tempChildResource->next;
3717     }
3718
3719     // Do memory allocation for child resource
3720     newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3721     if(!newChildResource)
3722     {
3723         OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3724         return OC_STACK_ERROR;
3725     }
3726
3727     newChildResource->rsrcResource = (OCResource *) resourceHandle;
3728     newChildResource->next = NULL;
3729
3730     if(!resource->rsrcChildResourcesHead)
3731     {
3732         resource->rsrcChildResourcesHead = newChildResource;
3733     }
3734     else {
3735         tempChildResource->next = newChildResource;
3736     }
3737
3738     OIC_LOG(INFO, TAG, "resource bound");
3739
3740 #ifdef WITH_PRESENCE
3741     if (presenceResource.handle)
3742     {
3743         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3744         SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3745                 OC_PRESENCE_TRIGGER_CHANGE);
3746     }
3747 #endif
3748
3749     return OC_STACK_OK;
3750 }
3751
3752 OCStackResult OCUnBindResource(
3753         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3754 {
3755     OCResource *resource = NULL;
3756     OCChildResource *tempChildResource = NULL;
3757     OCChildResource *tempLastChildResource = NULL;
3758
3759     OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3760
3761     // Validate parameters
3762     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3763     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3764     // Container cannot contain itself
3765     if (collectionHandle == resourceHandle)
3766     {
3767         OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3768         return OC_STACK_INVALID_PARAM;
3769     }
3770
3771     // Use the handle to find the resource in the resource linked list
3772     resource = findResource((OCResource *) collectionHandle);
3773     if (!resource)
3774     {
3775         OIC_LOG(ERROR, TAG, "Collection handle not found");
3776         return OC_STACK_INVALID_PARAM;
3777     }
3778
3779     // Look for an open slot to add add the child resource.
3780     // If found, add it and return success
3781     if(!resource->rsrcChildResourcesHead)
3782     {
3783         OIC_LOG(INFO, TAG, "resource not found in collection");
3784
3785         // Unable to add resourceHandle, so return error
3786         return OC_STACK_ERROR;
3787
3788     }
3789
3790     tempChildResource = resource->rsrcChildResourcesHead;
3791
3792     while (tempChildResource)
3793     {
3794         if(tempChildResource->rsrcResource == resourceHandle)
3795         {
3796             // if resource going to be unbinded is the head one.
3797             if( tempChildResource == resource->rsrcChildResourcesHead )
3798             {
3799                 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3800                 OICFree(resource->rsrcChildResourcesHead);
3801                 resource->rsrcChildResourcesHead = temp;
3802                 temp = NULL;
3803             }
3804             else
3805             {
3806                 OCChildResource *temp = tempChildResource->next;
3807                 OICFree(tempChildResource);
3808                 if (tempLastChildResource)
3809                 {
3810                     tempLastChildResource->next = temp;
3811                     temp = NULL;
3812                 }
3813             }
3814
3815             OIC_LOG(INFO, TAG, "resource unbound");
3816
3817             // Send notification when resource is unbounded successfully.
3818 #ifdef WITH_PRESENCE
3819             if (presenceResource.handle)
3820             {
3821                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3822                 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3823                         OC_PRESENCE_TRIGGER_CHANGE);
3824             }
3825 #endif
3826             tempChildResource = NULL;
3827             tempLastChildResource = NULL;
3828
3829             return OC_STACK_OK;
3830
3831         }
3832
3833         tempLastChildResource = tempChildResource;
3834         tempChildResource = tempChildResource->next;
3835     }
3836
3837     OIC_LOG(INFO, TAG, "resource not found in collection");
3838
3839     tempChildResource = NULL;
3840     tempLastChildResource = NULL;
3841
3842     // Unable to add resourceHandle, so return error
3843     return OC_STACK_ERROR;
3844 }
3845
3846 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3847 {
3848     if (!resourceItemName)
3849     {
3850         return false;
3851     }
3852     // Per RFC 6690 only registered values must follow the first rule below.
3853     // At this point in time the only values registered begin with "core", and
3854     // all other values are specified as opaque strings where multiple values
3855     // are separated by a space.
3856     if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3857     {
3858         for(size_t index = sizeof(CORESPEC) - 1;  resourceItemName[index]; ++index)
3859         {
3860             if (resourceItemName[index] != '.'
3861                 && resourceItemName[index] != '-'
3862                 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3863                 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3864             {
3865                 return false;
3866             }
3867         }
3868     }
3869     else
3870     {
3871         for (size_t index = 0; resourceItemName[index]; ++index)
3872         {
3873             if (resourceItemName[index] == ' '
3874                 || resourceItemName[index] == '\t'
3875                 || resourceItemName[index] == '\r'
3876                 || resourceItemName[index] == '\n')
3877             {
3878                 return false;
3879             }
3880         }
3881     }
3882
3883     return true;
3884 }
3885
3886 OCStackResult BindResourceTypeToResource(OCResource* resource,
3887                                             const char *resourceTypeName)
3888 {
3889     OCResourceType *pointer = NULL;
3890     char *str = NULL;
3891     OCStackResult result = OC_STACK_ERROR;
3892
3893     VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3894
3895     if (!ValidateResourceTypeInterface(resourceTypeName))
3896     {
3897         OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3898         return OC_STACK_INVALID_PARAM;
3899     }
3900
3901     pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3902     if (!pointer)
3903     {
3904         result = OC_STACK_NO_MEMORY;
3905         goto exit;
3906     }
3907
3908     str = OICStrdup(resourceTypeName);
3909     if (!str)
3910     {
3911         result = OC_STACK_NO_MEMORY;
3912         goto exit;
3913     }
3914     pointer->resourcetypename = str;
3915     pointer->next = NULL;
3916
3917     insertResourceType(resource, pointer);
3918     result = OC_STACK_OK;
3919
3920 exit:
3921     if (result != OC_STACK_OK)
3922     {
3923         OICFree(pointer);
3924         OICFree(str);
3925     }
3926
3927     return result;
3928 }
3929
3930 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3931         const char *resourceInterfaceName)
3932 {
3933     OCResourceInterface *pointer = NULL;
3934     char *str = NULL;
3935     OCStackResult result = OC_STACK_ERROR;
3936
3937     VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3938
3939     if (!ValidateResourceTypeInterface(resourceInterfaceName))
3940     {
3941         OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3942         return OC_STACK_INVALID_PARAM;
3943     }
3944
3945     OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3946
3947     pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3948     if (!pointer)
3949     {
3950         result = OC_STACK_NO_MEMORY;
3951         goto exit;
3952     }
3953
3954     str = OICStrdup(resourceInterfaceName);
3955     if (!str)
3956     {
3957         result = OC_STACK_NO_MEMORY;
3958         goto exit;
3959     }
3960     pointer->name = str;
3961
3962     // Bind the resourceinterface to the resource
3963     insertResourceInterface(resource, pointer);
3964
3965     result = OC_STACK_OK;
3966
3967     exit:
3968     if (result != OC_STACK_OK)
3969     {
3970         OICFree(pointer);
3971         OICFree(str);
3972     }
3973
3974     return result;
3975 }
3976
3977 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3978         const char *resourceTypeName)
3979 {
3980
3981     OCStackResult result = OC_STACK_ERROR;
3982     OCResource *resource = NULL;
3983
3984     resource = findResource((OCResource *) handle);
3985     if (!resource)
3986     {
3987         OIC_LOG(ERROR, TAG, "Resource not found");
3988         return OC_STACK_ERROR;
3989     }
3990
3991     result = BindResourceTypeToResource(resource, resourceTypeName);
3992
3993 #ifdef WITH_PRESENCE
3994     if(presenceResource.handle)
3995     {
3996         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3997         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3998     }
3999 #endif
4000
4001     return result;
4002 }
4003
4004 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
4005         const char *resourceInterfaceName)
4006 {
4007
4008     OCStackResult result = OC_STACK_ERROR;
4009     OCResource *resource = NULL;
4010
4011     resource = findResource((OCResource *) handle);
4012     if (!resource)
4013     {
4014         OIC_LOG(ERROR, TAG, "Resource not found");
4015         return OC_STACK_ERROR;
4016     }
4017
4018     result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
4019
4020 #ifdef WITH_PRESENCE
4021     if (presenceResource.handle)
4022     {
4023         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4024         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4025     }
4026 #endif
4027
4028     return result;
4029 }
4030
4031 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
4032 {
4033     OCResource *pointer = headResource;
4034
4035     VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
4036     *numResources = 0;
4037     while (pointer)
4038     {
4039         *numResources = *numResources + 1;
4040         pointer = pointer->next;
4041     }
4042     return OC_STACK_OK;
4043 }
4044
4045 OCResourceHandle OCGetResourceHandle(uint8_t index)
4046 {
4047     OCResource *pointer = headResource;
4048
4049     for( uint8_t i = 0; i < index && pointer; ++i)
4050     {
4051         pointer = pointer->next;
4052     }
4053     return (OCResourceHandle) pointer;
4054 }
4055
4056 OCStackResult OCDeleteResource(OCResourceHandle handle)
4057 {
4058     if (!handle)
4059     {
4060         OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4061         return OC_STACK_INVALID_PARAM;
4062     }
4063
4064     OCResource *resource = findResource((OCResource *) handle);
4065     if (resource == NULL)
4066     {
4067         OIC_LOG(ERROR, TAG, "Resource not found");
4068         return OC_STACK_NO_RESOURCE;
4069     }
4070
4071     if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4072     {
4073         OIC_LOG(ERROR, TAG, "Error deleting resource");
4074         return OC_STACK_ERROR;
4075     }
4076
4077     return OC_STACK_OK;
4078 }
4079
4080 const char *OCGetResourceUri(OCResourceHandle handle)
4081 {
4082     OCResource *resource = NULL;
4083
4084     resource = findResource((OCResource *) handle);
4085     if (resource)
4086     {
4087         return resource->uri;
4088     }
4089     return (const char *) NULL;
4090 }
4091
4092 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4093 {
4094     OCResource *resource = NULL;
4095
4096     resource = findResource((OCResource *) handle);
4097     if (resource)
4098     {
4099         return resource->resourceProperties;
4100     }
4101     return (OCResourceProperty)-1;
4102 }
4103
4104 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4105         uint8_t *numResourceTypes)
4106 {
4107     OCResource *resource = NULL;
4108     OCResourceType *pointer = NULL;
4109
4110     VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4111     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4112
4113     *numResourceTypes = 0;
4114
4115     resource = findResource((OCResource *) handle);
4116     if (resource)
4117     {
4118         pointer = resource->rsrcType;
4119         while (pointer)
4120         {
4121             *numResourceTypes = *numResourceTypes + 1;
4122             pointer = pointer->next;
4123         }
4124     }
4125     return OC_STACK_OK;
4126 }
4127
4128 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4129 {
4130     OCResourceType *resourceType = NULL;
4131
4132     resourceType = findResourceTypeAtIndex(handle, index);
4133     if (resourceType)
4134     {
4135         return resourceType->resourcetypename;
4136     }
4137     return (const char *) NULL;
4138 }
4139
4140 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4141         uint8_t *numResourceInterfaces)
4142 {
4143     OCResourceInterface *pointer = NULL;
4144     OCResource *resource = NULL;
4145
4146     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4147     VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4148
4149     *numResourceInterfaces = 0;
4150     resource = findResource((OCResource *) handle);
4151     if (resource)
4152     {
4153         pointer = resource->rsrcInterface;
4154         while (pointer)
4155         {
4156             *numResourceInterfaces = *numResourceInterfaces + 1;
4157             pointer = pointer->next;
4158         }
4159     }
4160     return OC_STACK_OK;
4161 }
4162
4163 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4164 {
4165     OCResourceInterface *resourceInterface = NULL;
4166
4167     resourceInterface = findResourceInterfaceAtIndex(handle, index);
4168     if (resourceInterface)
4169     {
4170         return resourceInterface->name;
4171     }
4172     return (const char *) NULL;
4173 }
4174
4175 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4176         uint8_t index)
4177 {
4178     OCResource *resource = NULL;
4179     OCChildResource *tempChildResource = NULL;
4180     uint8_t num = 0;
4181
4182     resource = findResource((OCResource *) collectionHandle);
4183     if (!resource)
4184     {
4185         return NULL;
4186     }
4187
4188     tempChildResource = resource->rsrcChildResourcesHead;
4189
4190     while(tempChildResource)
4191     {
4192         if( num == index )
4193         {
4194             return tempChildResource->rsrcResource;
4195         }
4196         num++;
4197         tempChildResource = tempChildResource->next;
4198     }
4199
4200     // In this case, the number of resource handles in the collection exceeds the index
4201     tempChildResource = NULL;
4202     return NULL;
4203 }
4204
4205 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4206         OCEntityHandler entityHandler,
4207         void* callbackParam)
4208 {
4209     OCResource *resource = NULL;
4210
4211     // Validate parameters
4212     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4213
4214     // Use the handle to find the resource in the resource linked list
4215     resource = findResource((OCResource *)handle);
4216     if (!resource)
4217     {
4218         OIC_LOG(ERROR, TAG, "Resource not found");
4219         return OC_STACK_ERROR;
4220     }
4221
4222     // Bind the handler
4223     resource->entityHandler = entityHandler;
4224     resource->entityHandlerCallbackParam = callbackParam;
4225
4226 #ifdef WITH_PRESENCE
4227     if (presenceResource.handle)
4228     {
4229         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4230         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4231     }
4232 #endif
4233
4234     return OC_STACK_OK;
4235 }
4236
4237 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4238 {
4239     OCResource *resource = NULL;
4240
4241     resource = findResource((OCResource *)handle);
4242     if (!resource)
4243     {
4244         OIC_LOG(ERROR, TAG, "Resource not found");
4245         return NULL;
4246     }
4247
4248     // Bind the handler
4249     return resource->entityHandler;
4250 }
4251
4252 void incrementSequenceNumber(OCResource * resPtr)
4253 {
4254     // Increment the sequence number
4255     resPtr->sequenceNum += 1;
4256     if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4257     {
4258         resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4259     }
4260     return;
4261 }
4262
4263 #ifdef WITH_PRESENCE
4264 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4265         OCPresenceTrigger trigger)
4266 {
4267     OIC_LOG(INFO, TAG, "SendPresenceNotification");
4268     OCResource *resPtr = NULL;
4269     OCStackResult result = OC_STACK_ERROR;
4270     OCMethod method = OC_REST_PRESENCE;
4271     uint32_t maxAge = 0;
4272     resPtr = findResource((OCResource *) presenceResource.handle);
4273     if(NULL == resPtr)
4274     {
4275         return OC_STACK_NO_RESOURCE;
4276     }
4277
4278     if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4279     {
4280         maxAge = presenceResource.presenceTTL;
4281
4282         result = SendAllObserverNotification(method, resPtr, maxAge,
4283                 trigger, resourceType, OC_LOW_QOS);
4284     }
4285
4286     return result;
4287 }
4288
4289 OCStackResult SendStopNotification()
4290 {
4291     OIC_LOG(INFO, TAG, "SendStopNotification");
4292     OCResource *resPtr = NULL;
4293     OCStackResult result = OC_STACK_ERROR;
4294     OCMethod method = OC_REST_PRESENCE;
4295     resPtr = findResource((OCResource *) presenceResource.handle);
4296     if(NULL == resPtr)
4297     {
4298         return OC_STACK_NO_RESOURCE;
4299     }
4300
4301     // maxAge is 0. ResourceType is NULL.
4302     result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4303             NULL, OC_LOW_QOS);
4304
4305     return result;
4306 }
4307
4308 #endif // WITH_PRESENCE
4309 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4310 {
4311     OCResource *resPtr = NULL;
4312     OCStackResult result = OC_STACK_ERROR;
4313     OCMethod method = OC_REST_NOMETHOD;
4314     uint32_t maxAge = 0;
4315
4316     OIC_LOG(INFO, TAG, "Notifying all observers");
4317 #ifdef WITH_PRESENCE
4318     if(handle == presenceResource.handle)
4319     {
4320         return OC_STACK_OK;
4321     }
4322 #endif // WITH_PRESENCE
4323     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4324
4325     // Verify that the resource exists
4326     resPtr = findResource ((OCResource *) handle);
4327     if (NULL == resPtr)
4328     {
4329         return OC_STACK_NO_RESOURCE;
4330     }
4331     else
4332     {
4333         //only increment in the case of regular observing (not presence)
4334         incrementSequenceNumber(resPtr);
4335         method = OC_REST_OBSERVE;
4336         maxAge = MAX_OBSERVE_AGE;
4337 #ifdef WITH_PRESENCE
4338         result = SendAllObserverNotification (method, resPtr, maxAge,
4339                 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4340 #else
4341         result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4342 #endif
4343         return result;
4344     }
4345 }
4346
4347 OCStackResult
4348 OCNotifyListOfObservers (OCResourceHandle handle,
4349                          OCObservationId  *obsIdList,
4350                          uint8_t          numberOfIds,
4351                          const OCRepPayload       *payload,
4352                          OCQualityOfService qos)
4353 {
4354     OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4355
4356     OCResource *resPtr = NULL;
4357     //TODO: we should allow the server to define this
4358     uint32_t maxAge = MAX_OBSERVE_AGE;
4359
4360     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4361     VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4362     VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4363
4364     resPtr = findResource ((OCResource *) handle);
4365     if (NULL == resPtr || myStackMode == OC_CLIENT)
4366     {
4367         return OC_STACK_NO_RESOURCE;
4368     }
4369     else
4370     {
4371         incrementSequenceNumber(resPtr);
4372     }
4373     return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4374             payload, maxAge, qos));
4375 }
4376
4377 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4378 {
4379     OIC_TRACE_BEGIN(%s:OCDoResponse, TAG);
4380     OCStackResult result = OC_STACK_ERROR;
4381     OCServerRequest *serverRequest = NULL;
4382
4383     OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4384
4385     // Validate input parameters
4386     VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4387     VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4388
4389     // Normal response
4390     // Get pointer to request info
4391     serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
4392     if(serverRequest)
4393     {
4394         // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4395         result = serverRequest->ehResponseHandler(ehResponse);
4396     }
4397
4398     OIC_TRACE_END();
4399     return result;
4400 }
4401
4402 //#ifdef DIRECT_PAIRING
4403 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4404 {
4405     OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4406     if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4407     {
4408         OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4409         return NULL;
4410     }
4411
4412     return (const OCDPDev_t*)DPGetDiscoveredDevices();
4413 }
4414
4415 const OCDPDev_t* OCGetDirectPairedDevices()
4416 {
4417     return (const OCDPDev_t*)DPGetPairedDevices();
4418 }
4419
4420 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4421                                                      OCDirectPairingCB resultCallback)
4422 {
4423     OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4424     if(NULL ==  peer || NULL == pinNumber)
4425     {
4426         OIC_LOG(ERROR, TAG, "Invalid parameters");
4427         return OC_STACK_INVALID_PARAM;
4428     }
4429     if (NULL == resultCallback)
4430     {
4431         OIC_LOG(ERROR, TAG, "Invalid callback");
4432         return OC_STACK_INVALID_CALLBACK;
4433     }
4434
4435     return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4436                                            pinNumber, (OCDirectPairingResultCB)resultCallback);
4437 }
4438 //#endif // DIRECT_PAIRING
4439
4440 //-----------------------------------------------------------------------------
4441 // Private internal function definitions
4442 //-----------------------------------------------------------------------------
4443 static OCDoHandle GenerateInvocationHandle()
4444 {
4445     OCDoHandle handle = NULL;
4446     // Generate token here, it will be deleted when the transaction is deleted
4447     handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4448     if (handle)
4449     {
4450         OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4451     }
4452
4453     return handle;
4454 }
4455
4456 #ifdef WITH_PRESENCE
4457 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4458         OCResourceProperty resourceProperties, uint8_t enable)
4459 {
4460     if (!inputProperty)
4461     {
4462         return OC_STACK_INVALID_PARAM;
4463     }
4464     if (resourceProperties
4465             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4466     {
4467         OIC_LOG(ERROR, TAG, "Invalid property");
4468         return OC_STACK_INVALID_PARAM;
4469     }
4470     if(!enable)
4471     {
4472         *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4473     }
4474     else
4475     {
4476         *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4477     }
4478     return OC_STACK_OK;
4479 }
4480 #endif
4481
4482 OCStackResult initResources()
4483 {
4484     OCStackResult result = OC_STACK_OK;
4485
4486     headResource = NULL;
4487     tailResource = NULL;
4488     // Init Virtual Resources
4489 #ifdef WITH_PRESENCE
4490     presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4491
4492     result = OCCreateResource(&presenceResource.handle,
4493             OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4494             "core.r",
4495             OC_RSRVD_PRESENCE_URI,
4496             NULL,
4497             NULL,
4498             OC_OBSERVABLE);
4499     //make resource inactive
4500     result = OCChangeResourceProperty(
4501             &(((OCResource *) presenceResource.handle)->resourceProperties),
4502             OC_ACTIVE, 0);
4503 #endif
4504 #ifndef WITH_ARDUINO
4505     if (result == OC_STACK_OK)
4506     {
4507         result = SRMInitSecureResources();
4508     }
4509 #endif
4510
4511     if(result == OC_STACK_OK)
4512     {
4513         CreateResetProfile();
4514         result = OCCreateResource(&deviceResource,
4515                                   OC_RSRVD_RESOURCE_TYPE_DEVICE,
4516                                   OC_RSRVD_INTERFACE_DEFAULT,
4517                                   OC_RSRVD_DEVICE_URI,
4518                                   NULL,
4519                                   NULL,
4520                                   OC_DISCOVERABLE);
4521         if(result == OC_STACK_OK)
4522         {
4523             result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4524                                                      OC_RSRVD_INTERFACE_READ);
4525         }
4526     }
4527
4528     if(result == OC_STACK_OK)
4529     {
4530         result = OCCreateResource(&platformResource,
4531                                   OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4532                                   OC_RSRVD_INTERFACE_DEFAULT,
4533                                   OC_RSRVD_PLATFORM_URI,
4534                                   NULL,
4535                                   NULL,
4536                                   OC_DISCOVERABLE);
4537         if(result == OC_STACK_OK)
4538         {
4539             result = BindResourceInterfaceToResource((OCResource *)platformResource,
4540                                                      OC_RSRVD_INTERFACE_READ);
4541         }
4542     }
4543
4544     return result;
4545 }
4546
4547 void insertResource(OCResource *resource)
4548 {
4549     if (!headResource)
4550     {
4551         headResource = resource;
4552         tailResource = resource;
4553     }
4554     else
4555     {
4556         tailResource->next = resource;
4557         tailResource = resource;
4558     }
4559     resource->next = NULL;
4560 }
4561
4562 OCResource *findResource(OCResource *resource)
4563 {
4564     OCResource *pointer = headResource;
4565
4566     while (pointer)
4567     {
4568         if (pointer == resource)
4569         {
4570             return resource;
4571         }
4572         pointer = pointer->next;
4573     }
4574     return NULL;
4575 }
4576
4577 void deleteAllResources()
4578 {
4579     OCResource *pointer = headResource;
4580     OCResource *temp = NULL;
4581
4582     while (pointer)
4583     {
4584         temp = pointer->next;
4585 #ifdef WITH_PRESENCE
4586         if (pointer != (OCResource *) presenceResource.handle)
4587         {
4588 #endif // WITH_PRESENCE
4589             deleteResource(pointer);
4590 #ifdef WITH_PRESENCE
4591         }
4592 #endif // WITH_PRESENCE
4593         pointer = temp;
4594     }
4595     memset(&platformResource, 0, sizeof(platformResource));
4596     memset(&deviceResource, 0, sizeof(deviceResource));
4597 #ifdef MQ_BROKER
4598     memset(&brokerResource, 0, sizeof(brokerResource));
4599 #endif
4600
4601     SRMDeInitSecureResources();
4602
4603 #ifdef WITH_PRESENCE
4604     // Ensure that the last resource to be deleted is the presence resource. This allows for all
4605     // presence notification attributed to their deletion to be processed.
4606     deleteResource((OCResource *) presenceResource.handle);
4607     memset(&presenceResource, 0, sizeof(presenceResource));
4608 #endif // WITH_PRESENCE
4609 }
4610
4611 OCStackResult deleteResource(OCResource *resource)
4612 {
4613     OCResource *prev = NULL;
4614     OCResource *temp = NULL;
4615     if(!resource)
4616     {
4617         OIC_LOG(DEBUG,TAG,"resource is NULL");
4618         return OC_STACK_INVALID_PARAM;
4619     }
4620
4621     OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4622
4623     temp = headResource;
4624     while (temp)
4625     {
4626         if (temp == resource)
4627         {
4628             // Invalidate all Resource Properties.
4629             resource->resourceProperties = (OCResourceProperty) 0;
4630 #ifdef WITH_PRESENCE
4631             if(resource != (OCResource *) presenceResource.handle)
4632             {
4633 #endif // WITH_PRESENCE
4634                 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4635 #ifdef WITH_PRESENCE
4636             }
4637
4638             if(presenceResource.handle)
4639             {
4640                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4641                 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4642             }
4643 #endif
4644             // Only resource in list.
4645             if (temp == headResource && temp == tailResource)
4646             {
4647                 headResource = NULL;
4648                 tailResource = NULL;
4649             }
4650             // Deleting head.
4651             else if (temp == headResource)
4652             {
4653                 headResource = temp->next;
4654             }
4655             // Deleting tail.
4656             else if (temp == tailResource && prev)
4657             {
4658                 tailResource = prev;
4659                 tailResource->next = NULL;
4660             }
4661             else if (prev)
4662             {
4663                 prev->next = temp->next;
4664             }
4665
4666             deleteResourceElements(temp);
4667             OICFree(temp);
4668             return OC_STACK_OK;
4669         }
4670         else
4671         {
4672             prev = temp;
4673             temp = temp->next;
4674         }
4675     }
4676
4677     return OC_STACK_ERROR;
4678 }
4679
4680 void deleteResourceElements(OCResource *resource)
4681 {
4682     if (!resource)
4683     {
4684         return;
4685     }
4686
4687     if (resource->uri)
4688     {
4689         OICFree(resource->uri);
4690         resource->uri = NULL;
4691     }
4692     if (resource->rsrcType)
4693     {
4694         deleteResourceType(resource->rsrcType);
4695         resource->rsrcType = NULL;
4696     }
4697     if (resource->rsrcInterface)
4698     {
4699         deleteResourceInterface(resource->rsrcInterface);
4700         resource->rsrcInterface = NULL;
4701     }
4702     if (resource->rsrcChildResourcesHead)
4703     {
4704         unbindChildResources(resource->rsrcChildResourcesHead);
4705         resource->rsrcChildResourcesHead = NULL;
4706     }
4707     if (resource->rsrcAttributes)
4708     {
4709         OCDeleteResourceAttributes(resource->rsrcAttributes);
4710         resource->rsrcAttributes = NULL;
4711     }
4712     resource = NULL;
4713 }
4714
4715 void deleteResourceType(OCResourceType *resourceType)
4716 {
4717     OCResourceType *next = NULL;
4718
4719     for (OCResourceType *pointer = resourceType; pointer; pointer = next)
4720     {
4721         next = pointer->next ? pointer->next : NULL;
4722         if (pointer->resourcetypename)
4723         {
4724             OICFree(pointer->resourcetypename);
4725             pointer->resourcetypename = NULL;
4726         }
4727         OICFree(pointer);
4728     }
4729 }
4730
4731 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4732 {
4733     OCResourceInterface *next = NULL;
4734     for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
4735     {
4736         next = pointer->next ? pointer->next : NULL;
4737         if (pointer->name)
4738         {
4739             OICFree(pointer->name);
4740             pointer->name = NULL;
4741         }
4742         OICFree(pointer);
4743     }
4744 }
4745
4746 void unbindChildResources(OCChildResource *head)
4747 {
4748     OCChildResource *next = NULL;
4749     for (OCChildResource *current = head; current; current = next)
4750     {
4751         next = current->next;
4752         OICFree(current);
4753     }
4754 }
4755
4756 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
4757 {
4758     OCAttribute *next = NULL;
4759     for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
4760     {
4761         next = pointer->next ? pointer->next : NULL;
4762         if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
4763         {
4764             OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
4765             pointer->attrValue = NULL;
4766         }
4767         else if (pointer->attrValue)
4768         {
4769             OICFree(pointer->attrValue);
4770             pointer->attrValue = NULL;
4771         }
4772         if (pointer->attrName)
4773         {
4774             OICFree(pointer->attrName);
4775             pointer->attrName = NULL;
4776         }
4777         OICFree(pointer);
4778     }
4779 }
4780
4781 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4782 {
4783     OCResourceType *pointer = NULL;
4784     OCResourceType *previous = NULL;
4785     if (!resource || !resourceType)
4786     {
4787         return;
4788     }
4789     // resource type list is empty.
4790     else if (!resource->rsrcType)
4791     {
4792         resource->rsrcType = resourceType;
4793     }
4794     else
4795     {
4796         pointer = resource->rsrcType;
4797
4798         while (pointer)
4799         {
4800             if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4801             {
4802                 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4803                 OICFree(resourceType->resourcetypename);
4804                 OICFree(resourceType);
4805                 return;
4806             }
4807             previous = pointer;
4808             pointer = pointer->next;
4809         }
4810
4811         if (previous)
4812         {
4813             previous->next = resourceType;
4814         }
4815     }
4816     resourceType->next = NULL;
4817
4818     OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4819 }
4820
4821 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4822 {
4823     OCResource *resource = NULL;
4824     OCResourceType *pointer = NULL;
4825
4826     // Find the specified resource
4827     resource = findResource((OCResource *) handle);
4828     if (!resource)
4829     {
4830         return NULL;
4831     }
4832
4833     // Make sure a resource has a resourcetype
4834     if (!resource->rsrcType)
4835     {
4836         return NULL;
4837     }
4838
4839     // Iterate through the list
4840     pointer = resource->rsrcType;
4841     for(uint8_t i = 0; i< index && pointer; ++i)
4842     {
4843         pointer = pointer->next;
4844     }
4845     return pointer;
4846 }
4847
4848 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4849 {
4850     if(resourceTypeList && resourceTypeName)
4851     {
4852         OCResourceType * rtPointer = resourceTypeList;
4853         while(resourceTypeName && rtPointer)
4854         {
4855             OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4856             if(rtPointer->resourcetypename &&
4857                     strcmp(resourceTypeName, (const char *)
4858                     (rtPointer->resourcetypename)) == 0)
4859             {
4860                 break;
4861             }
4862             rtPointer = rtPointer->next;
4863         }
4864         return rtPointer;
4865     }
4866     return NULL;
4867 }
4868
4869 /*
4870  * Insert a new interface into interface linked list only if not already present.
4871  * If alredy present, 2nd arg is free'd.
4872  * Default interface will always be first if present.
4873  */
4874 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4875 {
4876     OCResourceInterface *pointer = NULL;
4877     OCResourceInterface *previous = NULL;
4878
4879     newInterface->next = NULL;
4880
4881     OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4882
4883     if (!*firstInterface)
4884     {
4885         // If first interface is not oic.if.baseline, by default add it as first interface type.
4886         if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4887         {
4888             *firstInterface = newInterface;
4889         }
4890         else
4891         {
4892             OCStackResult result = BindResourceInterfaceToResource(resource,
4893                                                                     OC_RSRVD_INTERFACE_DEFAULT);
4894             if (result != OC_STACK_OK)
4895             {
4896                 OICFree(newInterface->name);
4897                 OICFree(newInterface);
4898                 return;
4899             }
4900             if (*firstInterface)
4901             {
4902                 (*firstInterface)->next = newInterface;
4903             }
4904         }
4905     }
4906     // If once add oic.if.baseline, later too below code take care of freeing memory.
4907     else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4908     {
4909         if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4910         {
4911             OICFree(newInterface->name);
4912             OICFree(newInterface);
4913             return;
4914         }
4915         // This code will not hit anymore, keeping
4916         else
4917         {
4918             newInterface->next = *firstInterface;
4919             *firstInterface = newInterface;
4920         }
4921     }
4922     else
4923     {
4924         pointer = *firstInterface;
4925         while (pointer)
4926         {
4927             if (strcmp(newInterface->name, pointer->name) == 0)
4928             {
4929                 OICFree(newInterface->name);
4930                 OICFree(newInterface);
4931                 return;
4932             }
4933             previous = pointer;
4934             pointer = pointer->next;
4935         }
4936
4937         if (previous)
4938         {
4939             previous->next = newInterface;
4940         }
4941     }
4942 }
4943
4944 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4945         uint8_t index)
4946 {
4947     OCResource *resource = NULL;
4948     OCResourceInterface *pointer = NULL;
4949
4950     // Find the specified resource
4951     resource = findResource((OCResource *) handle);
4952     if (!resource)
4953     {
4954         return NULL;
4955     }
4956
4957     // Make sure a resource has a resourceinterface
4958     if (!resource->rsrcInterface)
4959     {
4960         return NULL;
4961     }
4962
4963     // Iterate through the list
4964     pointer = resource->rsrcInterface;
4965
4966     for (uint8_t i = 0; i < index && pointer; ++i)
4967     {
4968         pointer = pointer->next;
4969     }
4970     return pointer;
4971 }
4972
4973 /*
4974  * This function splits the uri using the '?' delimiter.
4975  * "uriWithoutQuery" is the block of characters between the beginning
4976  * till the delimiter or '\0' which ever comes first.
4977  * "query" is whatever is to the right of the delimiter if present.
4978  * No delimiter sets the query to NULL.
4979  * If either are present, they will be malloc'ed into the params 2, 3.
4980  * The first param, *uri is left untouched.
4981
4982  * NOTE: This function does not account for whitespace at the end of the uri NOR
4983  *       malformed uri's with '??'. Whitespace at the end will be assumed to be
4984  *       part of the query.
4985  */
4986 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4987 {
4988     if(!uri)
4989     {
4990         return OC_STACK_INVALID_URI;
4991     }
4992     if(!query || !uriWithoutQuery)
4993     {
4994         return OC_STACK_INVALID_PARAM;
4995     }
4996
4997     *query           = NULL;
4998     *uriWithoutQuery = NULL;
4999
5000     size_t uriWithoutQueryLen = 0;
5001     size_t queryLen = 0;
5002     size_t uriLen = strlen(uri);
5003
5004     char *pointerToDelimiter = strstr(uri, "?");
5005
5006     uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
5007     queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
5008
5009     if (uriWithoutQueryLen)
5010     {
5011         *uriWithoutQuery =  (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
5012         if (!*uriWithoutQuery)
5013         {
5014             goto exit;
5015         }
5016         OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
5017     }
5018     if (queryLen)
5019     {
5020         *query = (char *) OICCalloc(queryLen + 1, 1);
5021         if (!*query)
5022         {
5023             OICFree(*uriWithoutQuery);
5024             *uriWithoutQuery = NULL;
5025             goto exit;
5026         }
5027         OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5028     }
5029
5030     return OC_STACK_OK;
5031
5032     exit:
5033         return OC_STACK_NO_MEMORY;
5034 }
5035
5036 const char* OCGetServerInstanceIDString(void)
5037 {
5038     static char sidStr[UUID_STRING_SIZE];
5039     OicUuid_t sid;
5040     if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5041     {
5042         OIC_LOG(FATAL, TAG, "GetDoxmDeviceID failed!");
5043         return NULL;
5044     }
5045
5046     if (OCConvertUuidToString(sid.id, sidStr) != RAND_UUID_OK)
5047     {
5048         OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5049         return NULL;
5050     }
5051
5052     return sidStr;
5053 }
5054
5055 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5056 {
5057     OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5058     CAResult_t retResult = CA_STATUS_FAILED;
5059     CAResult_t caResult = CA_STATUS_OK;
5060
5061     CATransportAdapter_t connTypes[] = {
5062             CA_ADAPTER_IP,
5063             CA_ADAPTER_RFCOMM_BTEDR,
5064             CA_ADAPTER_GATT_BTLE,
5065             CA_ADAPTER_NFC
5066 #ifdef RA_ADAPTER
5067             ,CA_ADAPTER_REMOTE_ACCESS
5068 #endif
5069
5070 #ifdef TCP_ADAPTER
5071             ,CA_ADAPTER_TCP
5072 #endif
5073         };
5074     int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5075
5076     for(int i = 0; i < numConnTypes; i++)
5077     {
5078         // If CA status is not initialized, CASelectNetwork() will not be called.
5079         if (caResult != CA_STATUS_NOT_INITIALIZED)
5080         {
5081             if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5082             {
5083                 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5084                 caResult = CASelectNetwork(connTypes[i]);
5085                 if (caResult == CA_STATUS_OK)
5086                 {
5087                     retResult = CA_STATUS_OK;
5088                 }
5089             }
5090             else
5091             {
5092                 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5093             }
5094         }
5095     }
5096
5097     if (retResult != CA_STATUS_OK)
5098     {
5099         return caResult; // Returns error of appropriate transport that failed fatally.
5100     }
5101
5102     return retResult;
5103 }
5104
5105 OCStackResult CAResultToOCResult(CAResult_t caResult)
5106 {
5107     switch (caResult)
5108     {
5109         case CA_STATUS_OK:
5110             return OC_STACK_OK;
5111         case CA_STATUS_INVALID_PARAM:
5112             return OC_STACK_INVALID_PARAM;
5113         case CA_ADAPTER_NOT_ENABLED:
5114             return OC_STACK_ADAPTER_NOT_ENABLED;
5115         case CA_SERVER_STARTED_ALREADY:
5116             return OC_STACK_OK;
5117         case CA_SERVER_NOT_STARTED:
5118             return OC_STACK_ERROR;
5119         case CA_DESTINATION_NOT_REACHABLE:
5120             return OC_STACK_COMM_ERROR;
5121         case CA_SOCKET_OPERATION_FAILED:
5122             return OC_STACK_COMM_ERROR;
5123         case CA_SEND_FAILED:
5124             return OC_STACK_COMM_ERROR;
5125         case CA_RECEIVE_FAILED:
5126             return OC_STACK_COMM_ERROR;
5127         case CA_MEMORY_ALLOC_FAILED:
5128             return OC_STACK_NO_MEMORY;
5129         case CA_REQUEST_TIMEOUT:
5130             return OC_STACK_TIMEOUT;
5131         case CA_DESTINATION_DISCONNECTED:
5132             return OC_STACK_COMM_ERROR;
5133         case CA_STATUS_FAILED:
5134             return OC_STACK_ERROR;
5135         case CA_NOT_SUPPORTED:
5136             return OC_STACK_NOTIMPL;
5137         default:
5138             return OC_STACK_ERROR;
5139     }
5140 }
5141
5142 bool OCResultToSuccess(OCStackResult ocResult)
5143 {
5144     switch (ocResult)
5145     {
5146         case OC_STACK_OK:
5147         case OC_STACK_RESOURCE_CREATED:
5148         case OC_STACK_RESOURCE_DELETED:
5149         case OC_STACK_CONTINUE:
5150         case OC_STACK_RESOURCE_CHANGED:
5151         case OC_STACK_SLOW_RESOURCE:
5152             return true;
5153         default:
5154             return false;
5155     }
5156 }
5157
5158 #ifdef WITH_CHPROXY
5159 OCStackResult OCSetProxyURI(const char *uri)
5160 {
5161     return CAResultToOCResult(CASetProxyUri(uri));
5162 }
5163 #endif
5164
5165 #if defined(RD_CLIENT) || defined(RD_SERVER)
5166 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5167 {
5168     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5169
5170     OCResource *resource = NULL;
5171
5172     resource = findResource((OCResource *) handle);
5173     if (!resource)
5174     {
5175         OIC_LOG(ERROR, TAG, "Resource not found");
5176         return OC_STACK_ERROR;
5177     }
5178
5179     resource->ins = ins;
5180
5181     return OC_STACK_OK;
5182 }
5183
5184
5185 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5186                                               const OCClientResponse *response)
5187 {
5188     // Validate input parameters
5189     VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5190     VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5191
5192     char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5193     if (!targetUri)
5194     {
5195         return OC_STACK_NO_MEMORY;
5196     }
5197     strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5198
5199     if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5200     {
5201         OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5202
5203         char rdPubUri[MAX_URI_LENGTH] = { 0 };
5204         snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5205                  OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5206
5207         if (strcmp(rdPubUri, targetUri) == 0)
5208         {
5209             // Update resource unique id in stack.
5210             if (response)
5211             {
5212                 if (response->payload)
5213                 {
5214                     OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5215                     OCRepPayload **links = NULL;
5216                     size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5217                     if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5218                                                        &links, dimensions))
5219                     {
5220                         size_t i = 0;
5221                         for (; i < dimensions[0]; i++)
5222                         {
5223                             char *uri = NULL;
5224                             if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5225                             {
5226                                 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5227                                 int64_t ins = 0;
5228                                 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5229                                 {
5230                                     OCBindResourceInsToResource(handle, ins);
5231                                 }
5232
5233                                 OICFree(uri);
5234                                 uri = NULL;
5235                             }
5236                         }
5237
5238                         // Free links
5239                         size_t count = calcDimTotal(dimensions);
5240                         for (size_t k = 0; k < count; k++)
5241                         {
5242                             OCRepPayloadDestroy(links[k]);
5243                         }
5244                         OICFree(links);
5245                     }
5246                 }
5247             }
5248         }
5249     }
5250     else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5251     {
5252         OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5253
5254         uint8_t numResources = 0;
5255         OCGetNumberOfResources(&numResources);
5256
5257         char *ins = strstr(targetUri, OC_RSRVD_INS);
5258         if (!ins)
5259         {
5260             for (uint8_t i = 0; i < numResources; i++)
5261             {
5262                 OCResourceHandle resHandle = OCGetResourceHandle(i);
5263                 if (resHandle)
5264                 {
5265                     OCBindResourceInsToResource(resHandle, 0);
5266                 }
5267             }
5268         }
5269         else
5270         {
5271             const char *token = "&";
5272             char *iterTokenPtr = NULL;
5273             char *start = strtok_r(targetUri, token, &iterTokenPtr);
5274
5275              while (start != NULL)
5276              {
5277                  char *query = start;
5278                  query = strstr(query, OC_RSRVD_INS);
5279                  if (query)
5280                  {
5281                      int64_t queryIns = atoi(query + 4);
5282                      for (uint8_t i = 0; i < numResources; i++)
5283                      {
5284                          OCResourceHandle resHandle = OCGetResourceHandle(i);
5285                          if (resHandle)
5286                          {
5287                              int64_t resIns = 0;
5288                              OCGetResourceIns(resHandle, &resIns);
5289                              if (queryIns && queryIns == resIns)
5290                              {
5291                                  OCBindResourceInsToResource(resHandle, 0);
5292                                  break;
5293                              }
5294                          }
5295                      }
5296                  }
5297                  start = strtok_r(NULL, token, &iterTokenPtr);
5298              }
5299         }
5300     }
5301
5302     OICFree(targetUri);
5303     return OC_STACK_OK;
5304 }
5305
5306 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5307 {
5308     if (!uri)
5309     {
5310         OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5311         return NULL;
5312     }
5313
5314     OCResource *pointer = headResource;
5315
5316     while (pointer)
5317     {
5318         if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5319         {
5320             OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5321             return pointer;
5322         }
5323         pointer = pointer->next;
5324     }
5325     return NULL;
5326 }
5327
5328 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t *ins)
5329 {
5330     OCResource *resource = NULL;
5331
5332     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5333     VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5334
5335     resource = findResource((OCResource *) handle);
5336     if (resource)
5337     {
5338         *ins = resource->ins;
5339         return OC_STACK_OK;
5340     }
5341     return OC_STACK_ERROR;
5342 }
5343 #endif
5344
5345 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5346                                 const void* optionData, size_t optionDataLength)
5347 {
5348     if (!ocHdrOpt)
5349     {
5350         OIC_LOG (INFO, TAG, "Header options are NULL");
5351         return OC_STACK_INVALID_PARAM;
5352     }
5353
5354     if (!optionData)
5355     {
5356         OIC_LOG (INFO, TAG, "optionData are NULL");
5357         return OC_STACK_INVALID_PARAM;
5358     }
5359
5360     if (!numOptions)
5361     {
5362         OIC_LOG (INFO, TAG, "numOptions is NULL");
5363         return OC_STACK_INVALID_PARAM;
5364     }
5365
5366     if (*numOptions >= MAX_HEADER_OPTIONS)
5367     {
5368         OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5369         return OC_STACK_NO_MEMORY;
5370     }
5371
5372     ocHdrOpt += *numOptions;
5373     ocHdrOpt->protocolID = OC_COAP_ID;
5374     ocHdrOpt->optionID = optionID;
5375     ocHdrOpt->optionLength =
5376             optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
5377                     optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5378     memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5379     *numOptions += 1;
5380
5381     return OC_STACK_OK;
5382 }
5383
5384 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5385                                 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5386 {
5387     if (!ocHdrOpt || !numOptions)
5388     {
5389         OIC_LOG (INFO, TAG, "No options present");
5390         return OC_STACK_OK;
5391     }
5392
5393     if (!optionData)
5394     {
5395         OIC_LOG (INFO, TAG, "optionData are NULL");
5396         return OC_STACK_INVALID_PARAM;
5397     }
5398
5399     if (!receivedDataLength)
5400     {
5401         OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5402         return OC_STACK_INVALID_PARAM;
5403     }
5404
5405     for (uint8_t i = 0; i < numOptions; i++)
5406     {
5407         if (ocHdrOpt[i].optionID == optionID)
5408         {
5409             if (optionDataLength >= ocHdrOpt->optionLength)
5410             {
5411                 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5412                 *receivedDataLength = ocHdrOpt->optionLength;
5413                 return OC_STACK_OK;
5414             }
5415             else
5416             {
5417                 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5418                 return OC_STACK_ERROR;
5419             }
5420         }
5421     }
5422     return OC_STACK_OK;
5423 }
5424
5425 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5426 {
5427     OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5428     if (g_adapterHandler)
5429     {
5430         g_adapterHandler(adapter, enabled);
5431     }
5432 }
5433
5434 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5435 {
5436     OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5437     if (g_connectionHandler)
5438     {
5439        g_connectionHandler(info, isConnected);
5440     }
5441
5442     /*
5443      * If the client observes one or more resources over a reliable connection,
5444      * then the CoAP server (or intermediary in the role of the CoAP server)
5445      * MUST remove all entries associated with the client endpoint from the lists
5446      * of observers when the connection is either closed or times out.
5447      */
5448     if (!isConnected)
5449     {
5450         OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5451         CopyEndpointToDevAddr(info, &devAddr);
5452
5453         // remove observer list with remote device address.
5454         DeleteObserverUsingDevAddr(&devAddr);
5455     }
5456 }
5457
5458 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5459 {
5460     OicUuid_t oicUuid;
5461     OCStackResult ret = OC_STACK_ERROR;
5462
5463     ret = GetDoxmDeviceID(&oicUuid);
5464     if (OC_STACK_OK == ret)
5465     {
5466         memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5467     }
5468     else
5469     {
5470         OIC_LOG(ERROR, TAG, "Device ID Get error");
5471     }
5472     return ret;
5473 }
5474
5475 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5476 {
5477     OicUuid_t oicUuid;
5478     OCStackResult ret = OC_STACK_ERROR;
5479
5480     memcpy(&oicUuid, deviceId, UUID_LENGTH);
5481     for (int i = 0; i < UUID_LENGTH; i++)
5482     {
5483         OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5484     }
5485     ret = SetDoxmDeviceID(&oicUuid);
5486     return ret;
5487 }
5488
5489 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5490 {
5491     bool isDeviceOwned = true;
5492     OCStackResult ret = OC_STACK_ERROR;
5493
5494     ret = GetDoxmIsOwned(&isDeviceOwned);
5495     if (OC_STACK_OK == ret)
5496     {
5497         *isOwned = isDeviceOwned;
5498     }
5499     else
5500     {
5501         OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5502     }
5503     return ret;
5504 }
5505
5506 void OCClearCallBackList()
5507 {
5508     DeleteClientCBList();
5509 }
5510
5511 void OCClearObserverlist()
5512 {
5513     DeleteObserverList();
5514 }
5515
5516 int OCEncrypt(const unsigned char *pt, size_t pt_len,
5517         unsigned char **ct, size_t *ct_len)
5518 {
5519 #ifndef __SECURE_PSI__
5520     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5521     return 0;
5522 #else
5523     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5524
5525     return psiEncrypt(pt, pt_len, ct, ct_len);
5526 #endif // __SECURE_PSI__
5527 }
5528
5529 int OCDecrypt(const unsigned char *ct, size_t ct_len,
5530         unsigned char **pt, size_t *pt_len)
5531 {
5532 #ifndef __SECURE_PSI__
5533     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5534     return 0;
5535 #else
5536     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5537
5538     return psiDecrypt(ct, ct_len, pt, pt_len);
5539 #endif // __SECURE_PSI__
5540 }
5541
5542 OCStackResult OCSetKey(const unsigned char* key)
5543 {
5544 #ifndef __SECURE_PSI__
5545     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5546     return OC_STACK_OK;
5547 #else
5548     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5549
5550     return psiSetKey(key);
5551 #endif // __SECURE_PSI__
5552 }
5553
5554 OCStackResult OCGetKey(unsigned char* key)
5555 {
5556 #ifndef __SECURE_PSI__
5557     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5558     return OC_STACK_OK;
5559 #else
5560     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5561
5562     return psiGetKey(key);
5563 #endif // __SECURE_PSI__
5564 }
5565
5566 OCStackResult OCSetSecurePSI(const unsigned char *key, const OCPersistentStorage *psPlain,
5567         const OCPersistentStorage *psEnc, const OCPersistentStorage *psRescue)
5568 {
5569 #ifndef __SECURE_PSI__
5570     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5571     return OC_STACK_OK;
5572 #else
5573     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5574
5575     return setSecurePSI(key, psPlain, psEnc, psRescue);
5576 #endif // __SECURE_PSI__
5577 }
5578
5579 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5580 static void OtmEventHandler(const char *addr, uint16_t port, const char *uuid, int event)
5581 {
5582     if (g_otmEventHandler.cb)
5583     {
5584         g_otmEventHandler.cb(g_otmEventHandler.ctx, addr, port, uuid, event);
5585     }
5586 }
5587
5588 /* TODO Work-around
5589  * It is already declared in srmutility.h.
5590  * We can't include the header file, because of "redefined VERIFY_NON_NULL"
5591  */
5592 typedef void (*OicSecOtmEventHandler_t)(const char* addr, uint16_t port,
5593         const char* uuid, int event);
5594 void SetOtmEventHandler(OicSecOtmEventHandler_t otmEventHandler);
5595 #endif
5596
5597 OCStackResult OCSetOtmEventHandler(void *ctx, OCOtmEventHandler cb)
5598 {
5599 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5600     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5601
5602     g_otmEventHandler.cb = cb;
5603     g_otmEventHandler.ctx = ctx;
5604
5605     if (g_otmEventHandler.cb)
5606     {
5607         OIC_LOG(DEBUG, TAG, "SET OCOtmEventHandler");
5608         SetOtmEventHandler(OtmEventHandler);
5609     }
5610     else
5611     {
5612         OIC_LOG(DEBUG, TAG, "UNSET OCOtmEventHandler");
5613         SetOtmEventHandler(NULL);
5614     }
5615 #else
5616     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5617     OC_UNUSED(ctx);
5618     OC_UNUSED(cb);
5619 #endif
5620     return OC_STACK_OK;
5621 }