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