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